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

#
# $Log: not supported by cvs2svn $
# Revision 1.32  2011/06/02 17:32:41  borland
# Added ability to enable/disable orbit correction.
#
# Revision 1.31  2011/06/02 16:53:32  borland
# Added saving/loading of correction() array.
#
# Revision 1.30  2011/06/02 16:35:58  borland
# Moved correction controls to separate frame to indicate that they are active
# without explicit errors.
#
# Revision 1.29  2011/06/02 16:20:41  borland
# For FMA, can now specify using a single job (good for parallel mode).
#
# Revision 1.28  2011/06/02 16:16:48  borland
# Added control of number of orbit correction SVs.
#
# Revision 1.27  2011/06/02 15:51:52  borland
# Added BPM offset errors.
#
# Revision 1.26  2011/06/01 23:51:48  borland
# Added portability improvements.  Added side tab option to elegantRingAnalysis.
#
# Revision 1.25  2011/05/26 17:04:56  borland
# Added option to use parallel elegant for DA with errors.
#
# Revision 1.24  2011/04/06 15:21:37  borland
# Added control of number of processors for FMA delta.
#
# Revision 1.23  2010/10/19 02:24:42  borland
# Added control over number of processors for FMA.
#
# Revision 1.22  2010/04/08 22:28:53  borland
# Added ability to run kick aperture with multiple processors per job.
#
# Revision 1.21  2010/04/08 18:08:32  borland
# Made the momentum aperture tab more compact.
#
# Revision 1.20  2010/04/04 00:12:16  borland
# Added KickAperture computation.
#
# Revision 1.19  2010/02/23 14:22:49  borland
# Added starting values for momentum apeture search.
#
# Revision 1.18  2010/02/01 01:00:49  borland
# Allow up to 31 lines for DA line search.
#
# Revision 1.17  2009/10/09 15:27:01  borland
# Added aperture to DA w/errors.
#
# Revision 1.16  2009/03/10 19:49:47  borland
# Added optional computation of driving terms.
#
# Revision 1.15  2009/03/06 22:44:47  borland
# Added masking feature for individual errors.
#
# Revision 1.14  2009/03/04 03:20:23  borland
# Added option for parameter file with errors.
#
# Revision 1.13  2009/03/03 18:52:47  borland
# Added moments computation feature.
#
# Revision 1.12  2008/08/26 18:24:18  borland
# Added element type pattern for momentum aperture.
#
# Revision 1.11  2008/07/03 16:46:20  borland
# Added option to include diffusion calculation.
#
# Revision 1.10  2008/06/05 13:01:22  borland
# Added status message after reading configuration file given on commandline.
#
# Revision 1.9  2008/04/16 13:22:30  borland
# Added steps back feature and documentation.
#
# Revision 1.8  2008/04/14 21:17:58  borland
# Improved (simplified) algorithm for momentum aperture determination.  Not
# backward compatible!
#
# Revision 1.7  2008/02/21 00:05:55  borland
# Allow up to 5 (instead of 4) parameter files.
#
# Revision 1.6  2007/12/21 17:03:36  borland
# Added control for body order in matrix dipoles.
#
# Revision 1.5  2007/11/16 19:12:30  borland
# For DynamicAperture with errors only, added process-only button.  Should
# be straightforward to add for others.
#
# Revision 1.4  2007/11/16 13:53:23  borland
# Added entry box for the template file for dynamic aperture, so user can
# change it if desired.
#
# Revision 1.3  2007/11/14 21:56:41  borland
# Scrolled status window is wider.
#
# Revision 1.2  2007/11/14 21:55:25  borland
# File entry boxes are now 80 characters wide.
#
# Revision 1.1  2007/03/30 16:50:28  soliday
# Moved from directory above.
#
# Revision 1.63  2007/01/24 19:06:23  emery
# Indented code.
#
# Revision 1.62  2006/11/16 00:36:05  borland
# The computation formerly under DA+Errors is now just called "DA".  The old "DA" computation is
# no longer needed and was removed.
#
# Revision 1.61  2006/08/22 17:57:25  borland
# Changed errors(numberOfseeds) to more standard errors(numberOfSeeds).
#
# Revision 1.60  2006/08/02 22:38:27  shang
# reorganized tabes, added error tab/
#
# Revision 1.59  2006/06/06 02:06:10  borland
# Removed initial carriage return.
#
# Revision 1.58  2006/06/02 13:26:01  borland
# Dynamic aperture with errors now uses line search modes.
#
# Revision 1.57  2006/03/25 21:52:30  borland
# Revised momentum apeture to scan from outside toward 0 initially, which gives
# better speed and accuracy.
#
# Revision 1.56  2006/03/23 00:05:46  borland
# Added coupled twiss parameter computation using code by V. Sajaev.
# Added momentum aperture computation to elegantRingAnalysis.
#
# Revision 1.55  2005/11/04 16:27:06  borland
# Added Xiao's code for space charge element SCMULT.
#
# Revision 1.53  2005/08/24 13:44:43  borland
# Now show the time for all status messages.
#
# Revision 1.52  2005/07/25 21:00:56  borland
# Corrected to "space charge tune spread" to "space charge tune shift".
#
# Revision 1.51  2005/07/14 17:58:00  borland
# Renamed saveVarList to elegantSaveVarList.
#
# Revision 1.50  2005/07/06 13:01:47  borland
# New version by Shang.  Many procedures are moved to elegant.tcl in
# ../tcltklib.
#
#

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

set CVSRevisionAuthor "\$Author: borland $"

APSApplication . -name elegantRingAnalysis \
  -overview "Performs various elegant simulations for a ring."
.menu.file.menu insert 1 command -label "Save as..." -command SaveConfiguration
.menu.file.menu insert 1 command -label "Read..." -command ReadConfiguration

set status "Working..."
APSScrolledStatus .status -parent .userFrame -textVariable status -height 10 -width 140 

set sourceDir $OAGGlobal(OAGAppConfigDataDirectory)/elegant/ringAnalysisTemplates

proc setStatus {text} {
    APSSetVarAndUpdate status "[clock format [clock seconds] -format %T]: $text"
    update
}
APSSetElegantGlobals

set momentum 7.0e3
set matrixLatticeFile ""
set matrixBeamline RING
set matrixOffsetElement MALIN
set kickLatticeFile ""
set kickBeamline RING
set kickOffsetElement MALIN
set mainParameterFile(1) ""
set mainParameterFile(2) ""
set mainParameterFile(3) ""
set mainParameterFile(4) ""
set mainParameterFile(5) ""
set forceOccurence 0
set mainDirectory [pwd]
set mainPrefix ""
set gridEngine 0
set makePngFiles 0

proc SaveConfiguration {} {
    global elegantSaveVarList
    eval global $elegantSaveVarList
    set configFile [APSFileSelectDialog .saveDialog -listDir $mainDirectory \
                      -checkValidity 0]
    if ![string length $configFile] return
    if [file exists $configFile] {
        if {[APSMultipleChoice [APSUniqueName .] \
               -question "$configFile exists already.  What do you want to do?" \
               -returnList {0 1} \
               -labelList {Overwrite Cancel}]} {
            return
        }
    }
    APSElegantSaveJobConfiguration -filename $configFile \
      -statusCallback setStatus -momentum $momentum \
      -matrixLatticeFile  $matrixLatticeFile -matrixBeamline $matrixBeamline \
      -matrixOffsetElement $matrixOffsetElement -kickLatticeFile $kickLatticeFile \
      -kickBeamline $kickBeamline -kickOffsetElement $kickOffsetElement \
      -forceOccurence $forceOccurence -mainDirectory $mainDirectory \
      -mainPrefix $mainPrefix -gridEngine $gridEngine -makePngFiles $makePngFiles
}


proc ReadConfiguration {} {
    global mainDirectory elegantSaveVarList env
    eval global $elegantSaveVarList
    set configFile [APSFileSelectDialog .saveDialog -listDir $mainDirectory \
                      -checkValidity 1]
    if ![string length $configFile] return
    if ![file exists $configFile] return
    SourceConfiguration $configFile
}

