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

set auto_path [linsert $auto_path 0  /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0  /usr/local/oag/lib_patch/$env(HOST_ARCH)]
APSDebugPath

set CVSRevisionAuthor "\$Revision: 1.5 $ \$Author: emery $"

APSApplication . -name createKickerBumpPlots -version $CVSRevisionAuthor \
  -overview "createKickerBumpPlots creates plots to show the trajectory of stored and injected beams."

set requiredFiles {kickerBumps01.cen kickerBumps01a.cen kickerBumps01b.cen \
                     kickerBumps01c.cen kickerBumps01.mag kickerBumps01b.mag}

proc MakeInputFrame {widget args} {
    set parent ""
    
    APSStrictParseArguments {parent}

    set w $parent$widget.frame
    APSFrame $widget -parent $parent -label "Input parameters"
    APSLabeledEntry .workingDir -parent $w -label "Directory:" \
      -textVariable outputDirectory -width 100 \
      -contextHelp "Directory for matched lattice."
    APSButton .pf1button -parent $w.workingDir \
      -text "F" -size small \
      -packOption {-side top} \
      -command {
          set filedialog [APSFileSelectDialog [APSUniqueName .] -pattern {*} -path $outputDirectory -width 70]
		   if {[string compare $filedialog ""] != 0} {set outputDirectory [file dirname $filedialog]} 
      }
    APSLabeledEntry .file -parent $w -label "Lattice file:" \
      -textVariable latticeFile -width 100 \
      -contextHelp "Matched lattice file. This file will be copied and modified to center the injection area."
    APSButton .pf1button -parent $w.file \
      -text "F" -size small \
      -packOption {-side top} \
      -command {
          set filedialog [APSFileSelectDialog [APSUniqueName .] -pattern {*} -path [file dirname $latticeFile] -width 70]
		   if {[string compare $filedialog ""] != 0} {set latticeFile $filedialog]} 
      }
}

proc MakeActionFrame {widget args} {
    set parent ""
    APSStrictParseArguments {parent}

    set w $parent$widget.frame
    APSFrame $widget -parent $parent -label "Actions"
    
    APSLabeledEntry .amplitude -parent $w -label "Bump amplitude (mm)  :" \
      -textVariable amplitude -width 15 \
      -packOption "-side top -anchor w" \
      -contextHelp "Amplitude (mm) for closed bump. Position at injection point."

    APSLabeledEntry .angle -parent $w -label "Angle at the injection point (mrad)  :" \
      -textVariable angle -width 15 \
      -packOption "-side top -anchor w" \
      -contextHelp "Angle (mrad) at the injection point."

    APSLabeledEntry .injOffset -parent $w -label "Injection offset (mm):" \
      -textVariable injOffset -width 15 \
      -packOption "-side top -anchor w" \
      -contextHelp "Injection offset at injection straight section. Value should be at least 7 mm larger than closed bump."

    APSLabeledEntry .injAngleOffset -parent $w -label "Angle offset (mrad):" \
      -textVariable angleOffset -width 15 \
      -packOption "-side top -anchor w" \
      -contextHelp "Injection angle offset at injection straight section. Value should be 0 usually."

    APSLabeledEntry .energyOffset -parent $w -label "Energy offset (%):    " \
      -textVariable energyOffset -width 15 \
      -packOption "-side top -anchor w" \
      -contextHelp "Energy offset of injected beam."

#    APSLabeledEntry .mismatchRatio -parent $w -label "Mismatch ratio:   " \
      -textVariable mismatchRatio -width 15 \
      -packOption "-side top -anchor w" \
      -contextHelp "Ratio for IK3 IK4 relative to closed bump for kicker bump mismatch."

    APSLabeledEntry .printer -parent $w -label "printer:" \
      -textVariable printer -width 15 \
      -packOption "-side top -anchor w" \
      -contextHelp "Printer for plot."

    APSLabeledEntry .plotFileRoot -parent $w -label "File root for plots:" \
      -textVariable plotFileRoot -width 15 \
      -packOption "-side top -anchor w" \
      -contextHelp "File root for plots. Encapsulated postscript files will bte written when the Plot button is pressed. The ceps suffix is added. PNG files are also plotted."

    APSLabeledEntry .showSector -parent $w -label "Show up to sector:" \
      -textVariable nSectors -width 15 \
      -packOption "-side top -anchor w" \
      -contextHelp "Number of sectors to show after the injection area."

    APSFrameGrid .grid -xList {optimize plot print} -parent $w \
      -contextHelp "Grid for optimize and plot buttons"

    set w $parent$widget.frame.grid.optimize
    APSButton .match -parent $w \
      -text "Match Closed Bump" \
      -packOption "-side top -anchor w" \
      -command "MatchAndTrack -mode closedBump" \
      -contextHelp "Matches the kicker bump with tracking."

    APSButton .mismatch -parent $w \
      -text "Optimize Mismatch" \
      -packOption "-side top -anchor w" \
      -command "MatchAndTrack -mode misMatch" \
      -contextHelp "Matches the kicker bump with tracking."

    APSButton .matchOnaxis -parent $w \
      -text "Match On-axis" \
      -packOption "-side top -anchor w" \
      -command "MatchAndTrack -mode onAxis" \
      -contextHelp "Matches the last two kickers for on-axis injection using the closed kicker bump as starting point."

    set w $parent$widget.frame.grid.plot
    APSButton .plot1 -parent $w \
      -text "Plot" \
      -packOption "-side top -anchor w" \
      -command "Plot -print 0 -mode closedBump" \
      -contextHelp "Plots the closed bump."

    APSButton .plot2 -parent $w \
      -text "Plot" \
      -packOption "-side top -anchor w" \
      -command "Plot -print 0 -mode misMatch" \
      -contextHelp "Plots the mismatch condition."

    APSButton .plot3 -parent $w \
      -text "Plot" \
      -packOption "-side top -anchor w" \
      -command "Plot -print 0 -mode onAxis" \
      -contextHelp "Plots the on-axis injection."

    set w $parent$widget.frame.grid.print
    APSButton .print1 -parent $w \
      -text "Print" \
      -packOption "-side top -anchor w" \
      -command "Plot -print 1 -mode closedBump" \
      -contextHelp "Plots the closed bump."

    APSButton .print2 -parent $w \
      -text "Print" \
      -packOption "-side top -anchor w" \
      -command "Plot -print 1 -mode misMatch" \
      -contextHelp "Plots the mismatch condition."

    APSButton .print3 -parent $w \
      -text "Print" \
      -packOption "-side top -anchor w" \
      -command "Plot -print 1 -mode onAxis" \
      -contextHelp "Plots the on-axis injection."

    set w $parent$widget.frame
    APSButton .plot -parent $w \
      -text "Plot All" \
      -packOption "-side left" \
      -command {Plot -print 0 -mode closedBump
          Plot -print 0 -mode misMatch
          Plot -print 0 -mode onAxis } \
      -contextHelp "Plots the various bumps."

    APSButton .plotPrint -parent $w \
      -text "Print All" \
      -packOption "-side left" \
      -command {Plot -print 1 -mode closedBump
          Plot -print 1 -mode misMatch
          Plot -print 1 -mode onAxis } \
      -contextHelp "Plots and prints the various bumps."
    return
}

