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

#
# $Log: not supported by cvs2svn $
# Revision 1.42  2004/04/06 04:48:00  emery
# Removed unnecessary -BPMList argument to set sr ioc bpm averaging.
#
# Revision 1.41  2003/03/04 06:46:45  emery
# Changed default bunch pattern for archiving,
#
# Revision 1.40  2003/03/04 05:30:49  emery
# Indented some procedures. Put catch statement around close $procFid
# in order to avoid the PV CA error upon exiting sddsmonitor.
#
# Revision 1.39  2003/01/28 19:42:17  soliday
# Fixed a bug stoping the scan if a problem has occured.
#
# Revision 1.38  2001/11/01 22:48:42  borland
# Fixed order of plots for case when orbit correction configuration is not
# selected.
#
# Revision 1.37  2001/10/30 22:50:54  soliday
# Added the BM PVs.
#
# Revision 1.36  2001/10/30 20:28:00  soliday
# Modified the interface, fitting, and plotting.
#
# Revision 1.35  2000/01/27 22:39:34  borland
# Made filename on plot more readable by splitting onto two lines.
#
# Revision 1.34  2000/01/27 21:40:12  borland
# By default, BBCM waveforms are now not collected.
#
# Revision 1.33  2000/01/27 21:38:35  borland
# Added scan filename to the plots.
#
# Revision 1.32  1999/09/24 15:52:12  emery
# Added ellipses to reminders button.
#
# Revision 1.31  1999/09/17 18:54:59  emery
# Added Reminders button.
#
# Revision 1.30  1999/09/16 14:02:24  borland
# Now uses 3x3 layout for plots.
#
# Revision 1.29  1999/07/28 17:58:01  soliday
# Added missing bracket
#
# Revision 1.28  1999/06/01 15:54:44  borland
# Added -erase option to sddsmonitor.
#
# Revision 1.27  1999/03/09 22:33:34  soliday
# Added ability to archive combined intensity scan fits along with the raw
# data files that were used to create the intensity scan fits.
#
# Revision 1.26  1999/02/16 22:49:41  borland
# Now uses sddsmpfit for much faster fitting.  The fitCoef file is different,
# but it isn't used for anything.
#
# Revision 1.25  1999/02/16 22:23:34  borland
# Added file deletion and addition to temp file list in fitting procedure.
#
# Revision 1.24  1999/02/12 16:56:25  borland
# Modified by N. Sereno to change default filename filter.
#
# Revision 1.23  1999/01/18 23:54:13  borland
# Changed sort order to decr instead of incr.
#
# Revision 1.22  1999/01/18 23:47:31  borland
# Improved the messages/behavior when Stop is pressed.
#
# Revision 1.21  1998/12/11 20:15:46  emery
# Indented some code, changed soem labels, made dialog boxes
# wide enough for directory and file names. Added column S35DCCT
# to final combined offset file.
#
# Revision 1.20  1998/12/08 18:05:32  emery
# Changed daily subdirectory from intensScan to intenScan.
#
# Revision 1.19  1998/12/08 17:31:25  emery
# "Go to Daily Directory" button added by D. Blach.
#
# Revision 1.18  1998/12/03 17:56:01  emery
# Indented new procedures.
#
# Revision 1.17  1998/12/02 15:34:45  soliday
# Changed archive directory and added Singlet Interval option.
#
# Revision 1.16  1998/11/25 21:46:33  soliday
# Removed link to my private version of quickSDDSplot
#
# Revision 1.15  1998/11/25 21:32:53  soliday
# Added quickSDDSplot button, added ability to archive fitted data.
#
# Revision 1.14  1998/11/20 19:07:35  soliday
# Displays archive directory in status screen.
#
# Revision 1.13  1998/11/06 19:27:33  soliday
# Added archive feature.
#
# Revision 1.12  1998/10/27 16:33:28  soliday
# Fixed packing order and grided some widgets.
#
# Revision 1.11  1998/09/09 23:24:50  borland
# Now collects and processes P0 data, when installation phase is 2.
#
# Revision 1.10  1998/06/30 17:25:14  borland
# Fixed a typo in WaitForPrompt procedure.
#
# Revision 1.9  1998/06/18 21:58:10  borland
# Expanded version by R. Soliday.  Now does data processing and display,
# using the methods from the doIntenScanFits and combineIntenScans tcl
# scripts.
#
# Revision 1.8  1998/04/06 18:58:59  borland
# Now takes bunch-by-bunch CM data instead of scope data.
#
# Revision 1.7  1997/08/14 16:42:29  borland
# Added option for collection or not collecting waveform data.
#
# Revision 1.6  1997/08/14 16:24:13  borland
# Commented out code that takes scope waveforms.
#
# Revision 1.5  1997/05/03 21:11:45  borland
# Added context help for buttons.
#
# Revision 1.4  1997/05/03 21:07:48  borland
# Added optional run with prompting for each measurement.
#
# Revision 1.3  1997/03/21 16:25:06  borland
# Changed window name and added overview text.
#
# Revision 1.2  1997/03/21 16:22:24  borland
# Modified to use sddsmonitor input file from oagData area.
#
# Revision 1.1  1997/03/21 16:16:54  borland
# First version in CVS.
#
#

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.43 $ \$Author: soliday $"

set procFid ""

proc sddsmonitorCallback {fid flagVariable} {
    # callback routine for sddsmonitor subprocess in single-shot mode
    gets $fid input
    global $flagVariable
    if [string compare $input "Type <cr> to read, q to quit:"]==0 {
        set $flagVariable 1
        return
    }
    if [string compare $input "Done."]==0 {
        set $flagVariable 2
    }
    if [string length $input] {
        # unknown string
        APSSetVarAndUpdate status "sddsmonitor: $input"
    }
}

proc StartProcess {} {
    global procFid processFlag step status

    set monitorDir /home/helios/oagData/sr/offsetAdjustmentData/inputFiles
    set monitorFile SR_msAveErrorCC+AveSums.mon
    if {[string length $procFid]} {
        APSSetVarAndUpdate status "Subprocess already running."
        return
    }
    APSSetVarAndUpdate status "Starting subprocess..."
    # start subprocess


    # start subprocess
    global output
    set procFid \
      [open "|sddsmonitor -erase $monitorDir/$monitorFile \
            $output -single=stdout -steps=1000 -update=1 -verbose" r+]
    
    # set up callbacks when there is data on the pipe from the subprocess
    set processFlag 0
    set step 0
    fileevent $procFid readable "sddsmonitorCallback $procFid processFlag"
    WaitForPrompt
}