proc SourceConfiguration {configFile} {
    global mainDirectory elegantSaveVarList env
    eval global $elegantSaveVarList
    source $configFile
    setStatus "Configuration $configFile read."
    if [info exists dynamicApertureErrors(mode)] {
	if [string match *line* $dynamicApertureErrors(mode)] {
	    switch $dynamicApertureErrors(mode) {
		one-line {
		    set dynamicApertureErrors(lines) 1
		}
		two-line {
		    set dynamicApertureErrors(lines) 2
		}
		three-line {
		    set dynamicApertureErrors(lines) 3
		}
		five-line {
		    set dynamicApertureErrors(lines) 5
		}
		seven-line {
		    set dynamicApertureErrors(lines) 7
		}
		nine-line {
		    set dynamicApertureErrors(lines) 9
		}
		eleven-line {
		    set dynamicApertureErrors(lines) 11
		}
		default {
		    set dynamicApertureErrors(lines) 11
		}
	    }
	}
    }
    switch $gridEngine {
        no - 
	0 {
	    set gridEngine no
	}
	1 {
	    if [string match oak??? $env(HOSTNAME)] {
		set gridEngine beamphysics
	    } else {
		set gridEngine yes
	    }
	}
	2 {
	    if [string match oak??? $env(HOSTNAME)] {
		set gridEngine beamphysics
	    } elseif {[info exists env(SGE_CLUSTER_NAME)] && [string compare $env(SGE_CLUSTER_NAME) "weed"]==0} {
		set gridEngine hive
	    } else {
		set gridEngine yes
	    }
	}
        yes - 
	default {
	    set gridEngine yes
	}
    }
}

proc Run {args} {
    set computation ""
    set processOnly 0
    APSStrictParseArguments {computation processOnly}
    global sourceDir elegantSaveVarList makePngFiles
    eval global $elegantSaveVarList

    if $processOnly {
        # Only if processOnly is set can we be sure that the procedure accepts this
        # argument
        APSElegant$computation -sourceDir $sourceDir -statusCallback setStatus \
          -momentum $momentum -matrixLatticeFile $matrixLatticeFile \
          -matrixBeamline $matrixBeamline -matrixOffsetElement $matrixOffsetElement \
          -kickLatticeFile $kickLatticeFile -kickBeamline  $kickBeamline \
          -kickOffsetElement $kickOffsetElement -forceOccurence $forceOccurence \
          -mainDirectory $mainDirectory -mainPrefix $mainPrefix \
          -gridEngine $gridEngine  -makePngFiles $makePngFiles \
          -processOnly $processOnly
    } else {
        APSElegant$computation -sourceDir $sourceDir -statusCallback setStatus \
          -momentum $momentum -matrixLatticeFile $matrixLatticeFile \
          -matrixBeamline $matrixBeamline -matrixOffsetElement $matrixOffsetElement \
          -kickLatticeFile $kickLatticeFile -kickBeamline  $kickBeamline \
          -kickOffsetElement $kickOffsetElement -forceOccurence $forceOccurence \
          -mainDirectory $mainDirectory -mainPrefix $mainPrefix \
          -gridEngine $gridEngine  -makePngFiles $makePngFiles 
    }
}

proc Display {args} {
    set type ""
    APSStrictParseArguments {type}
    if ![string length $type] {
        return
    }
    global mainDirectory mainPrefix elegantGlobalArrays makePngFiles
    eval global $elegantGlobalArrays
    set rootname ""
    set suffix ""
    if [regexp {Display} $type] {
        set rootname ""
        set suffix ""
    } else {
        set suffix PP
        if [regexp {Basic} $type] {
            set prefix Basic
        } elseif [regexp {Moments} $type] {
            set prefix Moments
        } else {
            set prefix $type
        }
        set variable [string tolower $type 0 0]
        set rootname $mainDirectory/${mainPrefix}${prefix}[set ${variable}(userSuffix)]
        if ![string compare $type "PhaseSpaceTracking"] {
            set rootname ${rootname}[set ${variable}(offsetPlane)]
        }
        if ![string compare $type "FrequencyMapDelta"] {
            set rootname ${rootname}[set ${variable}(plane)]
        }
    }
    APSElegant${type}${suffix} -rootname $rootname -makePngFiles $makePngFiles -statusCallback setStatus
}

proc FillErrorsFrame {widget args} {
    global errors correction

    APSFrame .f0 -parent $widget -label "Orbit correction"
    set w0 $widget.f0.frame
    APSRadioButtonFrame .disable -parent $w0 \
	-label "Enable: " -valueList {0 1} -buttonList {Yes No} \
	-variable correction(disableOrbitCorrection) -orientation horizontal 
    APSLabeledEntryFrame .svs -parent $w0 \
	-label "Singular values for H, V orbit correction: " \
	-width 10 -orientation horizontal \
	-variableList [list correction(horizontalSVs) correction(verticalSVs)]  -contextHelp \
	"Enter the number of largest singular values to use for orbit correction.  If zero, chosen automatically, which is generally good unless the orbit correction configuration has issues."
    APSLabeledEntry .accuracy -parent $w0 \
	-label "Accuracy of orbit determination (m): " -width 10 -textVariable correction(orbitAccuracy) \
	-contextHelp "Enter the required accuracy of orbit determination. If orbit is not found, try increasing this value." 
    APSLabeledEntry .fraction -parent $w0 \
	-label "Iteration fraction for orbit determination: " -width 10 -textVariable correction(orbitIterationFraction) \
	-contextHelp "Enter the desired iteration fraction for orbit determination. If orbit is not found, try decreasing this value while increasing the number of iterations."
    APSLabeledEntry .iterations -parent $w0 \
	-label "Maximum iterations for orbit determination: " -width 10 -textVariable correction(orbitIterations) \
	-contextHelp "Enter the maximum number of iterations for orbit determination. If orbit is not found, try increasing the number of iterations."

    APSFrame .f1 -parent $widget -label "Error control"
    set w0 $widget.f1.frame
    APSRadioButtonFrame .on -parent $w0 \
      -label "Include error in computation?" -valueList {1 0} -buttonList {Yes No} \
      -variable errors(on) -orientation horizontal
    APSLabeledEntry .seed -parent $w0 \
      -label "Number of seeds: " -width 80 -textVariable errors(numberOfSeeds) \
      -contextHelp "Enter the number of random seeds to run." 
    APSLabeledEntry .number -parent $w0 \
      -label "Random number seed: " -width 80 -textVariable errors(seed) \
      -contextHelp "Enter the random number seed." 
    APSLabeledEntry .file -parent $w0 \
      -label "Parameter file: " -width 80 -textVariable errors(errorInputFile) -fileSelectButton 1 -buttonsOnLeft 1 -fileSelectPattern *.erl \
      -contextHelp \
      "Enter the name of an optional file from which to read errors"

    APSFrame .other -parent $widget -label "Error rms values"
    set w1 $widget.other.frame
    APSRadioButtonFrame .mask -parent $w1 -label "Mask?" -valueList {1 0} -buttonList {Yes No} \
        -variable errors(maskTable) -orientation horizontal \
        -commandList [list "APSDisableWidget $w1.fg" "APSEnableWidget $w1.fg" ]
    APSFrameGrid .fg -parent $w1 -xList "magnet dx dy dtilt fse" \
      -yList "label bend quad sext moni"
    if $errors(maskTable) {
        APSDisableWidget $w1.fg
    }
    foreach label {dx dy dtilt fse} unit {m m rad ""} {
        label $w1.fg.$label.label.label -text "$label ($unit)"
        pack $w1.fg.$label.label.label 
    }
    foreach magnet {Bend Quad Sext Moni} type {bend quad sext moni} {
        label $w1.fg.magnet.$type.label -text "${magnet}:" 
        pack $w1.fg.magnet.$type.label
    }
    foreach quantity {dx dy dtilt fse} {
        foreach type {bend quad sext moni} magnet {Bend Quad Sext Moni} {
            entry $w1.fg.$quantity.$type.entry \
              -textvariable errors($quantity$magnet) \
              -width 10
            pack $w1.fg.$quantity.$type.entry
        }
    }
}


