#!/bin/sh  
# \
exec oagtclsh "$0" "$@"

# $Log: plotTwiss,v $
# Revision 1.20  2012/05/13 03:15:00  borland
# Fixed bug in last version.
#
# Revision 1.19  2011/07/21 13:13:01  borland
# Can now use -rootname in place of -fileRoot.
#
# Revision 1.18  2010/08/05 13:29:09  borland
# Added optional use of OAG_TOP_DIR environment variable.
#
# Revision 1.17  2010/05/26 17:31:32  borland
# Added pause before exit to avoid errors when the temporary file is deleted
# before sddsplot finishes.
#
# Revision 1.16  2010/02/04 18:42:46  borland
# Improve plotting of apertures for multipage files.
#
# Revision 1.15  2010/01/27 01:59:50  borland
# Added plotting of apertures.
#
# Revision 1.14  2009/10/06 15:36:16  borland
# Really fixed the problem this time.
#
# Revision 1.13  2009/10/06 15:31:55  borland
# Fixed problems with effective emittance display that screwed up the mouse
# tracker.
#
# Revision 1.12  2007/10/29 21:52:25  emery
# Fixed tuneString parameter creation.
#
# Revision 1.11  2007/10/29 18:27:04  emery
# Fixed typo instroduced last time.
#
# Revision 1.10  2007/10/29 18:22:41  emery
# Added switch for presence of parameter EffectiveEmittancePresent, skipping
# an unnecessary sddsprocess.
#
# Revision 1.9  2007/03/05 05:33:25  emery
# Added noDispersion option
#
# Revision 1.8  2006/11/11 00:35:57  emery
# Added -thick 1 options for thicker lines. Not recommended for
# beamlines with lots of magnets or whole rings.
#
# Revision 1.7  2004/12/08 16:11:55  borland
# Now computes the correct effective emittance for each point in the lattice.
#
# Revision 1.6  2004/05/10 21:52:14  emery
# Added more complete error return string.
#
# Revision 1.5  2004/05/10 21:46:12  emery
# Fixed order of options across all plot commands.
#
# Revision 1.4  2004/05/10 21:37:06  emery
# Added ylabel scales of 1.4 for all plotting possibilities.
#
# Revision 1.3  2004/03/28 07:23:24  emery
# Changed the path for averageOverElement to none, so
# that the executable is searched in the default login paths.
#
# Revision 1.2  2004/01/08 20:28:10  borland
# Now displays effective emittance as a number in the topline slot.
# Note that using the topline option didn't work, apparently an sddsplot bug.
#
# Revision 1.1  2003/10/17 22:46:37  emery
# First installation.
#

if [info exists env(OAG_TOP_DIR)] {
    set auto_path [linsert $auto_path 0 $env(OAG_TOP_DIR)/oag/apps/lib/$env(HOST_ARCH)]
} else {
    set auto_path [linsert $auto_path 0 /usr/local/oag/apps/lib/$env(HOST_ARCH)]
}

APSStandardSetup

set usage "plotTwiss {-fileRoot <root> | -rootname <root>} \[-plotOptions\] \[-morePlotOptions\] \n\
      \[-printer <printer>\] \[-psFile <file>\] \[-pngFile <file>\] \n\
      \[-display <displayName>\] \[-noDisplay  \{0|1\} \n\
     \[-thick \{0|1\}\]"

set args $argv
set rootname ""
set fileRoot ""
set plotOptions ""
set morePlotOptions ""
set display ""
set noDisplay 0
set psFile ""
set printer ""
set pngFile ""
set thick 0
set noDispersion 0
APSParseArguments {rootname fileRoot noDispersion plotOptions morePlotOptions thick \
                     display noDisplay psFile \
                     pngFile printer}

if ![string length $fileRoot] {
    set fileRoot $rootname
}
if ![string length $fileRoot] {
    puts $usage
    exit
}
if ![file readable $fileRoot.twi] {
    if ![file readable $fileRoot] {
        puts "$argv0 in [pwd]: problem with file $fileRoot.twi."
        exit
    }
    puts "$argv0 in [pwd]: Problem with file $fileRoot.twi. Trying file $fileRoot ..."
    set file $fileRoot
    set fileRoot [file rootname $file]
} else {
    set file $fileRoot.twi
}

if ![file readable $fileRoot.mag] {
    puts "$argv0 in [pwd]: problem with file $fileRoot.mag"
    exit
}