proc WaitForPrompt {} {
    global step processFlag status procFid
    APSSetVarAndUpdate status "Waiting for data collection/prompt...($processFlag)"
    if $processFlag==0 {
        tkwait variable processFlag
        if $processFlag!=1 {
            if $processFlag==-1 {
                APSSetVarAndUpdate status "Problem with readback from subprocess."
            } else {
                APSSetVarAndUpdate status "Unexpected return from process: $processFlag"
            }
            close $procFid
            set procFid ""
        }
    }
    set processFlag 0
    APSSetVarAndUpdate status "Prompt received."
}

set step 0
proc TakePoint {} {
    global step processFlag status procFid output spinPositions waveforms
    if {![string length $procFid]} {
        APSSetVarAndUpdate status "Subprocess not running."
        return 0
    }
    set processFlag 0
    after 2000
    puts stderr "TakePoint is called."
    puts stderr "[exec ps -fd | grep sddsmonitor]"
    puts $procFid "y"
    flush $procFid
    incr step
    APSSetVarAndUpdate status "Sent request to take data point $step."
    WaitForPrompt
    if $waveforms {
        APSSetVarAndUpdate status "Acquiring waveform"
        set waveform [format ${output}.wf%03ld $step]
        APSSRReadBunchCM -output $waveform
    }
    APSSetVarAndUpdate status "Pausing 10s for BPM averaging [exec date +%T]"
    APSWaitWithUpdate -waitSeconds 10 -updateInterval 1
    return 1
}


proc StopProcess {} {
    global processFlag procFid status tabPage
    APSEnableButton $tabPage(Measurement).iDFrame.frame.run.button
    APSEnableButton $tabPage(Measurement).iDFrame.frame.runPrompt.button
    APSDisableButton $tabPage(Measurement).iDFrame.frame.stop.button
    puts stderr "Button Stop process is pressed."
    puts stderr "[exec ps -fd | grep sddsmonitor]"
    if {![string length $procFid]} {
        APSSetVarAndUpdate status "Subprocess not running."
        return
    }
    # terminate the subprocess
    puts $procFid "q"
# There was often a
# CA error on many sdcu PVs immediately after the q command, which then
# causes a problem with the close command. Shouldn't the file close itself
# after a q command?
    flush $procFid
    catch {close $procFid}
    set procFid ""
    APSSetVarAndUpdate status "Subprocess stopped.  Wait..."
}

proc APSSRSetSCDUAveraging {args} {
    set num2Ave 0
    set mode ""
    if {[APSStrictParseArguments {mode num2Ave}] || \
	    ![string length $mode] || $num2Ave<=2} {
        return -code error "APSSRSetSCDUAveraging: bad syntax/values"
    }
    switch $mode {
        On -
        on {
            set mode On
        }
        Off -
        off {
            set mode Off
        }
        default {
            return -code error "APSSRSetSCDUAveraging: bad mode $mode"
        }
    }

    if {[catch \
	     {exec cavput -list=S:bpm -range=begin=1,end=40 -pend=4 \
		  -list=:ave_cont_bo=$mode -blunder=silent} result] || \
	    [catch {exec cavput -list=S -range=begin=1,end=40 -pend=30 \
			-list=A:P1,A:P2,A:P3,A:P4,B:P5,B:P4,B:P3,B:P2,B:P1 \
			-list=:num2ave_ao.VAL=$num2Ave} result]} {
        return -code error "APSSRSetSCDUAveraging: $result"
    }
}

proc RunExperiment {args} {
    set prompt 0
    APSStrictParseArguments {prompt}

    global output continueButton tabPage
    if ![string length $output] {
        APSSetVarAndUpdate status "No output filename given."
        return
    }
    if {[file exists $output]  && \
	    ![APSMultipleChoice [APSUniqueName .] -name "Overwrite Dialog" \
		  -question "$output exists---Overwrite it?" \
		  -width 30 -returnList {1 0} -labelList {Yes No}]} {
        APSSetVarAndUpdate status "Give a new filename."
        return
    }
    catch {file delete $output}
    APSDisableButton $tabPage(Measurement).iDFrame.frame.run.button
    APSDisableButton $tabPage(Measurement).iDFrame.frame.runPrompt.button
    APSEnableButton $tabPage(Measurement).iDFrame.frame.stop.button
    APSSetVarAndUpdate status "Setting IOC averaging to 64 with filter coefficient of 1."
    APSSRSetIOCAveraging -num2Ave 64 -filterCoeff 1 -enable 1 
    APSSRSetSCDUAveraging -num2Ave 20 -mode on
    APSSetVarAndUpdate status "Waiting for averaging."
    APSWaitWithUpdate -waitSeconds 10 -updateInterval 1
    StartProcess
    while 1 {
        if $prompt {
            APSEnableButton $continueButton
            bell
            APSSetVarAndUpdate status "Press continue to proceed..."
            tkwait variable continueRun
            APSDisableButton $continueButton
        }
        if ![TakePoint] break
    }
    APSSetVarAndUpdate status "Postprocessing..."
    if {[catch {exec sddssort $output -column=S8B:P5:scdu:ave_sum.VAL,decr \
                  -noWarnings} result]} {
        APSSetVarAndUpdate status "RunExperiment: $result"
    }
    file delete $output~
    APSSetVarAndUpdate status "Done. May go to \"Do Intensity Scan Fits.\""
#   global iSFinput
#   set iSFinput $output
    APSSetVarAndUpdate status "Output file transfered to Intensity scan fits. May go to \"Do Intensity Scan Fits.\" and start fitting."
}