proc FillMainFrame {widget args} {
    global env
    APSLabeledEntry .le1 -parent $widget -label "Momentum (MeV/c): " \
      -width 60 -textVariable momentum -contextHelp \
      "Enter the beam momentum in MeV/c."
    APSLabeledEntry .le2 -parent $widget -label "Matrix lattice file: " \
      -width 80 -textVariable matrixLatticeFile -fileSelectButton 1 -buttonsOnLeft 1 -fileSelectPattern *.lte \
      -contextHelp \
      "Enter the name of the lattice file that uses matrix-based elements."
    APSLabeledEntry .le2a -parent $widget -label "Matrix beamline: " \
      -width 80 -textVariable matrixBeamline \
      -contextHelp \
      "Enter the name of the beamline for the matrix representation"
    APSLabeledEntry .le2b -parent $widget -label "Offset element for matrix beamline: " \
      -width 80 -textVariable matrixOffsetElement \
      -contextHelp \
      "Enter the name of the offset element (MALIGN) for the beamline for the matrix representation.  It should be at the start of the beamline."

    APSLabeledEntry .le3 -parent $widget -label "Tracking lattice file: " \
      -width 80 -textVariable kickLatticeFile -fileSelectButton 1 -buttonsOnLeft 1 -fileSelectPattern *.lte \
      -contextHelp \
      "Enter the name of the lattice file that uses kick-based elements for tracking."
    APSLabeledEntry .le3a -parent $widget -label "Kick beamline: " \
      -width 80 -textVariable kickBeamline \
      -contextHelp \
      "Enter the name of the beamline for the kick representation"
    APSLabeledEntry .le3b -parent $widget -label "Offset element for kick beamline: " \
      -width 80 -textVariable kickOffsetElement \
      -contextHelp \
      "Enter the name of the offset element (MALIGN) for the beamline for the kick representation.  It should be at the start of the beamline."

    foreach item {1 2 3 4 5} {
        APSLabeledEntry .le4$item -parent $widget -label "Parameter file (optional): " \
          -width 80 -textVariable mainParameterFile($item) -fileSelectButton 1 -buttonsOnLeft 1 -fileSelectPattern *.param \
          -contextHelp \
          "Enter the name of the parameter file that contains element parameters.  It will be loaded over the lattice."
    }
    APSRadioButtonFrame .rb4 -parent $widget -label "Force occurence data on parameter files: " \
      -variable forceOccurence -valueList "1 0" -buttonList "Yes No" -orientation horizontal \
      -contextHelp "If Yes, then when elements have the same name in the lattice file, elegant is forced to honor the occurence number of elements when loading parameters.  Not only is this faster, but it is necessary if there is any variation in properties among like-named elements.  If the parameter file only covers one sector of the ring, then No should be selected so that the element properties are loaded into all occurences of the same-named element."
    APSLabeledEntry .le5 -parent $widget -label "Output directory: " \
      -width 80 -textVariable mainDirectory \
      -fileSelectButton 1 -buttonsOnLeft 1 -fileSelectDirectory 1 \
      -contextHelp \
      "Enter the directory in which to place calculation results." 
    APSLabeledEntry .le6 -parent $widget -label "Output file prefix (optional): " \
      -width 80 -textVariable mainPrefix \
      -contextHelp "Enter an optional prefix to use in creating output filenames."

    if {[info exists env(SGE_CLUSTER_NAME)] && [string compare $env(SGE_CLUSTER_NAME) "weed"]==0} {
	# APS weed cluster with main (all.q) and hive (hive.q) queues
	APSRadioButtonFrame .rb1 -parent $widget -label "Use GridEngine? " -orientation horizontal \
	    -variable gridEngine -buttonList "Yes(main) Yes(hive) No" -valueList "yes hive no" \
	    -contextHelp "Select whether or not to use the GridEngine queue to run jobs in parallel."
    } elseif {[string match oak??? $env(HOSTNAME)]} {
	# SLAC oak cluster with main (beamphysics) and test (beamphysics-test) queues
	APSRadioButtonFrame .rb1 -parent $widget -label "Use GridEngine? " -orientation horizontal \
	    -variable gridEngine -buttonList "Yes(main) Yes(test) No" -valueList "beamphysics beamphysics-test no" \
	    -contextHelp "Select whether or not to use the GridEngine queue to run jobs in parallel."
    } else {
	APSRadioButtonFrame .rb1 -parent $widget -label "Use GridEngine? " -orientation horizontal \
	    -variable gridEngine -buttonList "Yes No" -valueList "yes no" \
	    -contextHelp "Select whether or not to use the GridEngine queue to run jobs in parallel."
    }

    APSRadioButtonFrame .rb2 -parent $widget -label "Make PNG files? " \
      -orientation horizontal \
      -variable makePngFiles -buttonList "Yes No" -valueList "1 0" \
      -contextHelp "Select whether or not to automatically make PNG plot files for each plot generated."

}

proc FillBasicFrame {widget args} {
    global basicComputations
    foreach item [list Chromaticity HigherOrderChromaticity ChromaticTuneSpread \
                    RadiationIntegrals DrivingTerms ] {
        lappend variableList basicComputations(do$item) 
    }
    APSCheckButtonFrame .cb1 -parent $widget \
      -label "Include: " -allNone 1 -limitPerRow 4 \
      -buttonList [list Chromaticity "Higher-order chromaticity" "Chromatic Tune Spread" \
                     "Radiation Integrals" "Driving terms"] \
      -variableList $variableList 

    APSLabeledEntry .le1 -parent $widget -width 20 \
      -label "Momentum fractional half-range for chromatic tune spread: " \
      -textVariable basicComputations(chromaticTuneSpreadMomentumSpread) 

    APSLabeledEntry .le2 -parent $widget -width 20 \
      -label "Drift divisions: " -type integer \
      -textVariable basicComputations(driftDivisions)
    APSLabeledEntry .le3 -parent $widget -width 20 \
      -label "Dipole divisions: " -type integer \
      -textVariable basicComputations(dipoleDivisions)
    APSLabeledEntry .le4 -parent $widget -width 20 \
      -label "Quad divisions: " -type integer \
      -textVariable basicComputations(quadDivisions)
    APSLabeledEntry .le41 -parent $widget -width 20 \
      -label "Edge order for dipoles (always 1 for tracking): " -type integer \
      -textVariable basicComputations(edgeOrder) 
    APSLabeledEntry .le42 -parent $widget -width 20 \
      -label "Body order for matrix dipoles (always 1 for tracking): " -type integer \
      -textVariable basicComputations(bodyOrder) 
    APSLabeledEntry .le5 -parent $widget -width 20 \
      -label "Final s for twiss plots (m): " \
      -textVariable basicComputations(finalSTwiss)
    APSLabeledEntry .le6 -parent $widget -width 20 \
      -label "Run suffix: " \
      -textVariable basicComputations(userSuffix)

    APSButton .bu1 -parent $widget -text "Compute" -command \
      "Run -computation BasicComputations"
    APSButton .bu2 -parent $widget -text "Display" -command \
      {Display -type BasicComputations}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantBasicComputationsPP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSElegantBasicComputationsPP) 1" \
      -contextHelp "click to abort any running processes."
}

proc FillMomentsFrame {widget args} {
    global momentsComputations

    APSLabeledEntry .le1 -parent $widget -width 20 \
      -label "Order for matrix quadrupoles and sextupoles: " -type integer \
      -textVariable momentsComputations(order) 
    APSLabeledEntry .le2 -parent $widget -width 20 \
      -label "Edge order for dipoles: " -type integer \
      -textVariable momentsComputations(edgeOrder) 
    APSLabeledEntry .le3 -parent $widget -width 20 \
      -label "Body order for matrix dipoles: " -type integer \
      -textVariable momentsComputations(bodyOrder) 

    APSLabeledEntry .le4 -parent $widget -width 20 \
      -label "Source point type pattern: " \
      -textVariable momentsComputations(sourcePointTypePattern) 
    APSLabeledEntry .le5 -parent $widget -width 20 \
      -label "Source point name pattern: " \
      -textVariable momentsComputations(sourcePointNamePattern) 

    APSLabeledEntry .le6 -parent $widget -width 20 \
      -label "Run suffix: " \
      -textVariable momentsComputations(userSuffix)

    APSButton .bu1 -parent $widget -text "Compute" -command \
      "Run -computation MomentsComputations"
    APSButton .bu2 -parent $widget -text "Display" -command \
      {Display -type MomentsComputations}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantMomentsComputationsPP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSElegantMomentsComputationsPP) 1" \
      -contextHelp "click to abort any running processes."
}

