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

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

# $Log: not supported by cvs2svn $
# Revision 1.10  2006/09/21 20:39:57  soliday
# Updated because of PV name changes.
#
# Revision 1.9  2004/10/03 20:44:35  emery
# Changed the widget for profile and video selection.
# Removed unnecessary monitor files.
# REplaced the tune measurement with an external getxytunes.
#
# Revision 1.8  2004/10/03 17:56:04  emery
# Changed default directory for monitorDir
#
# Revision 1.7  2002/03/26 17:14:32  emery
# Changed argument of togglePulseMagnet from PARto.. to Gunto..
#
# Revision 1.6  2001/02/17 00:08:31  emery
# Corrected daily directory button definition, and make
# sure that the daily directory button is placed next to the
# directory entry slot.
#
# Revision 1.5  2001/01/17 23:24:53  emery
# Changed sr:vid:* PVs to S:VID1:*.
# Added procedure StopProcess.
#
# Revision 1.4  2000/09/06 05:11:45  emery
# Added more checks on filename existance.
#
# Revision 1.3  2000/08/03 20:50:12  emery
# Added dryrun variable. Fixed collectvid2* arguments and
# variables. Changed sr:vid* PVs to S:VID* Added timer with update.
# Added -pend=5 to cavget/put commands. Corrected names of
# input files in the new sddsmonitor commands.
#
# Revision 1.2  2000/08/01 19:00:34  emery
# Added the ability to select AM pinhole and Streak camera
# for sr:vid 2. This should be made more general later.
# Moved the twait variable command of the sddsexperiment
# after all the other shorter data acquisition is complete.
# Added more monitor file entry boxes. We need separate
# monitor files for AM pinhole and Streak camera since
# the data comes from the same PVs.
#

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