proc modifyLattice {args} {
# removes kicker elements and ring beamline 
# from original lattice and inserts a ring beamline from the append file.
# prepend is the kicker definitions file.
    set lattice ""
    set prepend ""
    set append ""
    set output ""
    APSParseArguments {lattice prepend append output}
    set tmpfile /tmp/[APSTmpString]
    if [catch {open $lattice r} fid1] {
        return -code error "modifyLattice(0): $fid1"
    }
    if [catch {open $tmpfile w} fid2] {
        return -code error "modifyLattice(1): $fid2"
    }
    set stringFound 0
    while {1} {
        if [catch {gets $fid1 line} result] {
            return -code error "modifyLattice(2): $result"
        }
        if [catch {regexp ring [string tolower $line] match } stringFound] {
            return -code error "modifyLattice(2a): $stringFound"
        }
        if {$stringFound} break
        # check for string S38IK1, S39IK2, S39IK3, and S40IK4
        set kickerDef 0
        if [catch {regexp {^S..IK.:} $line match } kickerDef] {
            return -code error "modifyLattice(2b): $kickerDef"
        }
        if {!$kickerDef} {
            if [catch {puts $fid2 $line} result] {
                return -code error "modifyLattice(2c): $result"
            }
        }
    }
    if [catch {close $fid1} result] {
        return -code error "modifyLattice(3): $result"
    }
    if [catch {close $fid2} result] {
        return -code error "modifyLattice(4): $result"
    }
    if [catch {exec cat $prepend $tmpfile $append > $output} result] {
        return -code error "modifyLattice(5): $result"
    }
    return
}

proc makeBeamFile {args} {
    global amplitude angle injOffset
    APSParseArguments {template file}
    set tmpfile /tmp/[APSTmpString]
    # this beam file is going to be track with an
    # offset equal to $injOffset
    set offset [expr ($amplitude - $injOffset) * 1e-3]
    # The tracking starts with angle of 0 even though the 
    # closed bump may have non-zero angle.
    # This is done because we want the stored beam and injection beam to
    # come as close as possible to each side of the septum vacuum chamber.
    if [catch {exec sddsprocess $template $tmpfile.1 \
                 -redef=col,x,$offset -redef=col,xp,0 \
                 -redef=col,y,0 -redef=col,yp,0 \
                 -redef=col,t,0 \
             } result ] {
        return -code error "makeBeamFile(0): $result"
    }
    if [catch {exec sddsprocess $template $tmpfile.2 \
                 -redef=col,x,0 -redef=col,xp,0 \
                 -redef=col,y,0 -redef=col,yp,0 \
                 -redef=col,t,0 \
             } result ] {
        return -code error "makeBeamFile(1): $result"
    }
    if [catch {exec sddscombine $tmpfile.1 $tmpfile.2 $file -merge -overWrite \
             } result ] {
        return -code error "makeBeamFile(2): $result"
    }
    file delete $tmpfile.1 $tmpfile.2
    return
}

