#!/bin/csh
set nonomatch

#
# astra2elegant:
# converts ASTRA phase space output to elegant input
# M. Borland, ANL/APS
#
# 7/28/2009: corrected two problems (M. Borland)
# 1. Was using p instead of pz to compute time from z position.
# 2. Wasn't transforming x and y to account for drift to zReference.
#

if ($#argv != 2) then
    echo "Usage: astra2elegant <input> <output>"
    exit 1
endif

set input = $1
set output = $2

if ( ! -e $input ) then
    echo "Not found: $input"
    exit 1
endif
if ( -e $output ) then
    echo "In use: $output"
    exit 1
endif

plaindata2sdds $input -pipe=out \
    -inputMode=ascii -outputMode=binary -noRowCount \
    -column=x,double,units=m -column=y,double,units=m -column=z,double,units=m \
    -column=px,double,units=eV/c -column=py,double,units=eV/c -column=dpz,double,units=eV/c \
    -column=t,double,units=ns -column=q,double,units=nC -column=particleType,short \
    -column=status,short \
  | sddsprocess -pipe=in $output \
    -process=*,first,%sReference -clip=1,0 \
  "-define=column,pz,dpz dpzReference +,units=eV/c" \
  "-define=column,p,px sqr py sqr + pz sqr + sqrt mev / 1e6 /" \
  "-redefine=column,t0,t 1e9 / chs,units=s" \
  "-define=column,betaz,pz mev / 1e6 / p sqr 1 + sqrt /" \
  "-redefine=column,t,z betaz c_mks * 1e-16 + / chs tReference 1e9 / +,units=s" \
  "-define=column,xp,px pz 1e-18 + /" \
  "-define=column,yp,py pz 1e-18 + /" \
  "-redefine=column,x,x xp z * -,units=m" \
  "-redefine=column,y,y yp z * -,units=m" \
  -filter=column,particleType,0.5,1.5 \
  '-filter=column,status,4.5,5.5,status,-6.5,-0.5,|' \
  -convert=column,q,C,nC,1e-9 \
  "-process=q,sum,Charge"