proc MakeInputFrame {widget args} {
    global monitorInterval InjectionInterval outputDir monitorDir monitorFile 
    global experimentDir experimentFile
    global root index comment target
    set parent ""
    APSStrictParseArguments {parent}
    
   #set outputDir .
    APSFrame $widget -parent $parent -label "Input parameters"
    set w $parent$widget.frame
    
    APSLabeledEntry .outputDir -parent $w \
      -label "Output directory:" -textVariable outputDir \
      -contextHelp "Enter a name for the output file directory." -width 50
    APSButton .daily -parent $w.outputDir -packOption "-anchor e" \
      -text "daily"  -size small \
      -command {set outputDir [APSGoToDailyDirectory -subdirectory currentScans]}
    APSLabeledEntry .monitorDir -parent $w \
      -label "Monitor directory:" -textVariable monitorDir \
      -contextHelp "Enter a name of the monitor file directory." -width 50
    APSLabeledEntry .monitorFile -parent $w \
      -label "Monitor file:" -textVariable monitorFile \
      -contextHelp "Enter a name of the monitor file." -width 50

    APSLabeledEntry .experimentDir -parent $w \
      -label "Experiment directory:" -textVariable experimentDir \
      -contextHelp "Enter a name of the experiment file directory." -width 50
    APSLabeledEntry .experimentFile -parent $w \
      -label "Experiment file:" -textVariable experimentFile \
      -contextHelp "Enter a name of the experiment file." -width 50

    APSLabeledEntry .root -parent $w -label "Root name of file: " \
      -textVariable root \
      -contextHelp "Enter the root name of the file."
    APSLabeledEntry .index -parent $w -label "Index: " -textVariable index \
      -contextHelp "Enter the index (minus 1) to be part of the name of the output file. The index is incremented by 1 before execution."
    APSLabeledEntry .comment -parent $w -label "Comment: " \
      -textVariable comment \
      -width 55 \
      -contextHelp "Enter a comment to be written as a parameter to the output file."
    APSLabeledEntry .monInterval -parent $w -label "Monitor interval: " \
      -textVariable monitorInterval \
      -contextHelp "Enter the monitoring interval."
    APSLabeledEntry .injInterval -parent $w -label "Injection interval: " \
      -textVariable injectionInterval \
      -contextHelp "Enter the injection interval."
    APSLabeledEntry .injPulses -parent $w -label "Injection pulses: " \
      -textVariable injectionPulses \
      -contextHelp "Enter the number of injection pulses. Enter 0 if you don't want to inject at all, for example, if yoiu want to scrape down the beam."
    APSLabeledEntry .target -parent $w -label "Target current (mA): " \
      -textVariable target \
      -contextHelp "Enter the target single bunch current."
    APSRadioButtonFrame .waveform -parent $w -label "Waveform to collect" \
      -buttonList {x-tune y-tune xy-tune s-tune none} -valueList {HTUNE VTUNE HVTUNE STUNE ""} \
      -orientation horizontal -variable waveform \
      -contextHelp "Choose whether to collect x-tune data or synchrotron tune data."
    APSLabeledEntry .tuneWait -parent $w -label "Time allowed for tune measurement: " \
      -textVariable tuneWait \
      -contextHelp "Enter the time required for tune. This applies only to synchrotron tunes. For transverse tunes, the wait is included in the script getxytunes."
    APSRadioButtonFrame .vidBM -parent $w -label "Video for BM profile" \
      -buttonList {None S:VID1 S:VID2 S:VID3} -valueList {None S:VID1 S:VID2 S:VID3} -orientation horizontal -variable collectBMVideo \
      -contextHelp "Choose whether to collect BM profile and its frame grabber."

    APSRadioButtonFrame .vidAM -parent $w -label "Video for AM profile" \
      -buttonList {None S:VID1 S:VID2 S:VID3} -valueList {None S:VID1 S:VID2 S:VID3} -orientation horizontal -variable collectAMVideo \
      -contextHelp "Choose whether to collect AM profile and its frame grabber."

    APSRadioButtonFrame .vidID -parent $w -label "Video for ID profile" \
      -buttonList {None S:VID1 S:VID2 S:VID3} -valueList {None S:VID1 S:VID2 S:VID3} -orientation horizontal -variable collectIDVideo \
      -contextHelp "Choose whether to collect ID profile and its frame grabber."

    APSRadioButtonFrame .vidStreak -parent $w -label "Video for Streak profile" \
      -buttonList {None S:VID1 S:VID2 S:VID3} -valueList {None S:VID1 S:VID2 S:VID3} -orientation horizontal -variable collectStreakVideo \
      -contextHelp "Choose whether to collect Streak profile and its frame grabber."

    return
}

proc SetupInjection {} {
    if [catch {exec cavput -list=Mt:SRinjectMultiExcludSIS1BO=0 -pend=5 \
             } result ] {
        return -code error "Setupinjection: $result"
    }
    # make sure of beam switch state.
   # if [catch {APSSRGetBeamSwitchState} switchState] {
   #     return -code error "SetupTopup: $switchState"
   # }
   # APSSetVarAndUpdate status "Switch state: $switchState"
#    if [string equal $switchState dump] {
#        return -code error "SetupTopup: Error: beam is at the dump."
#    }
    TogglePulsedMagnetEnables -location GuntoBoosterExt
    if [catch {SetupMultiBunchInject} result] {
        return  -code error "SetupTopup: $result"
    }
    return -code ok
}

proc SetupMultiBunchInject {} {
    global target

    if [catch {exec cavput -pend=10 -list=Mt:SR \
                 -list=injectCurrentLimitAO=$target,injectMaxCyclesAO=1,injectModeBO=Single,CurrentLimitModeBO=Estop,injectNumBunchesAO.VAL=1 \
             } result] {
        return  -code error "SetupMultiBunchInject: Error setting IOC parameters: $result"
    }
    if [catch {exec cavput -list=Mt:SRinjectZeroBucketsBO=1 \
             } result] {
        return  -code error "SetupMultiBunchInject: $result"
    }
    return
}