proc MatchAndTrack {args} {
    global outputDirectory latticeFile amplitude angle injOffset angleOffset energyOffset

    # matchedKickers01     optimize the closed bump
    # matchedKickers02     track stored beam with closed bump
    # matchedKickers03     track injected beam with closed bump
    # mismatchedKickers00  optimize inj and stored beam for minimum aperture requirements.
    # mismatchedKickers01  track stored beam with mismatched kickers
    # mismatchedKickers02  track injected beam with mismatched kickers
    # onAxisKickers01      optimize the on-axis injection
    # onAxisKickers02      track stored beam with on-axis injection setting
    # onAxisKickers03      track injected beam with on-axis injection setting
    # create file matchedKickers.lte from the entered lattice file
    # note that start of ring is at sector 37
    APSParseArguments {mode}

    set scriptDir /home/oxygen/EMERY/ring/elegant/injection
    switch $mode {
        closedBump {
            set modifiedLatticeFile $outputDirectory/kickerBump.lte
            set tmpfile /tmp/[APSTmpString]
            APSSetVarAndUpdate status "Modifying lattice $latticeFile for kicker optimization..."
            APSSetVarAndUpdate status "New lattice file $modifiedLatticeFile"
            if [catch {modifyLattice -lattice $latticeFile \
                         -prepend $scriptDir/kickers.lte \
                         -append $scriptDir/kickerBump.lte \
                         -output $tmpfile.lte
                     } result ] {
                return -code error "MatchAndTrack(1): $result"
            }
            if [catch {exec replaceText $tmpfile.lte $modifiedLatticeFile \
                         -orig=<injOffset>,<angleOffset>,<energyOffset> -replace=[expr 1e-3 * $injOffset],[expr 1e-3 * $angleOffset],[expr 0.01 * $energyOffset]} \
                  result ] {
                return -code error "MatchAndTrack(1a): $result"
            }
            APSSetVarAndUpdate status "Lattice modified to include special injection beamlines."
            set tmpfile /tmp/[APSTmpString]
            set file $modifiedLatticeFile
            set beamline "injsectors"
            set rootname "matchedKickers01"
            set saveFile $outputDirectory/[file tail $latticeFile].save
            APSSetVarAndUpdate status "Optimizing kickers..."
            if [catch {exec elegant $scriptDir/optimizeKickerBump.ele \
                         "-macro=latticeFile=$file,beamline=$beamline,rootname=$rootname,amplitude=[expr 1e-3 * $amplitude],angle=[expr 1e-3 * $angle],saveFile=$saveFile" >& \
                         $outputDirectory/$rootname.log \
                     } result ] {
                APSFileDisplayWindow  [APSUniqueName .fileDisp] -fileName $outputDirectory/$rootname.log -width 120 -height 51 -printCommand "enscript -r" -comment "Elegant log file for optimizeKickerBump.ele"
                return -code error "MatchAndTrack(2): $result"
            }

            if [catch {exec sddsprocess $outputDirectory/matchedKickers01.param -noWarning \
                         -match=col,ElementName=S??IK? \
                     } result ] {
                return -code error "MatchAndTrack(3): $result"
            }

            APSSetVarAndUpdate status "Tracking one-turn with matched kickers..."
            set beamline "injsectors"
            set rootname "matchedKickers02"
            set file $saveFile
            if [catch {exec elegant $scriptDir/trackOneTurn.ele \
                         -macro=latticeFile=$file,beamline=$beamline,rootname=$rootname \
                     } result ] {
                return -code error "MatchAndTrack(4): $result"
            }
            set beamline "firstsectors"
            set rootname "matchedKickers03"
            set file $saveFile
            if [catch {exec elegant $scriptDir/trackOneTurn.ele \
                         -macro=latticeFile=$file,beamline=$beamline,rootname=$rootname \
                     } result ] {
                return -code error "MatchAndTrack(5): $result"
            }
            APSSetVarAndUpdate status "All tracking complete."
            # this clip removes the beginning before the displacement 
            # of -23.4 mm is given.
            if [catch {exec sddsprocess matchedKickers03.cen -noWarning \
                         -clip=1,0 \
                     } result ] {
                return -code error "MatchAndTrack(5a): $result"
            }
            # for stored beam, shift s coordinate by 27 m
            if [catch {exec sddsprocess -noWarning \
                         "-redef=col,s,s 2 27.6 * - " matchedKickers01.mag
                exec sddsprocess -noWarning \
                         "-redef=col,s,s 2 27.6 * - " matchedKickers01.cen
                exec sddsprocess -noWarning \
                         "-redef=col,s,s 2 27.6 * - " matchedKickers02.mag
                exec sddsprocess -noWarning \
                         "-redef=col,s,s 2 27.6 * - " matchedKickers02.cen \
                     } result ] {
                return -code error "MatchAndTrack(6): $result"
            }    
        }
        misMatch {
            APSSetVarAndUpdate status "Optimizing for mismatched kickers..."
            set file $outputDirectory/[file tail $latticeFile].save
            set beamline "twosectors"
            set saveFile $outputDirectory/[file tail $latticeFile].mismatch.save
            set rootname "mismatchedKickers00"
            set beamFile /tmp/[APSTmpString]
            # use a previously generated output to create a new beam file.
            # it is easier than trying to create the column definitions
            # from scratch.
            makeBeamFile -template matchedKickers01.out -file $beamFile
            if [catch {exec elegant $scriptDir/optimizeMismatch.ele \
                         -macro=latticeFile=$file,beamline=$beamline,rootname=$rootname,beamFile=$beamFile,saveFile=$saveFile  >& \
                         $outputDirectory/$rootname.log \
                     } result ] {
                return -code error "MatchAndTrack(7): $result"
            }

            set file $saveFile
            set beamline "injsectors"
            set rootname "mismatchedKickers01"
            if [catch {exec elegant $scriptDir/trackOneTurn.ele \
                         -macro=latticeFile=$file,beamline=$beamline,rootname=$rootname \
                     } result ] {
                return -code error "MatchAndTrack(8): $result"
            }

            set file $saveFile
            set beamline "firstsectors"
            set rootname "mismatchedKickers02"
            if [catch {exec elegant $scriptDir/trackOneTurn.ele \
                         -macro=latticeFile=$file,beamline=$beamline,rootname=$rootname \
                     } result ] {
                return -code error "MatchAndTrack(9): $result"
            }
            # this clip removes the beginning before the displacement 
            # of -23.4 mm is given.
            if [catch {exec sddsprocess mismatchedKickers00.cen -noWarning \
                         -clip=1,0 
                exec sddsprocess mismatchedKickers02.cen -noWarning \
                         -clip=1,0 \
                     } result ] {
                return -code error "MatchAndTrack(10): $result"
            }
            APSSetVarAndUpdate status "All tracking complete."
            # for stored beam, shift s coordinate by 27 m
            if [catch {exec sddsprocess -noWarning \
                         "-redef=col,s,s 2 27.6 * - " mismatchedKickers01.mag
                exec sddsprocess -noWarning \
                         "-redef=col,s,s 2 27.6 * - " mismatchedKickers01.cen \
                     } result ] {
                return -code error "MatchAndTrack(11): $result"
            }    
        }
        onAxis {
            #
            # Optimizing kickers for on-axis injection
            #
            set file $outputDirectory/[file tail $latticeFile].save
            set beamline "firstsectors"
            set rootname "onAxisKickers01"
            set saveFile $outputDirectory/[file tail $latticeFile].onaxis.save
            APSSetVarAndUpdate status "Optimizing kickers for on-axis injection..."
            if [catch {exec elegant $scriptDir/optimizeOnAxis.ele \
                         -macro=latticeFile=$file,beamline=$beamline,rootname=$rootname,saveFile=$saveFile >& \
                         $outputDirectory/$rootname.log \
                     } result ] {
                return -code error "MatchAndTrack(12): $result"
            }
            if [catch {exec sddsprocess $outputDirectory/onAxisKickers01.param -noWarning \
                         -match=col,ElementName=S??IK? \
                     } result ] {
                return -code error "MatchAndTrack(13): $result"
            }

            # track stored beam and injected beam
            APSSetVarAndUpdate status "Tracking one-turn with kickers set to on-axis injection..."
            set file $saveFile
            set beamline "injsectors"
            set paramFile $outputDirectory/onAxisKickers01.param
            set rootname "onAxisKickers02"
            if [catch {exec elegant $scriptDir/trackOneTurn.ele \
                         -macro=latticeFile=$file,beamline=$beamline,rootname=$rootname  >& \
                         $outputDirectory/$rootname.log \
                     } result ] {
                return -code error "MatchAndTrack(14): $result"
            }
            
            set file $saveFile
            set beamline "firstsectors"
            set paramFile $outputDirectory/onAxisKickers01.param
            set rootname "onAxisKickers03"
            if [catch {exec elegant $scriptDir/trackOneTurn.ele \
                         -macro=latticeFile=$file,beamline=$beamline,rootname=$rootname >& \
                         $outputDirectory/$rootname.log  \
                     } result ] {
                return -code error "MatchAndTrack(15): $result"
            }

            APSSetVarAndUpdate status "Tracking done."
            # this clip removes the beginning before the displacement 
            # of -23.4 mm is given.
            if [catch {exec sddsprocess onAxisKickers01.cen -noWarning \
                         -clip=1,0 
                exec sddsprocess onAxisKickers03.cen -noWarning \
                         -clip=1,0 \
                     } result ] {
                return -code error "MatchAndTrack(16): $result"
            }
            # for stored beam, shift s coordinate by 27 m
            if [catch {exec sddsprocess -noWarning \
                         "-redef=col,s,s 2 27.6 * - " onAxisKickers02.mag
                exec sddsprocess -noWarning \
                         "-redef=col,s,s 2 27.6 * - " onAxisKickers02.cen \
                     } result ] {
                return -code error "MatchAndTrack(17): $result"
            }
            APSSetVarAndUpdate status "Post-processing done."
        }
        default {
            APSSetVarAndUpdate status "No can recognize mode $mode."
        }
    }    
    APSSetVarAndUpdate status "Ready."
}