set tmpFile /tmp/[APSTmpString].twi
# APSAddToTempFileList $tmpFile $tmpFile.1
set coupling 0.01
#check if radiation integrals are present
set integralsPresent 0
if {-1 < [lsearch [exec sddsquery -para $file] ex0]} {
    set integralsPresent 1
}
set effectiveEmittancePresent 0
if {-1 < [lsearch [exec sddsquery -para $file] EffectiveEmittancePresent]} {
    set effectiveEmittancePresent 1
}

if {$integralsPresent && !$effectiveEmittancePresent} {
    # if effective emittance and other columns are already present then we 
    # don't have to do the sddsprocess command.
    if [catch {exec sddsprocess $file $tmpFile -nowarning \
                 "-def=para,emitx,ex0,units=\$gp\$rm" \
                 "-def=para,emity,ex0 $coupling *,units=\$gp\$rm" \
                 "-def=col,gammax,alphax sqr 1 + betax /,units=1/m" \
                 "-def=col,gammay,alphay sqr 1 + betay /,units=1/m" \
                 "-def=col,Sigmax,emitx betax * etax Sdelta0 * sqr + sqrt 1e6 *,units=um" \
                 "-def=col,Sigmaxp,emitx gammax * etaxp Sdelta0 * sqr + sqrt 1e6 *,units=urad" \
                 "-def=col,Sxxp,Sdelta0 sqr etax * etaxp * alphax emitx * - 1e12 *,units=um-urad" \
                 "-def=col,Sigmay,emity betay * etay Sdelta0 * sqr + sqrt 1e6 *,units=um" \
                 "-def=col,Sigmayp,emity gammay * etayp Sdelta0 * sqr + sqrt 1e6 *,units=urad" \
                 "-def=col,EffectiveEmittance,Sigmax Sigmaxp * sqr Sxxp sqr - sqrt 1e3 /,units=nm-rad" \
                 -process=EffectiveEmittance,first,%s \
                 "-print=para,tuneString,nux: %7.4g  nuy: %7.4g,nux,nuy" \
                 -def=para,EffectiveEmittancePresent,1,type=long \
             } result ] {
        puts "$argv0 in [pwd]: $result"
    }
} else {
    if [catch {exec sddsprocess $file $tmpFile -nowarning \
                 "-redef=col,gammax,alphax sqr 1 + betax /,units=1/m" \
                 "-redef=col,gammay,alphay sqr 1 + betay /,units=1/m" \
                 "-reprint=para,tuneString,nux: %7.4g  nuy: %7.4g,nux,nuy" \
             } result ] {
        puts "$argv0 in [pwd]: $result"
    }
}
if [string length $display] {
    set displayOption "-display $display"
} else {
    set displayOption ""
}

#create file of average values
# APSAddToTempFileList $tmpFile.ave
if $integralsPresent {
    if [catch {exec averageOverElements -input $tmpFile \
                 -output ${tmpFile}.ave \
                 -itemList "betax betay etax gammax Sigmax Sigmaxp" \
             } result] {
        puts stderr "$argv0 in [pwd]: averageOverElements: $result"
        exit
    }
} else {
    if [catch {exec averageOverElements -input $tmpFile \
                 -output ${tmpFile}.ave \
                 -itemList "betax betay etax gammax" \
             } result] {
        puts stderr "$argv0 in [pwd]: averageOverElements: $result"
        exit
    }
}

# combine average values with end-point values
if $integralsPresent {
    exec sddsconvert ${tmpFile}.ave -pipe=out \
      -dele=col,s,beta?,etax,gammax,Sigmax,Sigmaxp \
      | sddsconvert -pipe=in ${tmpFile}.ave.1 \
      -edit=col,*Average,%/Average//
} else {
    exec sddsconvert ${tmpFile}.ave -pipe=out \
      -dele=col,s,beta?,etax,gammax \
      | sddsconvert -pipe=in ${tmpFile}.ave.1 \
      -edit=col,*Average,%/Average//
}
# APSAddToTempFileList $tmpFile.ave.1
exec sddscombine ${tmpFile} ${tmpFile}.ave.1 -pipe=out \
    -merge \
    | sddssort -pipe=in ${tmpFile}.1 -col=s 
file delete ${tmpFile}.ave~ 

# large list of possibilities:
# For postscript file output or
# send to printer or
# png file output
# or regular display:
# integral present or not