proc FillCollectiveEffectsFrame {widget args} {
    global collectiveEffects
    
    APSLabeledEntry .number -parent $widget \
      -label "Number of scan points: " -width 30 \
      -textVariable collectiveEffects(scanPoints) -type integer
    APSLabeledEntry .rfFreq -parent $widget \
      -label "Rf harmonic: " -width 30 -textVariable collectiveEffects(rfHarmonic) \
      -type integer
    APSLabeledEntry .superPeriods -parent $widget \
      -label "Super periods: " -width 30 -textVariable collectiveEffects(superPeriods) \
      -type integer

    APSLabeledEntryFrame .charge -parent $widget -type real \
      -label "Charge limits (C):                                                     " \
      -width 10 -orientation horizontal \
      -variableList [list collectiveEffects(charge0) collectiveEffects(charge1)]
    APSLabeledEntryFrame .rfVolt -parent $widget -type real \
      -label "Rf voltage limits (V):                                                 " \
      -width 10 -orientation horizontal \
      -variableList [list collectiveEffects(rfVoltage0) collectiveEffects(rfVoltage1)]
    APSLabeledEntryFrame .emitRatio -parent $widget -type real \
      -label "Emittance ratio limits (ey/ex):                                        " \
      -width 10 -orientation horizontal \
      -variableList [list collectiveEffects(emittanceRatio0) collectiveEffects(emittanceRatio1)]
    APSLabeledEntryFrame .bbimp -parent $widget -type real \
      -label "Broad-band impedance limits (Ohm):                                     " \
      -width 10 -orientation horizontal \
      -variableList [list collectiveEffects(BBImpedance0) collectiveEffects(BBImpedance1)]
    APSLabeledEntryFrame .harmv -parent $widget -type real \
      -label "Harmonic cavity voltage (MV):                                           " \
      -width 10 -orientation horizontal \
      -variableList [list collectiveEffects(VHarmonic0) collectiveEffects(VHarmonic1)] \
        -contextHelp "Negative voltage is lengthening, positive is shortening."
    APSLabeledEntry .harmh -parent $widget -type real \
        -label "Harmonic cavity freq. ratio to main: " \
        -width 10 -textVariable collectiveEffects(harmonicRatio)

    APSLabeledEntry .prefix -parent $widget \
      -label "Run prefix: " -width 30 -textVariable collectiveEffects(prefix)

    APSFrame .hai -parent $widget -label "" 
    set w $widget.hai.frame
    APSLabeledEntry .hai -parent $w -label "Haissinski: " \
      -width 80 -textVariable collectiveEffects(haissinskiOutput) -commandButton 1 
    APSButton .run -parent $w -text "Run" -command "Run -computation RunHaissinski" \
      -contextHelp "Do scan for Haissinski equation (bunch lengthening)."
    APSButton .display -parent $w -text "Display" -command "Display -type DisplayHaissinski" \
      -contextHelp "Display scan for intrabeam scattering."
    global apsAbortElegantRun
    set apsAbortElegantRun(Haissinski) 0 
    APSButton .abort -parent $w -text "Abort" \
      -command "set apsAbortElegantRun(Haissinski) 1" \
      -contextHelp "click to abort any running processes."

    APSFrame .ibs -parent $widget -label "" 
    set w $widget.ibs.frame
    APSLabeledEntry .ibs -parent $w -label "IBS: " -commandButton 1 \
      -width 80 -textVariable collectiveEffects(ibsOutput)
    APSButton .run -parent $w -text "Run" -command "Run -computation RunIBS" \
      -contextHelp "Do scan for intrabeam scattering."
    APSButton .display -parent $w -text "Display" -command "Display -type DisplayIBS" \
      -contextHelp "Display scan for intrabeam scattering."
    set apsAbortElegantRun(IBS) 0
    APSButton .abort -parent $w -text "Abort" -command "set apsAbortElegantRun(IBS) 1" \
      -contextHelp "click to abort any running processes."

    APSFrame .scts -parent $widget -label ""
    set w $widget.scts.frame
    APSLabeledEntry .scts -parent $w -label "SC tune spread: " -commandButton 1\
      -width 80 -textVariable collectiveEffects(scTuneShiftOutput)
    APSButton .run -parent $w -text "Run" -command "Run -computation RunSCTuneShift" \
      -contextHelp "Compute space charge tune spreads."
    APSButton .display -parent $w -text "Display" -command "Display -type DisplaySCTuneShift" \
      -contextHelp "Display scan for space-charge tune spread."
    set apsAbortElegantRun(SCTuneShift) 0
    APSButton .abort -parent $w -text "Abort" -command "set apsAbortElegantRun(SCTuneShift) 1" \
      -contextHelp "click to abort any running processes."
}

proc FillPhaseSpaceFrame {widget args} {
    global phaseSpaceTracking
    
    APSRadioButtonFrame .rb1 -parent $widget \
      -label "Plane: " -orientation horizontal -buttonList {x y} -valueList {X Y} \
      -commandList {"set phaseSpaceTracking(otherPlane) Y" "set phaseSpaceTracking(otherPlane) X"} \
      -variable phaseSpaceTracking(offsetPlane) -contextHelp \
      "Choose the plane for which the initial coordinate will be varied."
    APSLabeledEntry .le1 -parent $widget \
      -label "Initial offset for scan (m): " -width 20 -textVariable phaseSpaceTracking(initialOffset) \
      -contextHelp \
      "Enter the initial value of the offset for the swept coordinate."
    APSLabeledEntry .le2 -parent $widget \
      -label "Final offset for scan (m): " -width 20 -textVariable phaseSpaceTracking(finalOffset) \
      -contextHelp \
      "Enter the final value of the offset for the swept coordinate."
    APSLabeledEntry .le2p1 -parent $widget \
      -label "Number of offset values in scan: " -width 20 -textVariable phaseSpaceTracking(sweepPoints) \
      -contextHelp \
      "Enter the number of offset values in the scan."

    APSLabeledEntry .le3 -parent $widget \
      -label "Fixed offset value for the unscanned plane (m): " \
      -width 20 -textVariable phaseSpaceTracking(otherCoord) \
      -contextHelp \
      "Enter the fixed offset value for the unscanned plane."
    APSLabeledEntry .le3a -parent $widget \
      -label "Fixed fractional momentum offset: " \
      -width 20 -textVariable phaseSpaceTracking(delta) \
      -contextHelp \
      "Enter the fixed fractional momentum offset."
    APSLabeledEntry .le4 -parent $widget \
      -label "Turns to track: " -width 20 -textVariable phaseSpaceTracking(turns) \
      -contextHelp \
      "Enter the number of turns to track."

    APSLabeledEntry .le5 -parent $widget \
      -label "Run suffix: " -width 20 -textVariable phaseSpaceTracking(userSuffix) \
      -contextHelp "Enter a suffix for this set of runs."

    APSButton .bu1 -parent $widget \
      -text "Run" -command "Run -computation PhaseSpaceTracking"
    APSButton .bu2 -parent $widget \
      -text "Display" -command \
      {Display -type PhaseSpaceTracking}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantPhaseSpaceTrackingPP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSElegantPhaseSpaceTrackingPP) 1" \
      -contextHelp "click to abort any running processes."
}

proc FillOffMomentumTunesFrame {widget args} {
    global offMomentumTuneTracking
    
    APSLabeledEntry .le1 -parent $widget \
      -label "Initial momentum offset for scan: " -width 20 -textVariable offMomentumTuneTracking(initialOffset) \
      -contextHelp \
      "Enter the initial value of the fractional momentum offset."
    APSLabeledEntry .le2 -parent $widget \
      -label "Final momentum offset for scan: " -width 20 -textVariable offMomentumTuneTracking(finalOffset) \
      -contextHelp \
      "Enter the final value of the fractional momentum offset."
    APSLabeledEntry .le2p1 -parent $widget \
      -label "Number of offset values in scan: " -width 20 -textVariable offMomentumTuneTracking(sweepPoints) \
      -contextHelp \
      "Enter the number of offset values in the scan."

    APSLabeledEntry .le3 -parent $widget \
      -label "Fixed offset value for x plane (m): " \
      -width 20 -textVariable offMomentumTuneTracking(xOffset) \
      -contextHelp \
      "Enter the fixed offset value for the x plane."
    APSLabeledEntry .le3p1 -parent $widget \
      -label "Fixed offset value for y plane (m): " \
      -width 20 -textVariable offMomentumTuneTracking(yOffset) \
      -contextHelp \
      "Enter the fixed offset value for the y plane."

    APSLabeledEntry .le4 -parent $widget \
      -label "Turns to track: " -width 20 -textVariable offMomentumTuneTracking(turns) \
      -contextHelp \
      "Enter the number of turns to track."

    APSLabeledEntry .le4p1 -parent $widget \
      -label "Superperiodicity (for resonance diagram): " \
      -width 20 -textVariable offMomentumTuneTracking(superperiodicity) \
      -contextHelp \
      "Enter the superperiodicity of the lattice.  This is used only in generating the resonance diagram."

    
    APSLabeledEntry .le5 -parent $widget \
      -label "Run suffix: " -width 20 -textVariable offMomentumTuneTracking(userSuffix) \
      -contextHelp "Enter a suffix for this set of runs."


    APSButton .bu1 -parent $widget \
      -text "Run" -command "Run -computation OffMomentumTuneTracking"
    APSButton .bu2 -parent $widget \
      -text "Display" -command \
      {Display -type OffMomentumTuneTracking}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantOffMomentumTuneTrackingPP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSElegantOffMomentumTuneTrackingPP)  1" \
      -contextHelp "click to abort any running processes."
}