proc doIntenScanFits {args} {
    set input ""
    set plane ""
    set maxDCCT 100
    set minDCCT 40
    APSSetVarAndUpdate status "Starting IntenScanFit"
    if {[APSStrictParseArguments {input plane maxDCCT minDCCT}] || \
	    ![llength $input] || ![file exists $input] || \
	    [lsearch [list x y] $plane]==-1} {
        APSSetVarAndUpdate status "IntenScanFit: Error: wrong arguments"
        return -code error "IntenScanFit: Error: wrong arguments"
    }
    if [file exists $input.fitValues.$plane] {
        APSSetVarAndUpdate status "IntenScanFit: Exists: $input.fitValues.$plane"
        return -code error "IntenScanFit: Exists: $input.fitValues.$plane"
    }
    
    set sumName S8B:P5:scdu:ave_sum.VAL
    set DCCTName S35DCCT
    set tmpInput /tmp/[APSTmpString]
    if [catch {eval exec sddsconvert $input -pipe=out \
		   -retain=column,S35DCCT,${sumName},*${plane} \
		   | sddsprocess -pipe=in -clip=2,0 $tmpInput \
		   -filter=column,S35DCCT,$minDCCT,$maxDCCT} result] {
        APSSetVarAndUpdate status "IntenScanFit: $result"
        return -code error "IntenScanFit: $result"
    }

    if [catch {
        exec sddsmpfit $tmpInput -pipe=out \
          -terms=3 -independent=$sumName \
          -dependent=S*BM:P\[1-9\]:msAve:$plane,S*\[AB\]:P\[1-9\]:msAve:$plane \
          -evaluate=$input.fitValues.$plane.tmp1,number=100 \
          | sddscollapse -pipe \
          | sddscollect -pipe=in $input.fitCoef.1.$plane \
          -collect=suffix=ReducedChiSquared -collect=suffix=RmsResidual \
          -collect=suffix=SignicanceLevel -collect=suffix=FitIsValid \
          -collect=suffix=Sddspfitlabel -collect=suffix=Intercept \
          -collect=suffix=Slope -collect=suffix=Curvature \
          -nowarnings
        exec sddsmpfit $tmpInput -pipe=out \
          -terms=3 -independent=S35DCCT \
          -dependent=S*BM:P0:msAve:$plane,S*\[AB\]:P0:msAve:$plane \
          -evaluate=$input.fitValues.$plane.tmp2,number=100 \
          | sddscollapse -pipe \
          | sddscollect -pipe=in $input.fitCoef.2.$plane \
          -collect=suffix=ReducedChiSquared -collect=suffix=RmsResidual \
          -collect=suffix=SignicanceLevel -collect=suffix=FitIsValid \
          -collect=suffix=Sddspfitlabel -collect=suffix=Intercept \
          -collect=suffix=Slope -collect=suffix=Curvature \
          -nowarnings
        exec sddscombine $input.fitCoef.1.$plane $input.fitCoef.2.$plane $input.fitCoef.$plane -merge
        exec sddsxref $input.fitValues.$plane.tmp1 $input.fitValues.$plane.tmp2 $input.fitValues.$plane.tmp
        exec sddssort $input.fitValues.$plane.tmp -pipe=output \
          -column=$sumName,decr \
          | sddsprocess -pipe=in $input.fitValues.$plane \
          -print=parameter,RawFile,$input} result] {
        APSSetVarAndUpdate status "IntenScanFit: $result"
        return -code error "IntenScanFit: $result"
    }
    if 0 {
        if [catch {
            exec sddsmpfit $tmpInput -pipe=out \
              -terms=3 -independent=$sumName \
              -dependent=S*\[AB\]:P\[0-9\]:msAve:$plane,S35DCCT \
              -evaluate=$input.fitValues.$plane.tmp,number=100 \
              | sddscollapse -pipe \
              | sddscollect -pipe=in $input.fitCoef.$plane \
              -collect=suffix=ReducedChiSquared -collect=suffix=RmsResidual \
              -collect=suffix=SignicanceLevel -collect=suffix=FitIsValid \
              -collect=suffix=Sddspfitlabel -collect=suffix=Intercept \
              -collect=suffix=Slope -collect=suffix=Curvature
            exec sddssort $input.fitValues.$plane.tmp -pipe=output \
              -column=$sumName,decr \
              | sddsprocess -pipe=in $input.fitValues.$plane \
              -print=parameter,RawFile,$input} result] {
            APSSetVarAndUpdate status "IntenScanFit: $result"
            return -code error "IntenScanFit: $result"
        }
    }
    file delete $input.fitValues.$plane.tmp 
    file delete $input.fitValues.$plane.tmp1 $input.fitValues.$plane.tmp2
    file delete $input.fitCoef.1.$plane $input.fitCoef.2.$plane
    APSSetVarAndUpdate status "Finished IntenScanFit for plane $plane. Repeat for other plane, or if both are done, go to \"Combine Intensity Scan Fits\""
    if {[string compare $plane x] == 0} {
        global xfile
        set xfile $input.fitValues.$plane
    } else {
        global yfile
        set yfile $input.fitValues.$plane
    }
}

proc combineIntenScans {args} {
    set xfile ""
    set yfile ""
    set output ""
    APSSetVarAndUpdate status "Starting combineIntenScans"
    if {[APSStrictParseArguments {xfile yfile output}] || \
	    ![llength $xfile] || ![llength $yfile] || \
	    ![llength $output] || \
	    ![file exists $xfile] || ![file exists $yfile]} {
        APSSetVarAndUpdate status "combineIntenScans: Error: wrong arguements"
        return
    }
    if [file exists $output] {
        APSSetVarAndUpdate status "combineIntenScans: $output exists"
        return
    }

    set refBPM S8B:P5
    set sumName ${refBPM}:scdu:ave_sum.VAL
    
    if {[catch {exec sddsprocess $xfile -pipe=out \
		    -process=${sumName},max,SumMax \
		    -process=${sumName},min,SumMin \
		    | sdds2stream -pipe -param=SumMax,SumMin} xList] || \
	    [catch {exec sddsprocess $yfile -pipe=out \
			-process=${sumName},max,SumMax \
			-process=${sumName},min,SumMin \
			| sdds2stream -pipe -param=SumMax,SumMin} yList]} {
        APSSetVarAndUpdate status "combineIntenScans: xList: ${xList}"
        APSSetVarAndUpdate status "combineIntenScans: yList: ${yList}"
        return
    }
    
    set xSumMin [lindex $xList 1]
    set ySumMin [lindex $yList 1]
    set xSumMax [lindex $xList 0]
    set ySumMax [lindex $yList 0]
    
    set sumMin [expr $xSumMin>$ySumMin?$xSumMin:$ySumMin]
    set sumMax [expr $xSumMax<$ySumMax?$xSumMax:$ySumMax]
    
    set plane x
    set interpList ""
    foreach file [list $xfile $yfile] {
        set tempdir [file dirname $output]
        set tempfile [file tail $file]
        if [catch {exec sddsinterp $file $tempdir/$tempfile.interp$plane \
		       -columns=${sumName},*:${plane}*,S35DCCT \
		       -sequence=100,$sumMin,$sumMax} result] {
            APSSetVarAndUpdate status "combineIntenScans: Error: $result"
            return
        }
        lappend interpList $tempdir/$tempfile.interp$plane
        set plane y
    }
    set fID [sdds open $xfile]
    if [catch {sdds getParameter $fID RawFile -page 1} xRawFile] {
        set xRawFile ""
    }
    sdds close $fID
    set fID [sdds open $yfile]
    if [catch {sdds getParameter $fID RawFile -page 1} yRawFile] {
        set yRawFile ""
    }
    sdds close $fID

    if [catch {eval exec sddsxref $interpList -pipe=out -take=* \
		   | sddsconvert -pipe \
		   -edit=column,*,%/:msAve//%/scdu:ave_sum.VAL/sum// \
		   -delete=param,* \
		   | sddssort -pipe -column=${refBPM}:sum,decr \
		   | sddsprocess -pipe=in $output \
		   {-process=*\[xy\],first,%sFirst} \
		   {"-redefine=column,%s,%s %sFirst -,select=*\[xy\]"} \
		   -print=parameter,SumReferenceBPM,$refBPM \
		   -print=parameter,xRawFile,$xRawFile \
		   -print=parameter,yRawFile,$yRawFile} result] {
        APSSetVarAndUpdate status "combineIntenScans: Error: $result"
        return
    }
    APSSetVarAndUpdate status "Finished combineIntenScans"
}    

