#!/bin/bash

echo working

# Select initial coordinates of particles that eventually get lost
sddsselect FlatbeamInjection.bun FlatbeamInjection.lost -equate=particleID -pipe=out |\
 sddsbreak -pipe=in -rowlimit=1 initialCoordsLostParticles.sdds

# Track 10 of those particles to get the centroid vs s
elegant oneAtATime.ele 

sddsplot -col=Cx,Cxp oneAtATime.cen -split=page -sep=page -graph=dot

smax=`sddsprocess FlatbeamInjection.twi -pipe=out -process=s,max,%sMax | sdds2stream -pipe -parameter=sMax`
echo "smax = $smax"
np=`sdds2stream oneAtATime.cen -npage=bare`
echo $np pages
i=1
while [ $i -le $np ] ; do 
      echo page $i...
      # Each page of oneAtATime.cen corresponds to one particle.
      # 1. Filter for one page only
      # 2. Take data at quads only
      # 3. Define the turn number using the circumference
      # 4. Break into turns
      # 5. Define an index numbering the quadrupoles (locations of data)
      # 6. FFT vs the index gives the tune for each turn
      # 7. Plot it
      sddsconvert oneAtATime.cen -pipe=out -frompage=$i -topage=$i \
	  | sddsprocess -pipe -match=col,ElementType=*QUAD* \
	  "-define=col,Turn,s $smax / int,type=long" \
	  | sddsbreak -pipe -change=Turn \
	  | sddsprocess -pipe "-define=col,Index,i_row,type=long" \
	  -process=Turn,first,%s0 \
	  "-print=param,Label,Turn %.0f,Turn0" \
	  | sddsfft -pipe=in oneAtATime-$i.fft -column=Index,Cx,Cy  -nowarning
      sddsplot -column=f,FFTC? -graph=line,vary -split=page -group=page -sep=page -filename -title=@Label oneAtATime-$i.fft
      i=$((i+1))
done