proc Plot {args} {
    global outputDirectory printer nSectors plotFileRoot
    set print 0
    APSParseArguments {print mode}

    set matched $outputDirectory/matchedKickers02
    set matchedInj $outputDirectory/matchedKickers03
    set mismatched $outputDirectory/mismatchedKickers01
    set mismatchedInj $outputDirectory/mismatchedKickers02
    set onAxis $outputDirectory/onAxisKickers02
    set onAxisInj $outputDirectory/onAxisKickers03

    set sLimit [expr $nSectors * 27.6]
    # injection tracking has different starting s-coordinate so we have
    # to determine it.
    set S40ENDm [exec sddsprocess $matched.cen -pipe=out -match=col,ElementName=S40END | sdds2stream -pipe -col=s]
    set S40ENDt [exec sddsprocess $matchedInj.cen -pipe=out -match=col,ElementName=S40END | sdds2stream -pipe -col=s]
    switch $mode {
        closedBump {
            if [catch {exec sddsplot -title= \
                         "-topline=Injection bump produced by matched kickers,sca=1.4" \
                         -lspace=.5,.95,.05,.35 \
                         -filter=col,s,-$sLimit,$sLimit \
                         -col=s,Profile $matched.mag -overlay=xmode=normal,yfactor=0.05 \
                         -col=s,Cx $matched.cen \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=1 \
                         "-leg=spec=Stored beam,sca=2" \
                         \
                         -col=s,Cx $matchedInj.cen \
                         -offset=xChange=[expr $S40ENDm - $S40ENDt] \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=2 \
                         "-leg=spec=Incoming beam,sca=2" \
                         "-string=sector 1,x=31,y=-7" \
                         "-string=sector 2,x=57,y=-7" \
                         "-string=sector 38,x=-52,y=-7" \
                         "-string=\$s7\$ekicker 1,x=-24,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 2,x=-1.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 3,x=3.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 4,x=26,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$eseptums,angle=90,x=1.5,y=2,sca=0.7" \
                         & \
                     } result ] {
                APSSetVarAndUpdate status "Plot: $result"
                return -code error "Plot: $result"
            }
            if [catch {exec sddsplot -title= \
                         "-topline=Injection bump produced by matched kickers,sca=1.4" \
                         -lspace=.5,.95,.05,.35 \
                         -filter=col,s,-$sLimit,$sLimit \
                         -col=s,Profile $matched.mag -overlay=xmode=normal,yfactor=0.05 \
                         -col=s,Cx $matched.cen \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=1 \
                         "-leg=spec=Stored beam,sca=2" \
                         \
                         -col=s,Cx $matchedInj.cen \
                         -offset=xChange=[expr $S40ENDm - $S40ENDt] \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=2 \
                         "-leg=spec=Incoming beam,sca=2" \
                         "-string=sector 1,x=31,y=-7" \
                         "-string=sector 2,x=57,y=-7" \
                         "-string=sector 38,x=-52,y=-7" \
                         "-string=\$s7\$ekicker 1,x=-24,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 2,x=-1.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 3,x=3.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 4,x=26,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$eseptums,angle=90,x=1.5,y=2,sca=0.7" \
                         -dev=ceps -output=$plotFileRoot.$mode.ceps \
                         & \
                     } result ] {
                APSSetVarAndUpdate status "Plot: $result"
                return -code error "Plot: $result"
            }
            if [catch {exec sddsplot -title= \
                         "-topline=Injection bump produced by matched kickers,sca=1.4" \
                         -lspace=.5,.95,.05,.35 \
                         -filter=col,s,-$sLimit,$sLimit \
                         -col=s,Profile $matched.mag -overlay=xmode=normal,yfactor=0.05 \
                         -col=s,Cx $matched.cen \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=1 \
                         "-leg=spec=Stored beam,sca=2" \
                         \
                         -col=s,Cx $matchedInj.cen \
                         -offset=xChange=[expr $S40ENDm - $S40ENDt] \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=2 \
                         "-leg=spec=Incoming beam,sca=2" \
                         "-string=sector 1,x=31,y=-7" \
                         "-string=sector 2,x=57,y=-7" \
                         "-string=sector 38,x=-52,y=-7" \
                         "-string=\$s7\$ekicker 1,x=-24,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 2,x=-1.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 3,x=3.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 4,x=26,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$eseptums,angle=90,x=1.5,y=2,sca=0.7" \
                         -dev=lpng,onwhite -output=$plotFileRoot.$mode.png \
                         & \
                     } result ] {
                APSSetVarAndUpdate status "Plot: $result"
                return -code error "Plot: $result"
            }
        }
        misMatch {
            set sLimit [expr $nSectors * 27.6]
            if [catch {exec sddsplot -title= \
                         "-topline=Injection bump produced by mismatched kickers,sca=1.4" \
                         -lspace=.5,.95,.05,.35 \
                         -filter=col,s,-$sLimit,$sLimit \
                         -col=s,Profile $mismatched.mag -overlay=xmode=normal,yfactor=0.05 \
                         -col=s,Cx $mismatched.cen \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=1 \
                         "-leg=spec=Stored beam,sca=2" \
                         \
                         -col=s,Cx $mismatchedInj.cen \
                         -offset=xChange=[expr $S40ENDm - $S40ENDt] \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=2 \
                         "-leg=spec=Incoming beam,sca=2" \
                         "-string=sector 1,x=31,y=-7" \
                         "-string=sector 2,x=57,y=-7" \
                         "-string=sector 38,x=-52,y=-7" \
                         "-string=\$s7\$ekicker 1,x=-24,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 2,x=-1.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 3,x=3.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 4,x=26,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$eseptums,angle=90,x=1.5,y=2,sca=0.7" \
                         & \
                     } result ] {
                APSSetVarAndUpdate status "Plot: $result"
                return -code error "Plot: $result"
            }
            if [catch {exec sddsplot -title= \
                         "-topline=Injection bump produced by mismatched kickers,sca=1.4" \
                         -lspace=.5,.95,.05,.35 \
                         -filter=col,s,-$sLimit,$sLimit \
                         -col=s,Profile $mismatched.mag -overlay=xmode=normal,yfactor=0.05 \
                         -col=s,Cx $mismatched.cen \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=1 \
                         "-leg=spec=Stored beam,sca=2" \
                         \
                         -col=s,Cx $mismatchedInj.cen \
                         -offset=xChange=[expr $S40ENDm - $S40ENDt] \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=2 \
                         "-leg=spec=Incoming beam,sca=2" \
                         "-string=sector 1,x=31,y=-7" \
                         "-string=sector 2,x=57,y=-7" \
                         "-string=sector 38,x=-52,y=-7" \
                         "-string=\$s7\$ekicker 1,x=-24,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 2,x=-1.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 3,x=3.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 4,x=26,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$eseptums,angle=90,x=1.5,y=2,sca=0.7" \
                         -dev=ceps -output=$plotFileRoot.$mode.ceps \
                         & \
                     } result ] {
                APSSetVarAndUpdate status "Plot: $result"
                return -code error "Plot: $result"
            }
            if [catch {exec sddsplot -title= \
                         "-topline=Injection bump produced by mismatched kickers,sca=1.4" \
                         -lspace=.5,.95,.05,.35 \
                         -filter=col,s,-$sLimit,$sLimit \
                         -col=s,Profile $mismatched.mag -overlay=xmode=normal,yfactor=0.05 \
                         -col=s,Cx $mismatched.cen \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=1 \
                         "-leg=spec=Stored beam,sca=2" \
                         \
                         -col=s,Cx $mismatchedInj.cen \
                         -offset=xChange=[expr $S40ENDm - $S40ENDt] \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=2 \
                         "-leg=spec=Incoming beam,sca=2" \
                         "-string=sector 1,x=31,y=-7" \
                         "-string=sector 2,x=57,y=-7" \
                         "-string=sector 38,x=-52,y=-7" \
                         "-string=\$s7\$ekicker 1,x=-24,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 2,x=-1.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 3,x=3.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 4,x=26,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$eseptums,angle=90,x=1.5,y=2,sca=0.7" \
                         -dev=lpng,onwhite -output=$plotFileRoot.$mode.png \
                         & \
                     } result ] {
                APSSetVarAndUpdate status "Plot: $result"
                return -code error "Plot: $result"
            }
        }
        onAxis {
            set sLimit [expr $nSectors * 27.6]
            if [catch {exec sddsplot -title= \
                         "-topline=On-axis injection,sca=1.4" \
                         -lspace=.5,.95,.05,.35 \
                         -filter=col,s,-$sLimit,$sLimit \
                         -col=s,Profile $onAxis.mag -overlay=xmode=normal,yfactor=0.05 \
                         -col=s,Cx $onAxis.cen \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=1 \
                         "-leg=spec=Stored beam,sca=2" \
                         \
                         -col=s,Cx $onAxisInj.cen \
                         -offset=xChange=[expr $S40ENDm - $S40ENDt] \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=2 \
                         "-leg=spec=Incoming beam,sca=2" \
                         "-string=sector 1,x=31,y=-7" \
                         "-string=sector 2,x=57,y=-7" \
                         "-string=sector 38,x=-52,y=-7" \
                         "-string=\$s7\$ekicker 1,x=-24,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 2,x=-1.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 3,x=3.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 4,x=26,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$eseptums,angle=90,x=1.5,y=2,sca=0.7" \
                         & \
                     } result ] {
                APSSetVarAndUpdate status "Plot: $result"
                return -code error "Plot: $result"
            }
            if [catch {exec sddsplot -title= \
                         "-topline=On-axis injection,sca=1.4" \
                         -lspace=.5,.95,.05,.35 \
                         -filter=col,s,-$sLimit,$sLimit \
                         -col=s,Profile $onAxis.mag -overlay=xmode=normal,yfactor=0.05 \
                         -col=s,Cx $onAxis.cen \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=1 \
                         "-leg=spec=Stored beam,sca=2" \
                         \
                         -col=s,Cx $onAxisInj.cen \
                         -offset=xChange=[expr $S40ENDm - $S40ENDt] \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=2 \
                         "-leg=spec=Incoming beam,sca=2" \
                         "-string=sector 1,x=31,y=-7" \
                         "-string=sector 2,x=57,y=-7" \
                         "-string=sector 38,x=-52,y=-7" \
                         "-string=\$s7\$ekicker 1,x=-24,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 2,x=-1.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 3,x=3.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 4,x=26,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$eseptums,angle=90,x=1.5,y=2,sca=0.7" \
                         -dev=ceps -output=$plotFileRoot.$mode.ceps \
                         & \
                     } result ] {
                APSSetVarAndUpdate status "Plot: $result"
                return -code error "Plot: $result"
            }
            if [catch {exec sddsplot -title= \
                         "-topline=On-axis injection,sca=1.4" \
                         -lspace=.5,.95,.05,.35 \
                         -filter=col,s,-$sLimit,$sLimit \
                         -col=s,Profile $onAxis.mag -overlay=xmode=normal,yfactor=0.05 \
                         -col=s,Cx $onAxis.cen \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=1 \
                         "-leg=spec=Stored beam,sca=2" \
                         \
                         -col=s,Cx $onAxisInj.cen \
                         -offset=xChange=[expr $S40ENDm - $S40ENDt] \
                         -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                         -grap=line,type=2 \
                         "-leg=spec=Incoming beam,sca=2" \
                         "-string=sector 1,x=31,y=-7" \
                         "-string=sector 2,x=57,y=-7" \
                         "-string=sector 38,x=-52,y=-7" \
                         "-string=\$s7\$ekicker 1,x=-24,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 2,x=-1.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 3,x=3.5,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$ekicker 4,x=26,y=2,angle=90,sca=0.7" \
                         "-string=\$s7\$eseptums,angle=90,x=1.5,y=2,sca=0.7" \
                         -dev=lpng,onwhite -output=$plotFileRoot.$mode.png \
                         & \
                     } result ] {
                APSSetVarAndUpdate status "Plot: $result"
                return -code error "Plot: $result"
            }
        }
    }
    if $print {
        switch $mode {
            closedBump {
                if [catch {exec sddsplot -title= \
                             "-topline=Injection bump produced by matched kickers,sca=1.4" \
                             -lspace=.5,.95,.05,.35 \
                             -filter=col,s,-$sLimit,$sLimit \
                             -col=s,Profile $matched.mag -overlay=xmode=normal,yfactor=0.05 \
                             -col=s,Cx $matched.cen \
                             -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                             -grap=line,type=1 \
                             "-leg=spec=Stored beam,sca=2" \
                             \
                             -col=s,Cx $matchedInj.cen \
                             -offset=xChange=[expr $S40ENDm - $S40ENDt] \
                             -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                             -grap=line,type=2 \
                             "-leg=spec=Incoming beam,sca=2" \
                             "-string=sector 1,x=31,y=-7" \
                             "-string=sector 2,x=57,y=-7" \
                             "-string=sector 38,x=-52,y=-7" \
                             "-string=\$s7\$ekicker 1,x=-24,y=2,angle=90,sca=0.7" \
                             "-string=\$s7\$ekicker 2,x=-1.5,y=2,angle=90,sca=0.7" \
                             "-string=\$s7\$ekicker 3,x=3.5,y=2,angle=90,sca=0.7" \
                             "-string=\$s7\$ekicker 4,x=26,y=2,angle=90,sca=0.7" \
                             "-string=\$s7\$eseptums,angle=90,x=1.5,y=2,sca=0.7" \
                             -dev=cpost | lpr -P$printer \
                         } result ] {
                    APSSetVarAndUpdate status "Plot: $result"
                    return -code error "Plot: $result"
                }
            }
            misMatch {
                if [catch {exec sddsplot -title= \
                             "-topline=Injection bump produced by mismatched kickers,sca=1.4" \
                             -lspace=.5,.95,.05,.35 \
                             -filter=col,s,-$sLimit,$sLimit \
                             -col=s,Profile $mismatched.mag -overlay=xmode=normal,yfactor=0.05 \
                             -col=s,Cx $mismatched.cen \
                             -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                             -grap=line,type=1 \
                             "-leg=spec=Stored beam,sca=2" \
                             \
                             -col=s,Cx $mismatchedInj.cen \
                             -offset=xChange=[expr $S40ENDm - $S40ENDt] \
                             -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                             -grap=line,type=2 \
                             "-leg=spec=Incoming beam,sca=2" \
                             "-string=sector 1,x=31,y=-7" \
                             "-string=sector 2,x=57,y=-7" \
                             "-string=sector 38,x=-52,y=-7" \
                             "-string=\$s7\$ekicker 1,x=-24,y=2,angle=90,sca=0.7" \
                             "-string=\$s7\$ekicker 2,x=-1.5,y=2,angle=90,sca=0.7" \
                             "-string=\$s7\$ekicker 3,x=3.5,y=2,angle=90,sca=0.7" \
                             "-string=\$s7\$ekicker 4,x=26,y=2,angle=90,sca=0.7" \
                             "-string=\$s7\$eseptums,angle=90,x=1.5,y=2,sca=0.7" \
                             -dev=cpost | lpr -P$printer \
                         } result ] {
                    APSSetVarAndUpdate status "Plot: $result"
                    return -code error "Plot: $result"
                }
            }
            onAxis {
                if [catch {exec sddsplot -title= \
                             "-topline=On-axis injection,sca=1.4" \
                             -lspace=.5,.95,.05,.35 \
                             -filter=col,s,-$sLimit,$sLimit \
                             -col=s,Profile $onAxis.mag -overlay=xmode=normal,yfactor=0.05 \
                             -col=s,Cx $onAxis.cen \
                             -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                             -grap=line,type=1 \
                             "-leg=spec=Stored beam,sca=2" \
                             \
                             -col=s,Cx $onAxisInj.cen \
                             -offset=xChange=[expr $S40ENDm - $S40ENDt] \
                             -factor=ymult=1000 "-ylabel=edit=ei/ (mm)/" \
                             -grap=line,type=2 \
                             "-leg=spec=Incoming beam,sca=2" \
                             "-string=sector 1,x=31,y=-7" \
                             "-string=sector 2,x=57,y=-7" \
                             "-string=sector 38,x=-52,y=-7" \
                             "-string=\$s7\$ekicker 1,x=-24,y=2,angle=90,sca=0.7" \
                             "-string=\$s7\$ekicker 2,x=-1.5,y=2,angle=90,sca=0.7" \
                             "-string=\$s7\$ekicker 3,x=3.5,y=2,angle=90,sca=0.7" \
                             "-string=\$s7\$ekicker 4,x=26,y=2,angle=90,sca=0.7" \
                             "-string=\$s7\$eseptums,angle=90,x=1.5,y=2,sca=0.7" \
                             -dev=cpost | lpr -P$printer \
                         } result ] {
                    APSSetVarAndUpdate status "Plot: $result"
                    return -code error "Plot: $result"
                }
            }
            default {
                set status "Mode $mode unknown." 
            }
        }
    }
    return
}


set status "Working..."
APSScrolledStatus .status -parent .userFrame -textVariable status -width 90

set outputDirectory .
set latticeFile $OAGGlobal(SRLatticesDirectory)/default/aps.lte
# amplitude and angle in mm and mrad
set amplitude -16
set angle  -0.1
set injOffset -24
set angleOffset 0
set energyOffset 0
set mismatchRatio 1.4
set printer color
set plotFileRoot [expr abs($injOffset)]mm
set nSectors 4

MakeInputFrame .input -parent .userFrame
MakeActionFrame .action -parent .userFrame
set status "Ready."