proc FillHigherOrderDispersionFrame {widget args} {
    global higherOrderDispersion gridEngine
    
    APSLabeledEntry .le1 -parent $widget \
      -label "Initial momentum offset for scan: " -width 20 -textVariable higherOrderDispersion(initialOffset) \
      -contextHelp \
      "Enter the initial value of the fractional momentum offset."
    APSLabeledEntry .le2 -parent $widget \
      -label "Final momentum offset for scan: " -width 20 -textVariable higherOrderDispersion(finalOffset) \
      -contextHelp \
      "Enter the final value of the fractional momentum offset."
    APSLabeledEntry .le2p1 -parent $widget \
      -label "Number of offset values in scan: " -width 20 -textVariable higherOrderDispersion(sweepPoints) \
      -contextHelp \
      "Enter the number of offset values in the scan."

    
    APSLabeledEntry .le5 -parent $widget \
      -label "Run suffix: " -width 20 -textVariable higherOrderDispersion(userSuffix) \
      -contextHelp "Enter a suffix for this set of runs."


    APSButton .bu1 -parent $widget \
      -text "Run" -command "Run -computation HigherOrderDispersion"
    APSButton .bu2 -parent $widget \
      -text "Display" -command \
      {Display -type HigherOrderDispersion}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantHigherOrderDispersionPP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSElegantHigherOrderDispersionPP) 1" \
      -contextHelp "click to abort any running processes."
}


proc FillDynamicApertureFrame {widget args} {
    global dynamicAperture
    
    APSLabeledEntry .le1 -parent $widget \
      -label "Minimum x coordinate (m): " -width 20 -textVariable dynamicAperture(xMinimum) \
      -contextHelp \
      "Enter the minimum x coordinate for the dynamic aperture search"
    APSLabeledEntry .le2 -parent $widget \
      -label "Maximum x coordinate (m): " -width 20 -textVariable dynamicAperture(xMaximum) \
      -contextHelp \
      "Enter the maximum x coordinate for the dynamic aperture search"
    APSLabeledEntry .le3 -parent $widget \
      -label "Number of x points: " -width 20 -textVariable dynamicAperture(xPoints) \
      -contextHelp \
      "Enter the number of points into which to divide the x interval."
    APSLabeledEntry .le4 -parent $widget \
      -label "Maximum y coordinate (m): " -width 20 -textVariable dynamicAperture(yMaximum) \
      -contextHelp \
      "Enter the maximum y coordinate for the dynamic aperture search"
    APSLabeledEntry .le5 -parent $widget \
      -label "Number of y points: " -width 20 -textVariable dynamicAperture(yPoints) \
      -contextHelp \
      "Enter the number of points into which to divide the y interval."
    APSLabeledEntry .le6 -parent $widget \
      -label "Number of turns: " -width 20 -textVariable dynamicAperture(turns) \
      -contextHelp \
      "Enter the number of turns to track."

    
    APSLabeledEntry .le7 -parent $widget \
      -label "Run suffix: " -width 20 -textVariable dynamicAperture(userSuffix) \
      -contextHelp "Enter a suffix for this set of runs."

    APSRadioButtonFrame .rb1 -parent $widget \
      -label "Include apertures: " -orientation horizontal -buttonList {Yes No} -valueList {1 0} \
      -variable dynamicAperture(includeApertures) -contextHelp \
      "Choose whether to include the effects of apertures that are defined in the beamline."
    
    APSButton .bu1 -parent $widget \
      -text "Run" -command "Run -computation DynamicAperture"
    APSButton .bu2 -parent $widget \
      -text "Display" -command \
      {Display -type DynamicAperture}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantDynamicAperturePP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSAElegantDynamicAperturePP) 1" \
      -contextHelp "click to abort any running processes."
}


proc FillOffMomentumDynamicApertureFrame {widget args} {
    global offMomentumDynamicAperture
    
    APSLabeledEntry .le1 -parent $widget \
      -label "Minimum x coordinate (m): " -width 20 -textVariable offMomentumDynamicAperture(xMinimum) \
      -contextHelp \
      "Enter the minimum x coordinate for the dynamic aperture search"
    APSLabeledEntry .le2 -parent $widget \
      -label "Maximum x coordinate (m): " -width 20 -textVariable offMomentumDynamicAperture(xMaximum) \
      -contextHelp \
      "Enter the maximum x coordinate for the dynamic aperture search"
    APSLabeledEntry .le3 -parent $widget \
      -label "Number of x points: " -width 20 -textVariable offMomentumDynamicAperture(xPoints) \
      -contextHelp \
      "Enter the number of points into which to divide the x interval."
    APSLabeledEntry .le4 -parent $widget \
      -label "Maximum y coordinate (m): " -width 20 -textVariable offMomentumDynamicAperture(yMaximum) \
      -contextHelp \
      "Enter the maximum y coordinate for the dynamic aperture search"
    APSLabeledEntry .le5 -parent $widget \
      -label "Number of y points: " -width 20 -textVariable offMomentumDynamicAperture(yPoints) \
      -contextHelp \
      "Enter the number of points into which to divide the y interval."
    APSLabeledEntry .le6 -parent $widget \
      -label "Minimum delta value: " -width 20 -textVariable offMomentumDynamicAperture(deltaMinimum) \
      -contextHelp \
      "Enter the minimum delta coordinate for the dynamic aperture search"
    APSLabeledEntry .le7 -parent $widget \
      -label "Maximum delta value: " -width 20 -textVariable offMomentumDynamicAperture(deltaMaximum) \
      -contextHelp \
      "Enter the maximum delta coordinate for the dynamic aperture search"
    APSLabeledEntry .le8 -parent $widget \
      -label "Number of delta points: " -width 20 -textVariable offMomentumDynamicAperture(deltaPoints) \
      -contextHelp \
      "Enter the number of values of delta for which to find dynamic apertures"
    APSLabeledEntry .le9 -parent $widget \
      -label "Number of turns: " -width 20 -textVariable offMomentumDynamicAperture(turns) \
      -contextHelp \
      "Enter the number of turns to track."
    
    APSLabeledEntry .le10 -parent $widget \
      -label "Run suffix: " -width 20 -textVariable offMomentumDynamicAperture(userSuffix) \
      -contextHelp "Enter a suffix for this set of runs."

    
    APSRadioButtonFrame .rb1 -parent $widget \
      -label "Include apertures: " -orientation horizontal -buttonList {Yes No} -valueList {1 0} \
      -variable offMomentumDynamicAperture(includeApertures) -contextHelp \
      "Choose whether to include the effects of apertures that are defined in the beamline."

    APSButton .bu1 -parent $widget \
      -text "Run" -command "Run -computation OffMomentumDynamicAperture"
    APSButton .bu2 -parent $widget \
      -text "Display" -command \
      {Display -type OffMomentumDynamicAperture}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantOffMomentumDynamicAperturePP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSElegantOffMomentumDynamicAperturePP) 1" \
      -contextHelp "click to abort any running processes."
}