proc PlotData {args} {
    set PlotType raw
    set DataFile ""
    set MinX 0
    set MaxX 0
    set MinY 0
    set MaxY 0
    set quickSDDS 0
    set Offset 1
    set SameScale 1
    APSStrictParseArguments {PlotType DataFile Plane MinX MaxX MinY MaxY Offset SameScale quickSDDS}
    if {![string length $DataFile]} {
        APSSetVarAndUpdate status "PlotData: Enter data file"
        return
    }   
    if {![file exists $DataFile]} {
        APSSetVarAndUpdate status "PlotData: $DataFile does not exist"
        return
    }
    if {![file isfile $DataFile]} {
        APSSetVarAndUpdate status "PlotData: $DataFile is not a file"
        return
    }
    if {$PlotType != "raw"} { 
        if {![file exists $DataFile.fitValues.$Plane]} {
            APSSetVarAndUpdate status "PlotData: $DataFile.fitValues.$Plane does not exist"
            return
        }
    }
    APSSetVarAndUpdate status "Plotting... please wait"
    if {[string compare $PlotType both] == 0} {
        set passed ""
        set passed2 ""
        set dataFileList "$DataFile $DataFile.fitValues.$Plane"
    } elseif {[string compare $PlotType fit] == 0} {
        set passed "$DataFile.fitValues.$Plane -graphic=line,type=1"
        set passed2 ""
        set dataFileList $DataFile.fitValues.$Plane
    } else {
        set passed "$DataFile -graphic=symbol,scale=2"
        set passed2 ""
        set dataFileList $DataFile
    }
    APSValSimple -inputValue $MinX -outputValue MinX
    APSValSimple -inputValue $MaxX -outputValue MaxX
    APSValSimple -inputValue $MinY -outputValue MinY
    APSValSimple -inputValue $MaxY -outputValue MaxY
    if {$Offset == 1} {
        set passed3 -mode=y=offset
    } else {
        set passed3 ""
    }
    if {$SameScale == 1} {
        set passed4 -sameScale=y
    } else {
        set passed4 ""
    }
    if {!$quickSDDS} {
        global presentOrbitConfig
        set pathname [os editstring %./home/helios/.. [file dirname $DataFile]]
        set filename [file tail $DataFile]
        if {!$presentOrbitConfig} {
            set groupBy tag,nameIndex
            set separate nameIndex
            if {[string compare $PlotType fit] == 0} {
                set names [exec sddsquery $DataFile.fitValues.$Plane -columnlist "-delimiter= "]
            } else {
                set names [exec sddsquery $DataFile -columnlist "-delimiter= "]
            }
            set plotNames ""
            foreach name $names {
                if {[string match *:$Plane $name]} {
                    set number [string range $name 1 2]
                    if {![string is integer -strict $number]} {
                        set number [string range $name 1 1]
                    }
                    lappend plotNames "$name $number"
                }
            }
            set plotNames [lsort -integer -index 1 -unique $plotNames]
            set columnNames ""
            if {[string compare $PlotType both] == 0} {
                foreach number $plotNames {
                    set sector [lindex [split $number] 1]
                    set columnList [join [BPMArgList -sector $sector -plane $Plane] ,]
                    append columnNames "-columnNames=S8B:P5:scdu:ave_sum.VAL,($columnList) $DataFile -graphic=symbol,scale=2 -tag=[lindex $number 1] -columnNames=S8B:P5:scdu:ave_sum.VAL,($columnList) $DataFile.fitValues.$Plane -graphic=line,type=1 -tag=[lindex $number 1] -nextPage "
                }
            } else {
                foreach number $plotNames {
                    set sector [lindex [split $number] 1]
                    set columnList [join [BPMArgList -sector $sector -plane $Plane] ,]
                    append columnNames "-columnNames=S8B:P5:scdu:ave_sum.VAL,($columnList) -tag=[lindex $number 1] -nextPage "
                }
            }
        } else {
            set groupBy request
            set separate nameString
            if {$Plane == "x"} {
                set orbitfile "/home/helios/oagData/sr/orbitControllaw/lattices/default/h.default/config"
            } else {
                set orbitfile "/home/helios/oagData/sr/orbitControllaw/lattices/default/v.default/config"
            }
            set names [exec sdds2stream $orbitfile -columns=Name]
            if {[string compare $PlotType fit] == 0} {
                set datanames [exec sddsquery $DataFile.fitValues.$Plane -columnlist "-delimiter= "]
            } else {
                set datanames [exec sddsquery $DataFile -columnlist "-delimiter= "]
            }
            set plotNames ""
            foreach name $names {
                if {([string match *P* $name]) && ([lsearch -glob $datanames ${name}*] != -1)} {
                    set number [string range $name 1 2]
                    if {![string is integer -strict $number]} {
                        set number [string range $name 1 1]
                    }
                    lappend plotNames "$name $number"
                }
            }
            set plotNames [lsort -integer -index 1 $plotNames]
            set columnNames ""
            set page [lindex [lindex $plotNames 0] 1]
            if {[string compare $PlotType both] == 0} {
                foreach number $plotNames {
                    if {[lindex $number 1] != $page} {
                        append columnNames "-nextPage "
                        set page [lindex $number 1]
                    }
                    append columnNames "-columnNames=S8B:P5:scdu:ave_sum.VAL,[lindex $number 0]*$Plane $DataFile -graphic=symbol,scale=2 -tag=[lindex $number 1] -columnNames=S8B:P5:scdu:ave_sum.VAL,[lindex $number 0]*$Plane $DataFile.fitValues.$Plane -graphic=line,type=1 -tag=[lindex $number 1] "
                }
            } else {
                foreach number $plotNames {
                    if {[lindex $number 1] != $page} {
                        append columnNames "-nextPage "
                        set page [lindex $number 1]
                    }
                    append columnNames "-columnNames=S8B:P5:scdu:ave_sum.VAL,[lindex $number 0]*$Plane -tag=[lindex $number 1] "
                }
            }

        }
        APSExec -unixCommand "sddsplot -toptitle -topline=$pathname -title=$filename \
            -layout=4,4 -groupBy=$groupBy -separate=$separate -scales=$MinX,$MaxX,$MinY,$MaxY $passed3 $passed4 $passed $columnNames"    
    } else {
        set dataFileList "$dataFileList $dataFileList"
        set userCustomArguments "-groupBy=nameString -separate=nameString $passed3 $passed4"
        APSExec -unixCommand "quickSDDSplot -dataFileList [list $dataFileList] \
            -userCustomArguments [list $userCustomArguments] \
            -xNameFilter S8B:P5:scdu:ave_sum.VAL -yNameFilter *$Plane"
    }
}