proc DoCurrentScan {args} {
    set monitorDir .
    set experimentDir .
    set collectBMVideo None
    set collectAMVideo None
    set collectIDVideo None
    set collectStreakVideo None
    APSParseArguments {outputDir root index monitorDir monitorFile \
                         experimentDir experimentFile \
                         target monitorInterval injectionInterval \
                         waveform tuneWait \
                         injectionPulses \
                         dryRun \
                         collectBMVideo collectAMVideo collectIDVideo collectStreakVideo
                         comment abortVariable prompt}

    global $abortVariable continueButton monitorPid monitorPid2AM monitorPid2Streak
    global ExperimentDone
    set cameraPause 20
    if {![string length $outputDir] || ![string length $root]} {
        APSSetVarAndUpdate status "Output directory or root not given."
        return
    }
    if ![string length $monitorFile] {
        APSSetVarAndUpdate status "Main monitor file not given."
        return
    }
    if ![file exists $monitorDir/$monitorFile] {
        APSSetVarAndUpdate status "Can't find file $monitorDir/$monitorFile."
        return
    }
    set outputFile $root-[format %03ld $index]
    if [file exists $outputDir/$outputFile] {
        APSSetVarAndUpdate status "File $outputDir/$outputFile exists."
        return
    }
    if [file exists $outputDir/$outputFile] {
        APSSetVarAndUpdate status "File $outputDir/$outputFile exists."
        return
    }
    
    SetupInjection

# setup VSA
    if {[string length $waveform] && $waveform=="STUNE"} {
        APSSetVarAndUpdate status "Setting up VSA for $waveform. Wait 15 seconds..." 
        set streamID [APSOpenTelnetStream -IPaddress hpvecsr]
        switch $waveform {
            HVTUNE -
            HTUNE {
                APSWriteToTelnetStream -command "MMEM:LOAD:STAT 1,'INT:TUNES.STA'" -streamID $streamID
            }
            VTUNE {
                APSWriteToTelnetStream -command "MMEM:LOAD:STAT 1,'INT:TUNES.STA'" -streamID $streamID
            }
            STUNE {
                # special synch frequency setup for single bunch
                APSWriteToTelnetStream -command "MMEM:LOAD:STAT 1,'NVRAM:FSYNCHSI'" -streamID $streamID
            }
        }
        APSWaitWithUpdate -waitSeconds 15 -updateInterval 1
        APSSetVarAndUpdate status "VSA ready for $waveform." 
    }

    if [catch {set monitorPid [exec sddsmonitor $monitorDir/$monitorFile $outputDir/$outputFile \
                          -step=10000 -interval=$monitorInterval \
                          "-comment=Comment,[APSMakeSafeQualifierString $comment]" &] \
             } result ] {
        APSSetVarAndUpdate status $result
        return
    }
    APSSetVarAndUpdate status "sddsmonitor launched..."
    update

    global S35DCCT
    if {[pv linkw S35DCCT S-DCCT:CurrentM]!=0} {
        return -code error "Error connecting to PVs S-DCCT:CurrentM."
    }

    if {[pv getw S35DCCT]!=0} {
        return -code error "Error getting S35DCCT values."
    }
    set S35DCCT $S35DCCT
    set rfFrequency [exec cavget -list=A014-IETS:BTC:SRSetFreqM -float=%.0f -pendIoTime=5]
    set HTune 0.185
    set VTune 0.228
    set harmonic 1316
    set HTuneFreq [expr ($rfFrequency/1296.0)*($harmonic - $HTune)]
    set VTuneFreq [expr ($rfFrequency/1296.0)*($harmonic - $VTune)]
    set i 0

# don't need a conditional for current
    while {1} {
        if {[string length $abortVariable] && [subst \$$abortVariable]} {
            APSSetVarAndUpdate status "Killing sddsmonitor processes..."
            StopProcesses
            set $abortVariable 0
            return
        }
        # do experiment 
        if {[string length $experimentFile]} {
            set experimentRoot [file root $experimentFile]
            set experimentIn $experimentDir/$experimentFile
            if ![file exists $experimentIn] {
                APSSetVarAndUpdate status "Can't find experiment file $experimentIn"
                return
            }
            set experimentOut $outputDir/$outputFile-$experimentRoot-[format %03ld $i]
            set ExperimentDone 0
            if {$dryRun} {
                APSExecLog .expExec -name "Experiment log" \
                  -cancelCallback "CleanUpExperiment -datafile $experimentOut" \
                  -abortCallback "CleanUpExperiment -datafile $experimentOut" \
                  -unixCommand "sddsexperiment -dryRun $experimentIn $experimentOut -verbose" \
                  -callback "CleanUpExperiment -datafile $experimentOut"  -width 80
            } else {
                APSExecLog .expExec -name "Experiment log" \
                  -cancelCallback "CleanUpExperiment -datafile $experimentOut" \
                  -abortCallback "CleanUpExperiment -datafile $experimentOut" \
                  -unixCommand "sddsexperiment $experimentIn $experimentOut -verbose" \
                  -callback "CleanUpExperiment -datafile $experimentOut"  -width 80
            }
            # Moved the tkwait command till after the profiles are collected.
            #        tkwait variable ExperimentDone
            update
        }
        # take beam profiles
        foreach profile {BM AM ID Streak} {
            set varName collect${profile}Video
            set vidName [set $varName]
            if {$vidName!="None"} {
                catch {exec cavget -list=${vidName}:opComments} comment 
                set profile $outputDir/$outputFile-${vidName}-[format %03ld $i]
                exec sddswmonitor $profile -step=1 \
                  -PV=${vidName}:xAxisWF,${vidName}:xFitWF,${vidName}:xDataWF,${vidName}:yAxisWF,${vidName}:yFitWF,${vidName}:yDataWF
                exec sddsprocess $profile \
                  -noWarning \
                  -def=para,S35DCCT,$S35DCCT \
                  -print=para,Comment,$comment \
                  "-print=para,CurrentString,I = %4.2f mA,S35DCCT"
                file delete $profile~
            }
        }

        # take tune spectrum
        if {[string length $waveform]} {
            switch $waveform {
                HVTUNE {
                    APSSetVarAndUpdate status "Taking tune data. Wait several seconds..."
                    exec getxytunes -root $outputDir/${outputFile}-[format %03ld $i] \
                      -description "$S35DCCT mA" \
                      -xTune .185 -yTune .23 \
                      -plotTunes 0 
                }
                HTUNE {
                    APSSetVarAndUpdate status "Taking tune data. Wait several seconds..."
                    exec getxytunes -root $outputDir/${outputFile}-[format %03ld $i] \
                      -description "$S35DCCT mA" \
                      -xTune .185 -yTune .23  \
                      -only x -plotTunes 0 
                }
                VTUNE {
                    APSSetVarAndUpdate status "Taking tune data. Wait several seconds..."
                    exec getxytunes -root $outputDir/${outputFile}-[format %03ld $i] \
                      -description "$S35DCCT mA" \
                      -xTune .185 -yTune .23  \
                      -only y -plotTunes 0 
                }
                STUNE {
                    APSSetVarAndUpdate status "Taking tune data. Wait several seconds..."
                    APSWriteToTelnetStream -command "ABOR;*WAI" -streamID $streamID
                    set syncTuneFile $outputDir/$outputFile-stune[format %03ld $i]
                    APSWaitWithUpdate -waitSeconds $tuneWait -updateInterval 1
                    exec hpVecTrace -unit=sr a $syncTuneFile
                    exec sddsprocess $outputDir/$outputFile-stune[format %03ld $i] \
                      -noWarning \
                      -def=para,S35DCCT,$S35DCCT \
                      "-print=para,CurrentString,I = %4.2f mA,S35DCCT"
                    catch {file delete ${syncTuneFile}~}
                }
            }
            APSSetVarAndUpdate status "Wait for the tunes to finish before continuing."
        }
        update
        if {[info exists ExperimentDone] && !$ExperimentDone} {
            APSSetVarAndUpdate status "Waiting for sddsexperiment to complete."
            tkwait variable ExperimentDone
        }
        update
        # variable injectionPulses should be set !=0 by user only if injection is desired.
        # i.e. scan current from zero.
        if {$injectionPulses!=0} {
            # inject pulses
            exec cavput -list=Mt:SRinjectMaxCyclesAO.VAL=$injectionPulses -pend=5
            APSSetVarAndUpdate status "Injecting $injectionPulses pulse(s)..."
            if {!$dryRun} {
                exec cavput -list=Mt:SRinjectMultiBO.VAL=1 -pend=1
            }
            # it takes about 3 seconds for the multi-bunch inject
            # to actually activate.
            APSWaitWithUpdate -waitSeconds $injectionInterval -updateInterval 1
        }
        pv getw S35DCCT
        set S35DCCT $S35DCCT
        
        update
        incr i
        if $prompt {
            APSEnableButton $continueButton
            bell
            APSSetVarAndUpdate status "Press continue to proceed..."
            tkwait variable continueRun
            APSDisableButton $continueButton
        }
    }

    if {[string length $waveform]} {
        APSCloseTelnetStream -streamID ${streamID}
    }
    APSSetVarAndUpdate status "Current target reached. Done."
    
}