proc FillDynamicApertureErrorsFrame {widget args} {
    global dynamicApertureErrors templateDirectory

    APSLabeledEntry .le1 -parent $widget \
      -label "Maximum x coordinate (m): " -width 20 -textVariable dynamicApertureErrors(xMaximum) \
      -contextHelp \
      "Enter the maximum x coordinate for the dynamic aperture search"
    APSLabeledEntry .le2 -parent $widget \
      -label "Maximum y coordinate (m): " -width 20 -textVariable dynamicApertureErrors(yMaximum) \
      -contextHelp \
      "Enter the maximum y coordinate for the dynamic aperture search"
    APSLabeledEntry .le3 -parent $widget \
      -label "Number of steps along lines: " -width 20 -textVariable dynamicApertureErrors(steps) \
      -contextHelp \
      "Enter the number of points into which to divide the line."
    APSLabeledEntry .le4 -parent $widget \
      -label "Number of divisions: " -width 20 -textVariable dynamicApertureErrors(splits) \
      -contextHelp \
      "Enter the number of times to divide the interval."
    APSRadioButtonFrame .rb1 -parent $widget -label "Lines: " \
      -orientation horizontal -variable dynamicApertureErrors(lines) \
      -valueList "1 3 5 7 9 11 15 19 23 27 31" \
      -buttonList "1 3 5 7 9 11 15 19 23 27 31" -contextHelp \
      "Number of lines to search on starting at the origin."
    APSLabeledEntry .le5a -parent $widget \
      -label "Fractional momentum offset: " -width 20 -textVariable dynamicApertureErrors(delta) \
      -contextHelp "Enter the fractional momentum offset."
    APSLabeledEntry .le6 -parent $widget \
      -label "Number of turns: " -width 20 -textVariable dynamicApertureErrors(turns) \
      -contextHelp \
      "Enter the number of turns to track." 

    APSLabeledEntry .le7 -parent $widget \
      -label "Run suffix: " -width 20 -textVariable dynamicApertureErrors(userSuffix) \
      -contextHelp "Enter a suffix for this set of runs."

    APSRadioButtonFrame .rb2 -parent $widget \
      -label "Include apertures: " -orientation horizontal -buttonList {Yes No} -valueList {1 0} \
      -variable dynamicApertureErrors(includeApertures) -contextHelp \
      "Choose whether to include the effects of apertures that are defined in the beamline."

    APSLabeledEntry .nproc -parent $widget \
	-label "Number of cores per job: " -width 20 \
	-textVariable dynamicApertureErrors(nCores) \
	-contextHelp "Enter the number of cores per job.  If 1, then serial elegant is used."

    APSLabeledEntry .leaf -parent $widget \
      -label "Aperture file: " -width 80 -textVariable dynamicApertureErrors(apertureFile) \
      -fileSelectButton 1 -buttonsOnLeft 1 -fileSelectPattern *.sdds \
      -contextHelp \
      "Enter the name of a file containing aperture data."

    set dynamicApertureErrors(template) [file join $templateDirectory $dynamicApertureErrors(template)]
    APSLabeledEntry .le8 -parent $widget \
        -label "Template file: " -width 80 -textVariable dynamicApertureErrors(template) \
        -contextHelp "Enter the name of the template file for the runs."

    APSButton .bu1 -parent $widget \
      -text "Run" -command "Run -computation DynamicApertureErrors"
    APSButton .bu1a -parent $widget \
      -text "Process" -command "Run -computation DynamicApertureErrors -processOnly 1"
    APSButton .bu2 -parent $widget \
      -text "Display" -command \
      {Display -type DynamicApertureErrors}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantDynamicApertureErrorsPP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSElegantDynamicApertureErrorsPP) 1" \
      -contextHelp "click to abort any running processes."
}


proc FillKickApertureErrorsFrame {widget args} {
    global kickApertureErrors templateDirectory

    APSLabeledEntry .le1 -parent $widget \
      -label "Minimum kick (mrad): " -width 20 -textVariable kickApertureErrors(minimumKick) \
      -contextHelp \
      "Enter the maximum x plane kick for the kick aperture search"
    APSLabeledEntry .le2 -parent $widget \
      -label "Maximum kick (mrad): " -width 20 -textVariable kickApertureErrors(maximumKick) \
      -contextHelp \
      "Enter the maximum x plane kick for the kick aperture search"
    APSLabeledEntry .le3 -parent $widget \
      -label "Number of steps: " -width 20 -textVariable kickApertureErrors(steps) \
      -contextHelp \
      "Enter the number of points into which to divide the range."
    APSLabeledEntry .le4 -parent $widget \
      -label "Number of turns: " -width 20 -textVariable kickApertureErrors(turns) \
      -contextHelp \
      "Enter the number of turns to track." 

    APSLabeledEntry .le5 -parent $widget \
      -label "Number of particles: " -width 20 -textVariable kickApertureErrors(particles) \
      -contextHelp \
      "Enter the number of particles to track." 

    APSLabeledEntry .le6 -parent $widget \
      -label "Emittance ratio: " -width 20 -textVariable kickApertureErrors(emittanceRatio) \
      -contextHelp \
      "Enter the emittance ratio (ey/ex)"

    APSLabeledEntry .le7 -parent $widget \
      -label "Element name for kick location: " -width 20 -textVariable kickApertureErrors(elementName) \
      -contextHelp "Enter name of the element at which to put initial kick."

    APSLabeledEntry .le9 -parent $widget \
      -label "Run suffix: " -width 20 -textVariable kickApertureErrors(userSuffix) \
      -contextHelp "Enter a suffix for this set of runs."

    APSRadioButtonFrame .rb2 -parent $widget \
      -label "Include apertures: " -orientation horizontal -buttonList {Yes No} -valueList {1 0} \
      -variable kickApertureErrors(includeApertures) -contextHelp \
      "Choose whether to include the effects of apertures that are defined in the beamline."

    APSLabeledEntry .leaf -parent $widget \
      -label "Aperture file: " -width 80 -textVariable kickApertureErrors(apertureFile) \
      -fileSelectButton 1 -buttonsOnLeft 1 -fileSelectPattern *.sdds \
      -contextHelp \
      "Enter the name of a file containing aperture data."

    APSLabeledEntry .le11 -parent $widget \
        -label "Template file: " -width 80 -textVariable kickApertureErrors(template) \
        -contextHelp "Enter the name of the template file for the runs."

    APSLabeledEntry .le12 -parent $widget \
	-label "Number of processors per job: " -width 20 -textVariable kickApertureErrors(processors) \
	-contextHelp "Enter the number of processors per job."

    APSButton .bu1 -parent $widget \
      -text "Run" -command "Run -computation KickApertureErrors"
    #APSButton .bu1a -parent $widget \
    #  -text "Process" -command "Run -computation KickApertureErrors -processOnly 1"
    APSButton .bu2 -parent $widget \
      -text "Display" -command {Display -type KickApertureErrors}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantKickApertureErrorsPP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSElegantKickApertureErrorsPP) 1" \
      -contextHelp "click to abort any running processes."
}



proc FillFineDynamicApertureFrame {widget args} {
    global fineDynamicAperture

    APSLabeledEntry .le1 -parent $widget \
      -label "Minimum x coordinate (m): " -width 20 -textVariable fineDynamicAperture(xMinimum) \
      -contextHelp \
      "Enter the minimum x coordinate for the dynamic aperture run"
    APSLabeledEntry .le2 -parent $widget \
      -label "Maximum x coordinate (m): " -width 20 -textVariable fineDynamicAperture(xMaximum) \
      -contextHelp \
      "Enter the maximum x coordinate for the dynamic aperture run"
    APSLabeledEntry .le3 -parent $widget \
      -label "Number of x points: " -width 20 -textVariable fineDynamicAperture(xPoints) \
      -contextHelp \
      "Enter the number of points into which to divide the x interval."
    APSLabeledEntry .le4 -parent $widget \
      -label "Maximum y coordinate (m): " -width 20 -textVariable fineDynamicAperture(yMaximum) \
      -contextHelp \
      "Enter the maximum y coordinate for the dynamic aperture search"
    APSLabeledEntry .le5 -parent $widget \
      -label "Number of y points: " -width 20 -textVariable fineDynamicAperture(yPoints) \
      -contextHelp \
      "Enter the number of points into which to divide the y interval."
    APSLabeledEntry .le6 -parent $widget \
      -label "Number of turns: " -width 20 -textVariable fineDynamicAperture(turns) \
      -contextHelp \
      "Enter the number of turns to track."
    APSLabeledEntry .le7 -parent $widget \
      -label "Fractional momentum offset: " -width 20 -textVariable fineDynamicAperture(delta) \
      -contextHelp "Enter the fractional momentum offset" 
    APSLabeledEntry .le8 -parent $widget \
      -label "Run suffix: " -width 20 -textVariable fineDynamicAperture(userSuffix) \
      -contextHelp "Enter the suffix for the filenames."

    APSRadioButtonFrame .rb1 -parent $widget \
      -label "Include apertures: " -orientation horizontal -buttonList {Yes No} -valueList {1 0} \
      -variable fineDynamicAperture(includeApertures) -contextHelp \
      "Choose whether to include the effects of apertures that are defined in the beamline."

    APSButton .bu1 -parent $widget \
      -text "Run" -command "Run -computation FineDynamicAperture"
    APSButton .bu2 -parent $widget \
      -text "Display" -command \
      {Display -type FineDynamicAperture}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantFineDynamicAperturePP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSElegantFineDynamicAperturePP) 1" \
      -contextHelp "click to abort any running processes."
}