proc APSValSimple {args} {
    APSStrictParseArguments {inputValue outputValue}
    if {[scan $inputValue %f out] != 1} {
        uplevel "set $outputValue 0"
    } else {
        uplevel "set $outputValue $out"
    }
}

proc APSLabeledEntryGrid { widget args } {
    global apsContextHelp
    set parent ""
    set noPack 0
    set packOption "-side top -fill x"
    set labelList ""
    set variableList ""
    set contextHelp ""
    set fileButtons 0
    APSStrictParseArguments {parent noPack packOption labelList variableList contextHelp fileButtons}
    
    if {$contextHelp != ""} {
        set apsContextHelp($parent$widget) $contextHelp
    }
    if {$parent == ""} {
        toplevel $widget -bd 1
        wm title $widget $label
    } else {
        frame $parent$widget -bd 1
        if {!$noPack} {
            eval pack $parent$widget $packOption
        }
    }
    set row 0
    foreach label $labelList variable $variableList {
        label $parent$widget.label$row -text $label
        entry $parent$widget.entry$row -relief sunken -textvariable $variable
        grid $parent$widget.label$row -column 0 -row $row -sticky e
        grid $parent$widget.entry$row -column 1 -row $row -sticky ew
        if {$fileButtons} {
            button $parent$widget.button$row -text "F"
            grid $parent$widget.button$row -column 2 -row $row
        }
        incr row
    }
    grid columnconfigure $parent$widget 1 -weight 1
}

proc archiveFiles {args} {
    global output archive plane maxDCCT minDCCT cISoutput
    set tempArchive /tmp/[APSTmpString]
    if {($archive(Options) == "raw") || ($archive(Options) == "fit")} {
        if {![file isfile $output]} {
            APSSetVarAndUpdate status "archiveFiles: $output is not a file"
            return
        }
        file copy -force -- $output $tempArchive
        exec gzip -f $tempArchive
        if {[catch [file copy -- $tempArchive.gz /home/helios/oagData/sr/offsetAdjustmentData/dataFiles/$archive(Raw)] results]} {
            APSSetVarAndUpdate status "Error: $results"
            file delete -- $tempArchive $tempArchive.gz
            return
        }
        file delete -- $tempArchive $tempArchive.gz
        APSSetVarAndUpdate status "Raw data file archived at\n/home/helios/oagData/sr/offsetAdjustmentData/dataFiles/"
    }
    if {$archive(Options) == "fit"} {
        if {[catch {doIntenScanFits -input $output -plane $plane -maxDCCT $maxDCCT -minDCCT $minDCCT} results]} {
            APSSetVarAndUpdate status "Error: $results"
            return
        }
        file copy -force -- $output.fitValues.$plane $tempArchive
        exec gzip -f $tempArchive
        if {[catch [file copy -- $tempArchive.gz /home/helios/oagData/sr/offsetAdjustmentData/dataFiles/$archive(Fit)] results]} {
            APSSetVarAndUpdate status "Error: $results"
            file delete -- $tempArchive $tempArchive.gz
            return
        }
        file delete -- $tempArchive $tempArchive.gz
        APSSetVarAndUpdate status "Fitted data file archived at\n/home/helios/oagData/sr/offsetAdjustmentData/dataFiles/"
    }
    if {$archive(Options) == "comb"} {
        if {![file isfile $cISoutput]} {
            APSSetVarAndUpdate status "archiveFiles: $cISoutput is not a file"
            return
        }
        set fID [sdds open $cISoutput]
        if [catch {sdds getParameter $fID xRawFile -page 1} xRawFile] {
            set xRawFile ""
        }
        if [catch {sdds getParameter $fID yRawFile -page 1} yRawFile] {
            set yRawFile ""
        }
        sdds close $fID
        if {([llength $xRawFile]) && ([llength $yRawFile]) && \
              ([file exists $xRawFile]) && ([file exists $yRawFile])} {
            if {$xRawFile != $yRawFile} {
                set archive(xRawFile) "intenScanDataRaw-x-$archive(Time)-$archive(Buckets)+$archive(Number)x$archive(Multiplicity)$archive(Singlet2).gz"
                set archive(yRawFile) "intenScanDataRaw-y-$archive(Time)-$archive(Buckets)+$archive(Number)x$archive(Multiplicity)$archive(Singlet2).gz"
                file copy -force -- $xRawFile ${tempArchive}2
                file copy -force -- $yRawFile ${tempArchive}3
                exec gzip -f ${tempArchive}2
                exec gzip -f ${tempArchive}3
                if {[catch [file copy -- ${tempArchive}2.gz \
                              /home/helios/oagData/sr/offsetAdjustmentData/dataFiles/$archive(xRawFile)] results]} {
                    APSSetVarAndUpdate status "Error: $results"
                    file delete -- ${tempArchive}2 ${tempArchive}3 ${tempArchive}2.gz ${tempArchive}3.gz
                    return
                }
                if {[catch [file copy -- ${tempArchive}3.gz \
                              /home/helios/oagData/sr/offsetAdjustmentData/dataFiles/$archive(yRawFile)] results]} {
                    APSSetVarAndUpdate status "Error: $results"
                    file delete -- ${tempArchive}2 ${tempArchive}3 ${tempArchive}2.gz ${tempArchive}3.gz
                    return
                }
            } else {
                set archive(xRawFile) "intenScanDataRaw-$archive(Time)-$archive(Buckets)+$archive(Number)x$archive(Multiplicity)$archive(Singlet2).gz"
                set archive(yRawFile) $archive(xRawFile)
                file copy -force -- $xRawFile ${tempArchive}2
                exec gzip -f ${tempArchive}2
                if {[catch [file copy -- ${tempArchive}2.gz \
                              /home/helios/oagData/sr/offsetAdjustmentData/dataFiles/$archive(xRawFile)] results]} {
                    APSSetVarAndUpdate status "Error: $results"
                    file delete -- ${tempArchive}2 ${tempArchive}2.gz
                    return
                }
            }
            file delete -- ${tempArchive}2 ${tempArchive}3 ${tempArchive}2.gz ${tempArchive}3.gz
            APSSetVarAndUpdate status "Raw data file archived at\n/home/helios/oagData/sr/offsetAdjustmentData/dataFiles/"
            exec sddsconvert $cISoutput -pipe=out -delete=parameters,xRawFile,yRawFile \
              | sddsprocess -pipe=in $tempArchive \
              -print=parameter,xRawFile,$archive(xRawFile) \
              -print=parameter,yRawFile,$archive(yRawFile)
        } else {
            APSSetVarAndUpdate status "Unable to archive associated Raw data files"
            file copy -force -- $cISoutput $tempArchive
        }
        exec gzip -f $tempArchive
        if {[catch [file copy -- $tempArchive.gz /home/helios/oagData/sr/offsetAdjustmentData/dataFiles/$archive(Comb)] results]} {
            APSSetVarAndUpdate status "Error: $results"
            file delete -- $tempArchive $tempArchive.gz
            return
        }
        file delete -- $tempArchive $tempArchive.gz
        APSSetVarAndUpdate status "Combined fit data file archived at\n/home/helios/oagData/sr/offsetAdjustmentData/dataFiles/"
        
    }
}