proc CleanUpExperiment {args} {
    APSParseArguments {datafile}
    global ExperimentDone
    set ExperimentDone 1

    if [catch {exec /home/helios/BXYANG/studies/sddsDevelop/sddserrfit/sddserrfit $datafile -pipe=out \
                 -full \
                 -column=theta1,PMTcurrentGPIB	\
                 | sddsprocess -pipe=in $datafile.energySpread \
                 -print=para,sigmaGammaString,%.3e,sigmaGamma \
             } results] {
        APSSetVarAndUpdate status $results
        return
    }
    return
}

proc ProcessData {args} {
    APSParseArguments {outputDir root index}
    set outputFile $root-[format %03ld $index]
    set file $outputDir/$outputFile
    if ![file exists $file] {
        APSSetVarAndUpdate status "Can't find file $file"
        return
    }
    # sum the RF voltages
    exec sddsprocess $file -pipe=out \
      "-def=col,SRTotalGapVoltage,rfvolt_s40 rfvolt_s36 + rfvolt_s37 + rfvolt_s38 + 1000 /,units=MV" \
      "-proc=SRTotalGapVoltage,first,SRTotalGapVoltage" \
      "-print=para,SRVoltageString,Vrf \= %4.2lf MV,SRTotalGapVoltage" \
      "-print=para,Topline,APS Storage Ring Bunch Length vs Current %s,SRVoltageString" \
      -filter=col,S35DCCT,0,0.2,BunchLength,40,1e9,&,! \
      -filter=col,S35DCCT,2.0,1e9 \
      "-def=col,lnBunchLength,BunchLength ln" \
      "-def=col,lnCurrent,S35DCCT ln" \
      | tee $file.para \
      | sddspfit -pipe -col=lnCurrent,lnBunchLength -sigmas=.2,abs \
      | sddsprocess -pipe=in $file.fit \
      "-def=col,BunchLengthFit,lnBunchLengthFit exp" \
      "-def=col,Current,lnCurrent exp" \
      "-def=col,BunchLength,lnBunchLength exp,units=mA"

    exec sddsxref $file.fit $file.para -noWarning \
      -transfer=para,SRVoltageString,Topline

    exec sddsplot -lay=1,2 -sep=2 -labelsize=0.03 \
      -col=S35DCCT,BunchLength    -leg=ysymbol -grap=sym \
      -filter=col,S35DCCT,0.2,1e9 \
      $file \
      -col=Current,BunchLengthFit -leg=ysymbol -gra=line,type=1 \
      $file.fit \
      -topline=@Topline \
      -lspace=0.6,0.8,-0.4,0.5 -subtic=xdiv=4 \
      "-ylabel=RMS Bunch Length (psec)" "-xlab=Current (mA)" \
      -col=S35DCCT,BunchLength -leg=ysymbol \
      -filter=col,S35DCCT,0.2,1e9 \
      -mode=y=log,y=special,x=log,x=special\
      -gra=sym \
      $file \
      -col=Current,BunchLengthFit -leg=ysymbol -gra=line,type=1 \
      -mode=y=log,y=special,x=log,x=special \
      -lspace=0.1,0.3,0,0.9 \
      "-ylabel=RMS Bunch Length (psec)" "-xlab=Current (mA)" \
      -topline=@sddspfitLabel \
      $file.fit \
      -col=TimeOfDay,S35DCCT $file -gra=dots -leg \
      -col=TimeOfDay,BunchLength $file -gra=dots,sub=1 -yscale=id=bl -leg \
      &

}