proc FillFrequencyMapFrame {widget args} {
    global frequencyMap
    
    APSLabeledEntry .le1 -parent $widget \
      -label "Minimum x coordinate (m): " -width 20 -textVariable frequencyMap(xMinimum) \
      -contextHelp \
      "Enter the minimum x coordinate for the frequency map run"
    APSLabeledEntry .le2 -parent $widget \
      -label "Maximum x coordinate (m): " -width 20 -textVariable frequencyMap(xMaximum) \
      -contextHelp \
      "Enter the maximum x coordinate for the frequency map run"
    APSLabeledEntry .le3 -parent $widget \
      -label "Number of x points: " -width 20 -textVariable frequencyMap(xPoints) \
      -contextHelp \
      "Enter the number of points into which to divide the x interval."
    APSLabeledEntry .le4a -parent $widget \
      -label "Minimum y coordinate (m): " -width 20 -textVariable frequencyMap(yMinimum) \
      -contextHelp \
      "Enter the maximum y coordinate for the frequency map search"
    APSLabeledEntry .le4 -parent $widget \
      -label "Maximum y coordinate (m): " -width 20 -textVariable frequencyMap(yMaximum) \
      -contextHelp \
      "Enter the maximum y coordinate for the frequency map search"
    APSLabeledEntry .le5 -parent $widget \
      -label "Number of y points: " -width 20 -textVariable frequencyMap(yPoints) \
      -contextHelp \
      "Enter the number of points into which to divide the y interval."
    APSLabeledEntry .le6 -parent $widget \
      -label "Number of turns: " -width 20 -textVariable frequencyMap(turns) \
      -contextHelp \
      "Enter the number of turns to track."
    APSLabeledEntry .le7 -parent $widget \
      -label "Fractional momentum offset: " -width 20 -textVariable frequencyMap(delta) \
      -contextHelp "Enter the fractional momentum offset" 
    APSLabeledEntry .le6a -parent $widget \
	-label "Number of processors per job: " -width 20 -textVariable frequencyMap(processors) \
	-contextHelp "Enter the number of processors per job."
    APSRadioButtonFrame .rb2 -parent $widget \
	-label "Single job: " -orientation horizontal -buttonList {Yes No} -valueList {1 0} \
	-variable frequencyMap(singleJob) \
	-contextHelp "Select to use a single job.  Probably makes sense if more than one processor per job is used."

    APSRadioButtonFrame .rb0 -parent $widget \
      -label "Compute diffusion: " -orientation horizontal -buttonList {Yes No} -valueList {1 0} \
      -variable frequencyMap(includeChanges) -contextHelp \
      "Choose whether to compute diffusion (change in tune after tracking).  If Yes, then twice as many turns are tracked."
    APSRadioButtonFrame .rb1 -parent $widget \
      -label "Include apertures: " -orientation horizontal -buttonList {Yes No} -valueList {1 0} \
      -variable frequencyMap(includeApertures) -contextHelp \
      "Choose whether to include the effects of apertures that are defined in the beamline."
    APSLabeledEntry .le8 -parent $widget \
      -label "Run suffix: " -width 20 -textVariable frequencyMap(userSuffix) \
      -contextHelp "Enter the suffix for the filenames."

    APSButton .bu1 -parent $widget \
      -text "Run" -command "Run -computation FrequencyMap"
    APSButton .bu2 -parent $widget \
      -text "Display" -command \
      {Display -type FrequencyMap}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantFrequencyMapPP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSElegantFrequencyMapPP) 1" \
      -contextHelp "click to abort any running processes."
}


proc FillFrequencyMapDeltaFrame {widget args} {
    global frequencyMapDelta
    
    APSRadioButtonFrame .rbxy -parent $widget \
      -label "Plane: " -orientation horizontal -buttonList {x y} -valueList {X Y} \
      -variable frequencyMapDelta(plane) -contextHelp \
      "Choose the plane for which the initial coordinate will be varied."
    APSLabeledEntry .le1 -parent $widget \
      -label "Minimum x/y coordinate (m): " -width 20 -textVariable frequencyMapDelta(xyMinimum) \
      -contextHelp \
      "Enter the minimum x (or y) coordinate for the frequency map run"
    APSLabeledEntry .le2 -parent $widget \
      -label "Maximum x/y coordinate (m): " -width 20 -textVariable frequencyMapDelta(xyMaximum) \
      -contextHelp \
      "Enter the maximum x (or y) coordinate for the frequency map run"
    APSLabeledEntry .le3 -parent $widget \
      -label "Number of x/y points: " -width 20 -textVariable frequencyMapDelta(xyPoints) \
      -contextHelp \
      "Enter the number of points into which to divide the x interval."
    APSLabeledEntry .le3a -parent $widget \
      -label "Value for non-varied coordinate (m): " \
      -width 20 -textVariable frequencyMapDelta(otherCoordinate) \
      -contextHelp "Enter the value for the coordinate (y or x) that is not varied."
    APSLabeledEntry .le4a -parent $widget \
      -label "Minimum delta value: " -width 20 -textVariable frequencyMapDelta(deltaMinimum) \
      -contextHelp \
      "Enter the minimum delta coordinate for the frequency map search"
    APSLabeledEntry .le4 -parent $widget \
      -label "Maximum delta value: " -width 20 -textVariable frequencyMapDelta(deltaMaximum) \
      -contextHelp \
      "Enter the maximum delta coordinate for the frequency map search"
    APSLabeledEntry .le5 -parent $widget \
      -label "Number of delta points: " -width 20 -textVariable frequencyMapDelta(deltaPoints) \
      -contextHelp \
      "Enter the number of points into which to divide the delta interval."
    APSLabeledEntry .le6 -parent $widget \
      -label "Number of turns: " -width 20 -textVariable frequencyMapDelta(turns) \
      -contextHelp \
      "Enter the number of turns to track."
    APSRadioButtonFrame .rb1 -parent $widget \
      -label "Include apertures: " -orientation horizontal -buttonList {Yes No} -valueList {1 0} \
      -variable frequencyMapDelta(includeApertures) -contextHelp \
      "Choose whether to include the effects of apertures that are defined in the beamline."
    APSLabeledEntry .le8 -parent $widget \
      -label "Run suffix: " -width 20 -textVariable frequencyMapDelta(userSuffix) \
      -contextHelp "Enter the suffix for the filenames."
    
    APSLabeledEntry .le12 -parent $widget \
	-label "Number of processors per job: " -width 20 -textVariable frequencyMapDelta(processors) \
	-contextHelp "Enter the number of processors per job."

    APSButton .bu1 -parent $widget \
      -text "Run" -command "Run -computation FrequencyMapDelta"
    APSButton .bu2 -parent $widget \
      -text "Display" -command \
      {Display -type FrequencyMapDelta}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantFrequencyMapDeltaPP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSElegantFrequencyMapDeltaPP) 1" \
      -contextHelp "click to abort any running processes."
}