proc archiveData {args} {
    global output archive archiveOptions plane
    APSStrictParseArguments {}
    destroy .archive
    APSDialogBox .archive -name "Archive file" \
	-okCommand {archiveFiles} \
	-cancelCommand {APSSetVarAndUpdate status "Archive operation canceled"}
    set w .archive.userFrame
    set archive(Buckets) 1
    set archive(Number) 22
    set archive(Multiplicity) 1
    set archive(Singlet) ""
    set archive(Singlet2) ""
    grid [label $w.buckets -text "BPM bunches:"] -column 0 -row 0 -sticky e
    grid [label $w.number -text "Number:"] -column 0 -row 1 -sticky e
    grid [label $w.multiplicity -text "Multiplicity:"] -column 0 -row 2 -sticky e
    grid [label $w.singlets -text "Singlet Interval:"] -column 0 -row 3 -sticky e
    grid [entry $w.entryBuckets -textvariable archive(Buckets) -width 5] -column 1 -row 0 -sticky w
    grid [entry $w.entryNumber -textvariable archive(Number) -width 5] -column 1 -row 1 -sticky w
    grid [entry $w.entryMult -textvariable archive(Multiplicity) -width 5] -column 1 -row 2 -sticky w
    grid [entry $w.entrySinglet -textvariable archive(Singlet) -width 5] -column 1 -row 3 -sticky w
    APSRadioButtonFrame .rawOrFit -parent $w -noPack 1 -label "" \
	-buttonList {"Raw data only" "Intensity fit and Raw data" "Combined fit and Raw data"} \
	-valueList "raw fit comb" -variable archive(Options)
    grid $w.rawOrFit -column 1 -row 0 -rowspan 4
    set archive(Time) [clock format [clock seconds] -format "%Y-%m%d-%T"]
    set archive(TimeRaw) "intenScanDataRaw-$archive(Time)"
    set archive(TimeFit) "intenScanDataFit-$plane-$archive(Time)"
    set archive(TimeComb) "intenScanDataComb-$archive(Time)"
    set archive(Raw) "$archive(TimeRaw)-$archive(Buckets)+$archive(Number)x$archive(Multiplicity).gz"
    set archive(Fit) "$archive(TimeFit)-$archive(Buckets)+$archive(Number)x$archive(Multiplicity).gz"
    set archive(Comb) "$archive(TimeComb)-$archive(Buckets)+$archive(Number)x$archive(Multiplicity).gz"
    grid [label $w.labelFilename -text "Raw Data Filename:"] -column 0 -row 4 -sticky e
    grid [entry $w.filename -textvariable archive(Raw) -width 50] -column 1 -row 4 -sticky ew
    grid [label $w.labelFilenameFit -text "Intensity Fit Filename:"] -column 0 -row 5 -sticky e
    grid [entry $w.filenameFit -textvariable archive(Fit) -width 50] -column 1 -row 5 -sticky ew
    grid [label $w.labelFilenameComb -text "Combined Fit Filename:"] -column 0 -row 6 -sticky e
    grid [entry $w.filenameComb -textvariable archive(Comb) -width 50] -column 1 -row 6 -sticky ew
    grid columnconfigure $w 1 -weight 1
    foreach option "Buckets Number Mult Singlet" {
        bindtags $w.entry$option "Entry . all $w.entry$option"
        bind $w.entry$option <Key> {
            if {$archive(Singlet) != ""} {
                set archive(Singlet2) "-$archive(Singlet)"
            } else {
                set archive(Singlet2) ""
            }
            set archive(Raw) "$archive(TimeRaw)-$archive(Buckets)+$archive(Number)x$archive(Multiplicity)$archive(Singlet2).gz"
            set archive(Fit) "$archive(TimeFit)-$archive(Buckets)+$archive(Number)x$archive(Multiplicity)$archive(Singlet2).gz"
            set archive(Comb) "$archive(TimeComb)-$archive(Buckets)+$archive(Number)x$archive(Multiplicity)$archive(Singlet2).gz"
        }
    }
}

proc SetDailyDirectory {} {
    global output cISoutput xfile yfile cis outputDir 
#iSFinput
    set outputDir [APSGoToDailyDirectory -subdirectory intenScan]

    set output [file join $outputDir [file tail $output]]
# set iSFinput $output
    set xfile ${output}.fitValues.x
    set yfile ${output}.fitValues.y
    set cISoutput ${output}.fitValues
    update
}

proc DisplayReminders {} {
    APSInfoWindow .reminders -name "Reminders..." \
	-infoMessage "Before pressing the RUN button:\n\n1) Turn off offset adjustment process\n2) run orbit correction with lower gain or longer interval, say 0.2 and 2.5 seconds.\n3) Recommended initial S39 scraper position: 4.44 cm\n4) Target lifetime: 20 minutes." \
	-modal 0
}