proc StopProcesses {} {
    global processFlag monitorPid monitorPid2AM monitorPid2Streak
    APSEnableButton .userFrame.run.button
    APSEnableButton .userFrame.runPrompt.button
    APSDisableButton .userFrame.stop.button
    if ![string length $monitorPid] {
        APSSetVarAndUpdate status "Subprocess not running."
        return
    }
    APSSetVarAndUpdate status "Killing sddsmonitor..."
    if [catch {exec kill -KILL $monitorPid} result] {
        APSSetVarAndUpdate status $result
        APSSetVarAndUpdate status "The sddsmonitor process may have to be killed manually."
        set abortRun 0
        return
    }
    set monitorPid ""
    if {[info exists monitorPid2AM] && [string length $monitorPid2AM]} {
        APSSetVarAndUpdate status "Subprocess stopped."
        if [catch {exec kill -KILL $monitorPid2AM} result] {
            APSSetVarAndUpdate status $result
            APSSetVarAndUpdate status "The sddsmonitor process may have to be killed manually."
            set abortRun 0
            return
        }
        set monitorPid2AM ""
        APSSetVarAndUpdate status "Subprocess for S:VID2 AM stopped."
    }
    if {[info exists monitorPid2Streak] && [string length $monitorPid2Streak]} {
        if [catch {exec kill -KILL $monitorPid2Streak} result] {
            APSSetVarAndUpdate status $result
            APSSetVarAndUpdate status "The sddsmonitor process may have to be killed manually."
            set abortRun 0
            return
        }
        set monitorPid2Streak ""
        APSSetVarAndUpdate status "Subprocess for S:VID2 Streak stopped."
    }
}