if $thick {
    set graphicOption  -graphic=line,vary,thick=2
} else {
    set graphicOption  -graphic=line,vary
}

if $noDispersion {
    set dispersionOption ""
} else {
    set dispersionOption  "-column=s,etax  ${tmpFile}.1 -legend=ysymbol -unsup=y -yscale=id=eta -ylabel=sca=1.4d "
}
if {[string length $psFile]} {
    if $integralsPresent {
        if [catch {eval exec sddsplot [subst $displayOption] \
                     -split=pages -sep=pages -same \
                     \"-title=Twiss parameters for $fileRoot\"   \
                     $args \
                     [subst $plotOptions] \
                     [subst $morePlotOptions] \
                     -zoom=yfac=0.95,qcent=0.5 $graphicOption -axes=x \
                     -alignZero=yfactor \
                     -thick=2 \
                     -column=s,beta* ${tmpFile}.1 -legend=ysymbol -unsup=y -yscale=id=beta \
                     -ylabel=sca=1.4 \
                     $dispersionOption \
                     -col=s,Profile $fileRoot.mag -overlay=xmode=normal,yfactor=0.075 \
                     -yscale=id=profile \
                     -omnipresent \
                     -dev=ceps -out=$psFile \
                     & } result ] {
            puts stderr "$argv0 in [pwd]: $result"
        }
    } else {
        if [catch {eval exec sddsplot [subst $displayOption] \
                     -split=pages -sep=pages -same \
                     \"-title=Twiss parameters for $fileRoot\"   \
                     $args \
                     [subst $plotOptions] \
                     [subst $morePlotOptions] \
                     -zoom=yfac=0.95,qcent=0.5 $graphicOption -axes=x \
                     -alignZero=yfactor \
                     -thick=2 \
                     -column=s,beta* ${tmpFile}.1 -legend=ysymbol -unsup=y -yscale=id=beta \
                     -ylabel=sca=1.4 \
                     $dispersionOption \
                     -col=s,Profile $fileRoot.mag -overlay=xmode=normal,yfactor=0.075 \
                     -yscale=id=profile \
                     -omnipresent \
                     -dev=ceps -out=$psFile \
                     & } result ] {
            puts stderr "$argv0 in [pwd]: $result"
        }
    }
}
if {[string length $printer]} {
    if $integralsPresent {
        if [catch {eval exec sddsplot [subst $displayOption] \
                     -split=pages -sep=pages -same \
                     \"-title=Twiss parameters for $fileRoot\"   \
                     $args \
                     [subst $plotOptions] \
                     [subst $morePlotOptions] \
                     -zoom=yfac=0.95,qcent=0.5 $graphicOption -axes=x \
                     -alignZero=yfactor \
                     -thick=2 \
                     -column=s,beta* ${tmpFile}.1 -legend=ysymbol -unsup=y -yscale=id=beta \
                     -ylabel=sca=1.4 \
                     $dispersionOption \
                     -col=s,Profile $fileRoot.mag -overlay=xmode=normal,yfactor=0.075 \
                     -yscale=id=profile \
                     -omnipresent \
                     -dev=cpostscript | lpr -P$printer \
                     & } result ] {
            puts stderr "$argv0 in [pwd]: $result"
        }       
    } else {
        if [catch {eval exec sddsplot [subst $displayOption] \
                     -split=pages -sep=pages -same \
                     \"-title=Twiss parameters for $fileRoot\"   \
                     $args \
                     [subst $plotOptions] \
                     [subst $morePlotOptions] \
                     -zoom=yfac=0.95,qcent=0.5 $graphicOption -axes=x \
                     -alignZero=yfactor \
                     -thick=2 \
                     -column=s,beta* ${tmpFile}.1 -legend=ysymbol -unsup=y -yscale=id=beta \
                     -ylabel=sca=1.4 \
                     $dispersionOption \
                     -col=s,Profile $fileRoot.mag -overlay=xmode=normal,yfactor=0.075 \
                     -yscale=id=profile \
                     -omnipresent \
                     -dev=cpostscript | lpr -P$printer \
                     & } result ] {
            puts stderr "$argv0 in [pwd]: $result"
        }       
    }
}

if {[string length $pngFile]} {
    if $integralsPresent {
        if [catch {eval exec sddsplot [subst $displayOption] \
                     -split=pages -sep=pages -same \
                     \"-title=Twiss parameters for $fileRoot\"   \
                     $args \
                     [subst $plotOptions] \
                     [subst $morePlotOptions] \
                     -zoom=yfac=0.95,qcent=0.5 -graphic=line,thick=1,vary -axes=x \
                     -alignZero=yfactor \
                     -thick=2 \
                     -column=s,beta* ${tmpFile}.1 -legend=ysymbol -unsup=y -yscale=id=beta \
                     -ylabel=sca=1.4 \
                     $dispersionOption \
                     -col=s,Profile $fileRoot.mag -overlay=xmode=normal,yfactor=0.075 \
                     -yscale=id=profile \
                     -omnipresent \
                     -dev=png,onwhite -out=$pngFile \
                     & } result ] {
            puts stderr "$argv0 in [pwd]: $result"
        }       
    } else {
        if [catch {eval exec sddsplot [subst $displayOption] \
                     -split=pages -sep=pages -same \
                     \"-title=Twiss parameters for $fileRoot\"   \
                     $args \
                     [subst $plotOptions] \
                     [subst $morePlotOptions] \
                     -zoom=yfac=0.95,qcent=0.5 $graphicOption -axes=x \
                     -alignZero=yfactor \
                     -thick=2 \
                     -column=s,beta* ${tmpFile}.1 -legend=ysymbol -unsup=y -yscale=id=beta \
                     -ylabel=sca=1.4 \
                     $dispersionOption \
                     -col=s,Profile $fileRoot.mag -overlay=xmode=normal,yfactor=0.075 \
                     -yscale=id=profile \
                     -omnipresent \
                     -dev=png,onwhite -out=$pngFile \
                     & } result ] {
            puts stderr "$argv0 in [pwd]: $result"
        }       
    }
}

if !$noDisplay {
    if $integralsPresent {
        if [catch {eval exec sddsplot [subst $displayOption] \
                     -split=pages -sep=pages -same \
                     \"-title=Twiss parameters for $fileRoot\"   \
                     $args \
                     [subst $plotOptions] \
                     [subst $morePlotOptions] \
                     $graphicOption -axes=x \
                     -alignZero=yfactor \
                     -thick=2 \
                     -column=s,beta* ${tmpFile}.1 -legend=ysymbol -unsup=y -yscale=id=beta \
                     -ylabel=sca=1.4 \
                     $dispersionOption \
                     -end \
                     -column=s,EffectiveEmittance  ${tmpFile}.1 -unsup=y \
	             {"-topline=@EffectiveEmittance,edit=i/Effective emittance: /ei/ nm/"} \
                     -ylabel=sca=1.2 \
                     -yscale=id=beta -end \
	             -col=s,yAperture ${tmpFile}.1 -unsup=y -limit=ymax=1 -end \
	             -col=s,xAperture ${tmpFile}.1 -unsup=y -limit=ymax=1 -end \
                     -col=s,Profile $fileRoot.mag -overlay=xmode=normal,yfactor=0.075 \
                     -yscale=id=beta \
                     -omnipresent \
                     & } result ] {
            puts stderr "$argv0 in [pwd]: $result"
        }
    } else {
        if [catch {eval exec sddsplot [subst $displayOption] \
                     -split=pages -sep=pages -same \
                     \"-title=Twiss parameters for $fileRoot\"   \
                     $args \
                     [subst $plotOptions] \
                     [subst $morePlotOptions] \
                     -zoom=yfac=0.95,qcent=0.5 $graphicOption -axes=x \
                     -alignZero=yfactor \
                     -thick=2 \
                     -column=s,beta* ${tmpFile}.1 -legend=ysymbol -unsup=y -yscale=id=beta \
                     -ylabel=sca=1.4 \
                     $dispersionOption -end \
	             -col=s,yAperture ${tmpFile}.1 -unsup=y -limit=ymax=1 -end \
	             -col=s,xAperture ${tmpFile}.1 -unsup=y -limit=ymax=1 -end \
                     -col=s,Profile $fileRoot.mag -overlay=xmode=normal,yfactor=0.075 \
                     -yscale=id=profile \
                     -omnipresent -yscale=id=beta \
                     & } result ] {
            puts stderr "$argv0 in [pwd]: $result"
        }
    }
}
# Allow time for plots to be made before exiting and cleaning up temporary files
# after 2500
exit