APSApplication . -name SRBPMIntensityDependence \
    -version $CVSRevisionAuthor \
    -overview "This application does data collection for BPM data vs intensity.  The intensity variation is typically accomplished through reduction of the lifetime by use of scrapers; this is done manually by the user."

set w .userFrame
set status Ready.
set plane "x"

APSScrolledStatus .status \
    -parent $w \
    -textVariable status -width 90 \
    -height 25 \
    -packOption "-side top -fill both -expand true"
pack configure $w.status.frame \
    -fill both \
    -expand true
set widgetList [APSTabFrame .tn1 -parent $w -label "" -labelList {"Measurement" "Fitting" "Install"} -height 300]
set tabPage(Measurement) [lindex $widgetList 0]
set tabPage(Fitting) [lindex $widgetList 1]
set tabPage(Install) [lindex $widgetList 2]

#APSFrame .iDirFrame \
#    -parent $tabPage(Measurement) \
#    -label "SRBPM Intensity Dependence" \
#    -packOption "-side top -fill x"
APSFrame .iDFrame \
    -parent $tabPage(Measurement) \
    -label "Do Intensity Scan" \
    -packOption "-side top -fill x"
APSFrame .iPlotRawFrame \
    -parent $tabPage(Measurement) \
    -label "\nPlot Intensity Scan" \
    -packOption "-side top -fill x"
APSFrame .iSFFrame \
    -parent $tabPage(Fitting)  \
    -label "\nDo Intensity Scan Fits" \
    -packOption "-side top -fill x"
APSFrame .iPlotFrame \
    -parent $tabPage(Fitting) \
    -label "\nPlot Scan Fits" \
    -packOption "-side top -fill x"
APSFrame .cISFrame \
    -parent $tabPage(Install) \
    -label "\nCombine Intensity Scans" \
    -packOption "-side top -fill x" \
    -contextHelp "Does an interpolation of fitted values (files *.fitValues.\[xy\]) and combines everything in a file. This output file is to be used by the offset compensation application."

set outputDir "[pwd]"
#set wiD $tabPage(Measurement).iDirFrame.frame
#APSLabeledEntryGrid .outputFrame \
#    -parent $wiD \
#    -labelList {"Output directory:"} \
#    -variableList "outputDir" \
#    -contextHelp "Enter directory name where data files will be written. Normally one presses the\"Go to daily directory\" button for automatic generation."

set wiD $tabPage(Measurement).iDFrame.frame
set waveforms 0
APSLabeledEntryGrid .outputfile \
    -parent $wiD \
    -labelList {"Output filename:"} \
    -variableList "output" \
    -contextHelp "Normally one chooses a name such as scan01."
APSButton .daily \
    -parent $wiD \
    -packOption "-side top -anchor w" \
    -text "Go to daily directory" \
    -command SetDailyDirectory \
    -contextHelp "Setting daily directory in which to put data files."

APSRadioButtonFrame .wfs \
    -parent $wiD \
    -variable waveforms \
    -orientation horizontal \
    -label "Collect BBCM waveforms?" \
    -valueList {1 0} \
    -buttonList {Yes No} \
    -contextHelp "Specifies whether to collect current transformer waveforms from bunch-by-bunch CM." \
    -packOption "-side top"
APSButton .stop \
    -parent $wiD \
    -text Stop \
    -command "StopProcess" \
    -contextHelp "Stops the subprocess that is collecting data, and terminates other data taking." 
APSDisableButton $wiD.stop.button
APSButton .run \
    -parent $wiD \
    -text Run \
    -command RunExperiment \
    -contextHelp "Starts the experiment, recording data into the named file." 
APSButton .runPrompt \
    -parent $wiD \
    -text "Run with prompting" \
    -command "RunExperiment -prompt 1" \
    -contextHelp "Starts the experiment in an interactive mode that requires you to press the continue button before each set of data is taken." 
APSButton .continue \
    -parent $wiD \
    -text "Continue" \
    -command "set continueRun 1" \
    -contextHelp "In prompted running mode, used to indicate that the script should take data." 
APSDisableButton $wiD.continue.button
APSButton .archive \
    -parent $wiD \
    -text "Archive" \
    -command {set archive(Options) raw;archiveData} \
    -contextHelp "Archives the output file." 
APSButton .reminder \
    -parent $wiD \
    -text "Reminders" \
    -command {DisplayReminders} \
    -contextHelp "Creates a window of reminders before starting measurement."

set isf $tabPage(Fitting).iSFFrame.frame
#set iSFinput "[pwd]/scan01"
APSLabeledEntryGrid .iSFinputfile \
    -parent $isf \
    -labelList {"Input filename:"} \
    -variableList output \
    -fileButtons 1 \
    -contextHelp "Type in the output of an intensity dependence data file. Normally this is set automatically after a intensity scan is complete. Such a filename would be named "
$isf.iSFinputfile.button0 configure \
    -command  {set filedialog [APSFileSelectDialog [APSUniqueName .] -pattern {*} -path /home/helios/oagData/sr/offsetAdjustmentData/dataFiles -width 70];\
		   if {[string compare $filedialog ""] != 0} {set output $filedialog}}
set isf3 $isf.frame3
frame $isf3
pack $isf3 -fill x
APSButton .iSFStart \
    -parent $isf3 \
    -text "Do intensity scan fits" \
    -command {doIntenScanFits \
		  -input $output \
		  -plane $plane \
		  -maxDCCT $maxDCCT \
		  -minDCCT $minDCCT} \
    -packOption "-side left" -noPack 1
APSRadioButtonFrame .iSFRadioButtonFrame \
    -parent $isf3 \
    -noPack 1 \
    -label "Plane" \
    -variable plane \
    -buttonList "x y" \
    -valueList "x y" \
    -packOption "-side left" \
    -orientation horizontal
set minDCCT "40"
APSLabeledEntry .iSFminDDCT \
    -parent $isf3 \
    -noPack 1 \
    -label "Min DCCT" \
    -textVariable minDCCT \
    -width 4 \
    -packOption "-side left"
set maxDCCT "100"
APSLabeledEntry .iSFmaxDDCT \
    -parent $isf3 \
    -noPack 1 \
    -label "Max DCCT" \
    -textVariable maxDCCT \
    -width 4 \
    -packOption "-side left"