set args $argv
set outputDir [APSGoToDailyDirectory -subdirectory currentScans]
set root "currentScan"
set monitorDir /home/helios/oagData/sr/currentScans/monitorFiles
#set monitorFile s35Monitor-2004-1003-131252.mon
set monitorFile s35Monitor-2014-1119.mon

set experimentDir .
set experimentFile monoScan.exp
set experimentFile ""
set dryRun 0
set index -1
set target 25
set comment "Test scan"
set monitorInterval 1
set injectionInterval 5
set injectionPulses 0
#set waveform STUNE
set waveform ""
set tuneWait 10
set collectBMVideo S:VID1
set collectAMVideo None
set collectIDVideo S:VID3
set collectStreakVideo S:VID2

set vidComment "BM source transverse profile"
set vid2AMComment "AM source transverse profile"
set vid2StreakComment "Streak camera profile"
set vid3Comment "ID source transverse profile"
set vid4Comment "BM streak camera"
APSParseArguments {outputDir root index monitorDir monitorFile \
                     experimentDir experimentFile \
                     target monitorInterval injectionInterval \
                     injectionPulses \
                     comment}


APSApplication . -name SRscanCurrent -version $CVSRevisionAuthor \
  -overview {Scan the stored current while taking monitor data. The current is varied externally, either by injection or scraping. There is an optional user-supplied experiment file that can be run for each prompt.}

