#!/bin/bash

elegant run.ele

nw=`ls run-*.w1 | wc -l`
echo "Processing $nw data files..."

sddscombine run-00*.w1 -pipe=out -merge \
    | sddsprocess -pipe -process=?,min,%sMin -process=?,max,%sMax \
    | sddscollapse -pipe=in stats.sdds

xmin=`sdds2stream -column=xMin stats.sdds`
ymin=`sdds2stream -column=yMin stats.sdds`
xmax=`sdds2stream -column=xMax stats.sdds`
ymax=`sdds2stream -column=yMax stats.sdds`

xmin=`rpnl $xmin 1e3 mult`
xmax=`rpnl $xmax 1e3 mult`
ymin=`rpnl $ymin 1e3 mult`
ymax=`rpnl $ymax 1e3 mult`

xrange=`rpnl $xmax $xmin -`
yrange=`rpnl $ymax $ymin -`

sddscombine run-00*.w1 -pipe=out \
    | sddsprocess -pipe -convert=col,x,mm,m,1e3 \
    | sddshist -pipe=in run.xhis -bins=100 -lower=$xmin -upper=$xmax -data=x

sddscombine run-00*.w1 -pipe=out \
    | sddsprocess -pipe -convert=col,y,mm,m,1e3 \
    | sddshist -pipe=in run.yhis -bins=100 -lower=$ymin -upper=$ymax -data=y

sddsprocess run.mag run.mag-xscaled -redefine=col,Profile,"Profile $xrange * .05 * $xmin + $xrange .1 * +"
sddsprocess run.mag run.mag-yscaled -redefine=col,Profile,"Profile $yrange * .05 * $ymin + $yrange .1 * +"

sddscontour -shade -waterfall=parameter=s,indep=x,color=frequency run.xhis -shape=run.mag-xscaled,s,Profile -title= -topline= \
    -ylabel='x (mm)' 
sddscontour -shade -waterfall=parameter=s,indep=y,color=frequency run.yhis -shape=run.mag-yscaled,s,Profile -title= -topline= \
    -ylabel='y (mm)' 

sddsplot -ylabel='Rms beam size (mm)' -factor=ym=1e3 -title= \
    -graph=line,vary -unsup=y -col=s,Profile run.mag -overlay=yfactor=0.05,xmode=norm -column=s,S[xy] run.sig -legend 


sddscontour -device=lpng,onwhite -output=xmap.png \
    -shade -waterfall=parameter=s,indep=x,color=frequency run.xhis -shape=run.mag-xscaled,s,Profile -title= -topline= \
    -ylabel='x (mm)' 
sddscontour -device=lpng,onwhite -output=ymap.png \
    -shade -waterfall=parameter=s,indep=y,color=frequency run.yhis -shape=run.mag-yscaled,s,Profile -title= -topline= \
    -ylabel='y (mm)' 

sddsplot -device=lpng,onwhite -output=xyrms.png \
    -ylabel='Rms beam size (mm)' -factor=ym=1e3 -title= \
    -graph=line,vary -unsup=y -col=s,Profile run.mag -overlay=yfactor=0.05,xmode=norm -column=s,S[xy] run.sig -legend 
