#!/bin/bash  

rootname=beam-24x2

if [ -e $rootname.sdds ] ; then
   echo "in use: $rootname.sdds"
   exit 1
fi

if [ ! -e Basic.twi ] ; then
    echo "not found: Basic.twi"
    exit 1
fi

rfFrequency=`sddsprocess Basic.twi -pipe=out -process=s,max,sMax \
                        "-define=param,T0,sMax c_mks /,units=s" \
                        "-define=param,frf,T0 rec 1296 *,units=Hz" \
                        | sdds2stream -pipe -parameter=frf`

momentum=6e3
# Minimum acceptable with impedance is 30kP/bunch
nPerBunch=30000
harmonic=1296
nDoublets=24
doubletSpacing=4
pairFrequency=`rpnl $rfFrequency $harmonic / $nDoublets mult`
bunchFrequency=`rpnl $rfFrequency $doubletSpacing /`

elegant makeBunchTrain.ele -macro=momentum=$momentum,rootname=$rootname-s,nBunches=2,nPerBunch=$nPerBunch,bunchFrequency=$bunchFrequency,tOffset=0

if [ ! -e $rootname-s.done ] ; then
    echo "run to create double-bunch file failed."
    exit 1
fi

# For other doublets, offset the time coordinates by the pair spacing
fileList=$rootname-s.out
ib=1
while (( ib<nDoublets )) ; do
    echo "Working on pair $ib"
    offset=`rpnl $ib $pairFrequency /`
    sddsprocess $rootname-s.out $rootname-s.out$ib "-redefine=col,t,t $offset +,units=s"
    fileList="$fileList $rootname-s.out$ib"
    ib=$((ib+1))
done

echo "Combining all the beam files"
sddscombine $fileList -pipe=out -merge \
    | sddsprocess -pipe "-redefine=col,particleID,i_row 1 +,type=long" \
    | sddsbreak -pipe=in -rowlimit=$nPerBunch $rootname.sdds 
# Delete temporary files
\rm $fileList $rootname-s.done


# Make setup file for WATCH and HISTOGRAM elements to define the start and end particle ID for each
list1=""
list2=""
list3=""
startPID=1
endPID=$nPerBunch
nBunches=$((nDoublets*2))
echo "Making setup files for $nBunches histogram and watch elements"
while (( ie<nBunches )) ; do
    wpName=`printf "WP%02d" $ie`
    hName=`printf "H%02d" $ie`
    if [[ $list1 == "" ]] ; then
        list1="$wpName,$wpName,$hName,$hName"
        list2="START_PID,END_PID,START_PID,END_PID"
        list3="$startPID,$endPID,$startPID,$endPID"
    else
        list1="$list1,$wpName,$wpName,$hName,$hName"
        list2="$list2,START_PID,END_PID,START_PID,END_PID"
        list3="$list3,$startPID,$endPID,$startPID,$endPID"
    fi
    ie=$((ie+1))
    startPID=$((startPID+nPerBunch))
    endPID=$((endPID+nPerBunch))
done
sddsmakedataset $rootname.param \
    -column=ElementName,type=string -data=$list1 \
    -column=ElementParameter,type=string -data=$list2 \
    -column=ParameterValue,type=double -data=$list3