set status Working
APSScrolledStatus .status -parent .userFrame -textVariable status -width 50
MakeInputFrame .input -parent .userFrame
set status "Ready."
set abortRun 0
update

APSButton .run -parent .userFrame -text Run -command \
  { \
      APSDisableButton .userFrame.run.button 
      APSDisableButton .userFrame.runPrompt.button 
      APSEnableButton .userFrame.stop.button
      incr index
      catch {DoCurrentScan -outputDir $outputDir \
               -root $root -index $index \
               -monitorDir $monitorDir \
               -monitorFile $monitorFile \
               -experimentDir $experimentDir \
               -experimentFile $experimentFile \
               -target $target \
               -dryRun $dryRun \
               -monitorInterval $monitorInterval \
               -injectionInterval $injectionInterval \
               -injectionPulses $injectionPulses \
               -waveform $waveform -tuneWait $tuneWait \
               -comment $comment \
               -collectBMVideo $collectBMVideo \
               -collectAMVideo $collectAMVideo \
               -collectIDVideo $collectIDVideo \
               -collectStreakVideo $collectStreakVideo \
               -abortVariable abortRun \
               -prompt 0} status
      update idletasks
      APSDisableButton .userFrame.stop.button 
      APSEnableButton .userFrame.run.button }

APSButton .runPrompt -parent .userFrame -text "Run with prompting" -command \
  { \
      APSDisableButton .userFrame.run.button 
      APSDisableButton .userFrame.runPrompt.button 
      APSEnableButton .userFrame.stop.button
      incr index
      catch {DoCurrentScan -outputDir $outputDir \
               -root $root -index $index \
               -monitorDir $monitorDir \
               -monitorFile $monitorFile \
               -experimentDir $experimentDir \
               -experimentFile $experimentFile \
               -target $target \
               -dryRun $dryRun \
               -monitorInterval $monitorInterval \
               -injectionInterval $injectionInterval \
               -injectionPulses $injectionPulses \
               -waveform $waveform -tuneWait $tuneWait \
               -comment $comment \
               -collectBMVideo $collectBMVideo \
               -collectAMVideo $collectAMVideo \
               -collectIDVideo $collectIDVideo \
               -collectStreakVideo $collectStreakVideo \
               -abortVariable abortRun \
               -prompt 1} status
      update idletasks
      APSDisableButton .userFrame.stop.button 
      APSEnableButton .userFrame.run.button 
      APSEnableButton .userFrame.runPrompt.button }

APSButton .continue -parent .userFrame -text "Continue" \
    -command "set continueRun 1" \
    -contextHelp "In prompted running mode, used to indicate that the script should take data." 
APSDisableButton .userFrame.continue.button
 
APSButton .stop -parent .userFrame -text Stop -command \
  { \
      set abortRun 1
      set continueRun 1
      APSDisableButton .userFrame.stop.button
      APSEnableButton .userFrame.run.button 
      APSEnableButton .userFrame.runPrompt.button } \
  -contextHelp "Aborts scan."
APSDisableButton .userFrame.stop.button

APSButton .proc -parent .userFrame -text Process -command \
  { \
      APSDisableButton .userFrame.run.button 
      APSDisableButton .userFrame.runPrompt.button 
      APSEnableButton .userFrame.stop.button
      catch {ProcessData -outputDir $outputDir \
               -root $root -index $index } status
      update idletasks
      APSDisableButton .userFrame.stop.button 
      APSEnableButton .userFrame.run.button 
      APSEnableButton .userFrame.runPrompt.button }

set continueRun 0
set continueButton .userFrame.continue.button

dp_atexit append StopProcesses


