#!/bin/bash

ncores=`nproc`
if [ $ncores -gt 10 ] ; then
    # If more than 10 cores available, leave a few idle
    ncores=$((ncores-2))
fi

# Run linac 2 with an idealized gaussian beam
echo Running FCC_Linac2_bunch_0.ele on $ncores cores
mpiexec -np $ncores Pelegant FCC_Linac2_bunch_0.ele > FCC_Linac2_bunch_0.log

# Match the Linac1 beam to the initial conditions used in the "0" run
sddsmatchtwiss Linac1.out distr_matched.sdds \
               -xplane=filename=Linac2_0.twi,element=_BEG_ \
               -yplane=filename=Linac2_0.twi,element=_BEG_ 

# Verify the matching

sddsprocess Linac2_0.twi -pipe=out -clip=1,0,invert \
    | sddsprintout -pipe -column=beta? -column=alpha? -title="Nominal starting twiss functions"

# Note that the -correctedOnly option is needed to suppress spurious correlations with energy coordinates
sddsanalyzebeam distr_matched.sdds -pipe=out -correctedOnly \
    | sddsprintout -pipe -column=beta? -column=alpha? -title="Beam starting twiss functions"

# Run the matched beam through linac 2
echo Running FCC_Linac2_bunch.ele on $ncores cores
mpiexec -np $ncores Pelegant FCC_Linac2_bunch.ele > FCC_Linac2_bunch.log

# Plot the nominal twiss functions along with the beam-derived values
sddsplot -legend=file -graph=line,vary -col=s,betax Linac2*.twi -col=s,betaxBeam Linac2*.sig 
sddsplot -legend=file -graph=line,vary -col=s,betay Linac2*.twi -col=s,betayBeam Linac2*.sig 