proc FillMomentumApertureFrame {widget args} {
    global momentumAperture

    APSLabeledEntryFrame .lexy -parent $widget \
      -label "Initial x, y coordinates (m): " -width 20 \
      -orientation horizontal \
      -variableList [list momentumAperture(xInitial) momentumAperture(yInitial)] \
      -contextHelp \
      "Enter the initial x and y coordinates relative to the closed orbit."

    APSLabeledEntryFrame .lednst -parent $widget \
      -label "Negative, positive delta start: " -width 20 \
      -orientation horizontal \
      -variableList [list momentumAperture(deltaNegativeStart) momentumAperture(deltaPositiveStart)] \
      -contextHelp \
      "Enter the starting value for delta for the negative- and positive-side scan."

    APSLabeledEntryFrame .ledps -parent $widget \
      -label "Negative, positive delta limit: " -width 20 \
      -orientation horizontal \
      -variableList [list momentumAperture(deltaNegativeLimit) momentumAperture(deltaPositiveLimit)] \
      -contextHelp \
      "Enter the limiting value for delta for the negative- and positive-side scan."

    APSLabeledEntry .ledp -parent $widget \
      -label "Initial delta step: " \
      -width 20 -textVariable momentumAperture(initialDeltaStep) \
      -contextHelp "Initial step size for delta."
    APSLabeledEntry .lesb -parent $widget -type integer \
      -label "Steps back: " -width 20 -textVariable momentumAperture(stepsBack) \
      -contextHelp \
      "Enter the number of steps to back off from the last surviving particle before splitting the interval."
    APSLabeledEntry .lesp -parent $widget -type integer \
      -label "Splits: " -width 20 -textVariable momentumAperture(splits) \
      -contextHelp \
      "Enter the number of interval splits."
    APSLabeledEntry .splitdiv -parent $widget -type integer \
      -label "Step size divisor: " -width 20 -textVariable momentumAperture(stepDivisor) \
      -label "Divisor for step size when splitting." \

    APSLabeledEntry .les0 -parent $widget \
      -label "Starting s (m): " -width 20 -textVariable momentumAperture(sStart) \
      -contextHelp \
      "Enter the starting value of s for selecting beamline elements." 
    APSLabeledEntry .les1 -parent $widget \
      -label "Ending s (m): " -width 20 -textVariable momentumAperture(sEnd) \
      -contextHelp \
      "Enter the ending value of s for selecting beamline elements." 

    APSLabeledEntry .lep -parent $widget \
      -label "Element name pattern: " -width 20 -textVariable momentumAperture(pattern) \
      -contextHelp "Enter a pattern for matching to element names for selecting beamline elements."
    
    APSLabeledEntry .letp -parent $widget \
      -label "Element type pattern: " -width 20 -textVariable momentumAperture(typePattern) \
      -contextHelp "Enter a pattern for matching to element types for selecting beamline elements."
    
    APSLabeledEntry .let -parent $widget \
      -label "Turns: " -width 20 -textVariable momentumAperture(turns) \
      -contextHelp \
      "Enter the number of turns to track."
    
    APSRadioButtonFrame .rb1 -parent $widget \
      -label "Include apertures: " -orientation horizontal -buttonList {Yes No} -valueList {1 0} \
      -variable momentumAperture(includeApertures) -contextHelp \
      "Choose whether to include the effects of apertures that are defined in the beamline."

    APSLabeledEntry .lesn -parent $widget \
      -label "Number of jobs: " -width 20 -textVariable momentumAperture(numberOfJobs) \
      -contextHelp \
      "Enter the number of jobs into which to divide the computation."

    APSLabeledEntry .nproc -parent $widget \
	-label "Number of cores per job: " -width 20 \
	-textVariable momentumAperture(nCores) \
	-contextHelp "Enter the number of cores per job.  If 1, then serial elegant is used."

    APSLabeledEntry .leaf -parent $widget \
      -label "Aperture file: " -width 80 -textVariable momentumAperture(apertureFile) \
      -fileSelectButton 1 -buttonsOnLeft 1 -fileSelectPattern *.sdds \
      -contextHelp \
      "Enter the name of a file containing aperture data."

    APSRadioButtonFrame .rb2 -parent $widget \
      -label "Default matrix order: " -orientation horizontal -buttonList {1 2} -valueList {1 2} \
      -variable momentumAperture(defaultOrder) \
      -contextHelp \
      "Choose the default order for elements implemented as matrices."
    set momentumAperture(userSuffix) ""
    APSLabeledEntry .suffix -parent $widget \
      -label "Run suffix:" -width 20 \
      -textVariable momentumAperture(userSuffix)
    APSButton .bu1 -parent $widget \
      -text "Run" -command "Run -computation MomentumAperture"
    APSButton .bu15 -parent $widget \
      -text "Process" -command "Run -computation MomentumAperture -processOnly 1"
    APSButton .bu2 -parent $widget \
      -text "Display" -command {Display -type MomentumAperture}
    global apsAbortElegantRun
    set apsAbortElegantRun(APSElegantMomentumAperturePP) 0
    APSButton .abort -parent $widget -text "Abort" \
      -command "set apsAbortElegantRun(APSElegantMomentumAperturePP) 1" \
      -contextHelp "click to abort any running processes."
}


set topLabelList {Setup Main Aperture FMA Other}

set SetupTabList {Main Errors}
set SetupTabDescList [list "" ""]
set SetupFrameList {Main Errors}
set MainTabList {Basic Moments PhsSpc  HghrOrdrDsprsn OffMmntmTunes}
set MainFrameList {Basic Moments PhaseSpace HigherOrderDispersion OffMomentumTunes}
set MainTabDescList [list "Twiss parameters, chromaticities, radiation integrals" \
                       "Equilibrium beam moments" \
                       "Phase space tracking, plots, FFTs." \
                       "Higher order dispersion from off-momentum orbits." \
                       "Off-momentum tunes from tracking." ]
set ApertureTabList {DA OffMmntmDA FineDA MmntmAprtr KckAprtr}
set ApertureFrameList {DynamicApertureErrors OffMomentumDynamicAperture \
                         FineDynamicAperture MomentumAperture KickApertureErrors}
set ApertureTabDescList [list "On-momentum dynamic aperture using a line-scan algorithm, optionally with errors." \
                           "Off-momentum dynamic apertures using a relatively coarse algorithm." \
                           "Dynamic aperture using a high-resolution algorithm (requires a cluster)." \
                           "Momentum aperture vs s." "Kick aperture"]
set FMATabList {XY XYDelta}
set FMAFrameList {FrequencyMap FrequencyMapDelta}
set FMATabDescList [list "Frequency map analysis (requires a cluster)." \
                      "Frequency map analysis vs delta (requires a cluster)." ]
set OtherTabList {CollectiveEffects}
set OtherFrameList {CollectiveEffects}
set OtherTabDescList [list "Collective effects."]

foreach name $topLabelList {
    set ${name}Index -1
}
set topIndex -1 
proc DescribeSection {args} {
    global topIndex  topLabelList 
    set topSection [lindex $topLabelList $topIndex]
    if [string length $topSection] {
        global  ${topSection}Index ${topSection}TabDescList
        set index [set ${topSection}Index] 
        set descList [set ${topSection}TabDescList]
        set desc [lindex $descList $index]
        if [string length $desc] {
            setStatus "$desc"
        }
    }
}

lappend elegantSaveVarList errors correction
lappend elegantSaveVarList momentum matrixLatticeFile kickLatticeFile mainParameterFile mainDirectory
lappend elegantSaveVarList mainPrefix gridEngine forceOccurence makePngFiles
lappend elegantSaveVarList matrixBeamline kickBeamline matrixOffsetElement kickOffsetElement
lappend elegantSaveVarList basicComputations momentsComputations phaseSpaceTracking offMomentumTuneTracking higherOrderDispersion
lappend elegantSaveVarList dynamicAperture offMomentumDynamicAperture fineDynamicAperture
lappend elegantSaveVarList frequencyMap collectiveEffects dynamicApertureErrors frequencyMapDelta
lappend elegantSaveVarList momentumAperture kickApertureErrors

set args $argv
set configuration ""
set templateDirectory ""
set sideTabs 0
if {[APSStrictParseArguments {configuration templateDirectory sideTabs}]} {
    return -code error "usage: $argv0 \[-configuration <filename>\] \[-templateDirectory <path>\] [-sideTabs 1\]"
}
set tabPosition nw
if $sideTabs {
    set tabPosition wn
}
if {[string length $configuration]} {
    if ![file exists $configuration] {
        setStatus "not found: $configuration"
    } else {
        SourceConfiguration $configuration
        setStatus "Configuration $configuration read."
    }    
}
if [string length $templateDirectory] {
    set sourceDir $templateDirectory
}

set topTabList [APSTabFrame .top -parent .userFrame -tabPosition $tabPosition \
                  -labelList $topLabelList -frameIndexVariable topIndex \
                  -width 900 -height 600 -packOption "-expand true" \
                  -commandList \
                  [APSReplicateItem -item DescribeSection -number [llength $topLabelList]]]

set index 0
foreach name $topLabelList widget $topTabList { 
    set tabList [set ${name}TabList]
    set len [llength $tabList] 
    set tabFrameList [APSTabFrame .under$name -parent $widget  -packOption "-expand true" -tabPosition $tabPosition \
                        -labelList $tabList -width 900 -height 550 \
                        -frameIndexVariable ${name}Index \
                        -commandList \
                        [APSReplicateItem -item DescribeSection -number $len]]
    
    for {set i 0} {$i<$len} {incr i} {
        set section [lindex [set ${name}FrameList] $i]
        Fill${section}Frame [lindex $tabFrameList $i]
    } 
    incr index
}

setStatus "Ready."
update