grid $isf3.iSFStart -column 0 -row 0 -sticky we
grid $isf3.iSFRadioButtonFrame -column 1 -row 0
grid $isf3.iSFminDDCT -column 2 -row 0
grid $isf3.iSFmaxDDCT -column 3 -row 0
for {set i 0} {$i < 4} {incr i} {
    grid columnconfigure $isf3 $i -weight 1
}
############
set plottype raw
set offset 1
set samescale 1
set presentOrbitConfig 0
set minx 0
set maxx 0
set miny 0
set maxy 0

set isf $tabPage(Measurement).iPlotRawFrame.frame
APSCheckButtonFrame .plotoptions \
    -parent $isf \
    -label "Plot format" \
    -buttonList {"Y offset   " "Y samescale   " "Present orbit config"} \
    -variableList "offset samescale presentOrbitConfig" \
    -orientation horizontal
APSRadioButtonFrame .iSFRadioButtonFrame \
    -parent $isf \
    -noPack 0 \
    -label "      Plane" \
    -variable plane \
    -buttonList "x y" \
    -valueList "x y" \
    -orientation horizontal
APSButton .plotraw \
    -parent $isf \
    -text "Plot" \
    -command {PlotData -PlotType raw -DataFile $output -Plane $plane \
		  -MinX $minx -MaxX $maxx -MinY $miny -MaxY $maxy \
		  -Offset $offset -SameScale $samescale} \
    -packOption "-side left"
APSButton .quickPlot \
    -parent $isf \
    -text "Quick SDDS Plot" \
    -command {PlotData -PlotType raw -DataFile $output -Plane $plane \
		  -MinX $minx -MaxX $maxx -MinY $miny -MaxY $maxy \
		  -Offset $offset -SameScale $samescale -quickSDDS 1} \
    -packOption "-side left"
APSLabeledEntry .lowx \
    -parent $isf \
    -label "  Min X" \
    -textVariable minx \
    -width 5 \
    -packOption "-side left"
APSLabeledEntry .highx \
    -parent $isf \
    -label "  Max X" \
    -textVariable maxx \
    -width 5 \
    -packOption "-side left"
APSLabeledEntry .lowy \
    -parent $isf \
    -label "  Min Y" \
    -textVariable miny \
    -width 5 \
    -packOption "-side left"
APSLabeledEntry .highy \
    -parent $isf \
    -label "  Max Y" \
    -textVariable maxy \
    -width 5 \
    -packOption "-side left"


set isf $tabPage(Fitting).iPlotFrame.frame
APSRadioButtonFrame .plotframe \
    -parent $isf \
    -label "Plot format" \
    -variable plottype \
    -buttonList {"Raw data only  " "Intensity fit only  " "Both     "} \
    -valueList "raw fit both" -orientation horizontal
APSCheckButtonFrame .plotoptions \
    -parent $isf \
    -buttonList {"Y offset   " "Y samescale   " "Present orbit config"} \
    -variableList "offset samescale presentOrbitConfig" \
    -orientation horizontal \
    -label "\t   "
APSButton .plotraw \
    -parent $isf \
    -text "Plot" \
    -command {PlotData -PlotType $plottype -DataFile $output -Plane $plane \
		  -MinX $minx -MaxX $maxx -MinY $miny -MaxY $maxy \
		  -Offset $offset -SameScale $samescale} \
    -packOption "-side left"
APSButton .quickPlot \
    -parent $isf \
    -text "Quick SDDS Plot" \
    -command {PlotData -PlotType $plottype -DataFile $output -Plane $plane \
		  -MinX $minx -MaxX $maxx -MinY $miny -MaxY $maxy \
		  -Offset $offset -SameScale $samescale -quickSDDS 1} \
    -packOption "-side left"
APSLabeledEntry .lowx \
    -parent $isf \
    -label "  Min X" \
    -textVariable minx \
    -width 5 \
    -packOption "-side left"
APSLabeledEntry .highx \
    -parent $isf \
    -label "  Max X" \
    -textVariable maxx \
    -width 5 \
    -packOption "-side left"
APSLabeledEntry .lowy \
    -parent $isf \
    -label "  Min Y" \
    -textVariable miny \
    -width 5 \
    -packOption "-side left"
APSLabeledEntry .highy \
    -parent $isf \
    -label "  Max Y" \
    -textVariable maxy \
    -width 5 \
    -packOption "-side left"

set cis $tabPage(Install).cISFrame.frame
set output "$outputDir/scan01"
set xfile "$outputDir/scan01.fitValues.x"
set yfile "$outputDir/scan01.fitValues.y"
set cISoutput "$outputDir/scan01.fitValues"
APSLabeledEntryGrid .cISfile \
    -parent $cis \
    -labelList {"X-file:" "Y-file:"} \
    -variableList "xfile yfile" \
    -fileButtons 1
$cis.cISfile.button0 configure \
    -command  {set filedialog [APSFileSelectDialog [APSUniqueName .] -pattern {*.fitValues.x} -width 70];\
		   if {[string compare $filedialog ""] != 0} {set xfile $filedialog}}
$cis.cISfile.button1 configure \
    -command  {set filedialog [APSFileSelectDialog [APSUniqueName .] -pattern {*.fitValues.y} -width 70];\
		   if {[string compare $filedialog ""] != 0} {set yfile $filedialog}} 
APSLabeledEntryGrid .cISoutputfilename \
    -parent $cis \
    -labelList {"Output filename:"} \
    -variableList "cISoutput"
APSButton .cISStart \
    -parent $tabPage(Install).cISFrame.frame \
    -text "Combine Intensity Scan Fits" \
    -packOption "-side left"\
    -command {combineIntenScans -xfile $xfile -yfile $yfile -output $cISoutput}
APSButton .archive \
    -parent $tabPage(Install).cISFrame.frame \
    -text "Archive" \
    -command {set archive(Options) comb;archiveData} \
    -contextHelp "Archives the combined fit file." 

set continueRun 0
set continueButton $tabPage(Measurement).iDFrame.frame.continue.button

dp_atexit append StopProcess

proc BPMArgList {args} {
    set sector 1
    set plane x
    APSStrictParseArguments {sector plane}
    if [string compare $plane y]==0 {
        set list1 [list A:P0 A:P1 A:P2 A:P3 A:P4 B:P5 B:P4 B:P3 B:P2 B:P1 B:P0 BM:P1 BM:P2]
    } else {
        set list1 [list A:P0 A:P1 A:P2 A:P3 A:P4 B:P5 B:P4 B:P3 B:P2 B:P1 B:P0]
    }

    set list2 ""
    foreach item $list1 {
        lappend list2 S${sector}${item}:msAve:$plane
    }
    return $list2
}
