
proc LEUTL_SetupForUndulatorHallStudiesInfo {} {
    return "This procedure does the following:\n\
1. Checks that the linac-to-LEUTL double stop is open.\n\
2. Checks that the booster-to-LEUTL radiation stop is open.\n\
3. Turns off LTP and PTB dipoles.\n\
4. Turns on the booster bypass dipoles.\n\
5. Degauss and standardize all LTP, PTB, bypass, and undulator\
line magnets to their values from a selected save set.\n\
This procedure is independent of the gun selected."
}

proc LEUTL_SetupForUndulatorHallStudiesDialog {frame} {
    set frame $frame.f1
    pack [frame $frame]
    APSCheckButtonFrame .cb1 -parent $frame -label "" \
      -buttonList {"Turn Off LTP and PTB Dipoles"} \
      -variableList {LEUTL_SetupForUndulatorHallStudies(turnOffLTPAndPTB)} \
      -orientation vertical -allNone 0

    APSCheckButtonFrame .cb2 -parent $frame -label "Turn On" \
	-buttonList {LTP:Q LTP:V LTP:H PB:Q PB:V PB:H PTB:Q PTB:V PTB:H BB:Q BB:V BB:H BB:BM BB:BD:Q1 LA:Q LS:Q LS:V LS:H LS:BM LU:Q LU:V LU:H} \
	-variableList {LEUTL_SetupForUndulatorHallStudies(LTP:Q) LEUTL_SetupForUndulatorHallStudies(LTP:V) LEUTL_SetupForUndulatorHallStudies(LTP:H) LEUTL_SetupForUndulatorHallStudies(PB:Q) LEUTL_SetupForUndulatorHallStudies(PB:V) LEUTL_SetupForUndulatorHallStudies(PB:H) LEUTL_SetupForUndulatorHallStudies(PTB:Q) LEUTL_SetupForUndulatorHallStudies(PTB:V) LEUTL_SetupForUndulatorHallStudies(PTB:H) LEUTL_SetupForUndulatorHallStudies(BB:Q) LEUTL_SetupForUndulatorHallStudies(BB:V) LEUTL_SetupForUndulatorHallStudies(BB:H) LEUTL_SetupForUndulatorHallStudies(BB:BM) LEUTL_SetupForUndulatorHallStudies(BB:BD:Q1) LEUTL_SetupForUndulatorHallStudies(LA:Q) LEUTL_SetupForUndulatorHallStudies(LS:Q) LEUTL_SetupForUndulatorHallStudies(LS:V) LEUTL_SetupForUndulatorHallStudies(LS:H) LEUTL_SetupForUndulatorHallStudies(LS:BM) LEUTL_SetupForUndulatorHallStudies(LU:Q) LEUTL_SetupForUndulatorHallStudies(LU:V) LEUTL_SetupForUndulatorHallStudies(LU:H)} \
	-orientation horizontal -allNone 1 -limitPerRow 11

    APSCheckButtonFrame .cb3 -parent $frame -label "Condition" \
	-buttonList {LTP:Q LTP:V LTP:H PB:Q PB:V PB:H PTB:Q PTB:V PTB:H BB:Q BB:V BB:H BB:BM BB:BD:Q1 LA:Q LS:Q LS:V LS:H LS:BM LU:Q LU:V LU:H} \
	-variableList {LEUTL_SetupForUndulatorHallStudies(ConditionLTP:Q) LEUTL_SetupForUndulatorHallStudies(ConditionLTP:V) LEUTL_SetupForUndulatorHallStudies(ConditionLTP:H) LEUTL_SetupForUndulatorHallStudies(ConditionPB:Q) LEUTL_SetupForUndulatorHallStudies(ConditionPB:V) LEUTL_SetupForUndulatorHallStudies(ConditionPB:H) LEUTL_SetupForUndulatorHallStudies(ConditionPTB:Q) LEUTL_SetupForUndulatorHallStudies(ConditionPTB:V) LEUTL_SetupForUndulatorHallStudies(ConditionPTB:H) LEUTL_SetupForUndulatorHallStudies(ConditionBB:Q) LEUTL_SetupForUndulatorHallStudies(ConditionBB:V) LEUTL_SetupForUndulatorHallStudies(ConditionBB:H) LEUTL_SetupForUndulatorHallStudies(ConditionBB:BM) LEUTL_SetupForUndulatorHallStudies(ConditionBB:BD:Q1) LEUTL_SetupForUndulatorHallStudies(ConditionLA:Q) LEUTL_SetupForUndulatorHallStudies(ConditionLS:Q) LEUTL_SetupForUndulatorHallStudies(ConditionLS:V) LEUTL_SetupForUndulatorHallStudies(ConditionLS:H) LEUTL_SetupForUndulatorHallStudies(ConditionLS:BM) LEUTL_SetupForUndulatorHallStudies(ConditionLU:Q)  LEUTL_SetupForUndulatorHallStudies(ConditionLU:V)  LEUTL_SetupForUndulatorHallStudies(ConditionLU:H)} \
	-orientation horizontal -allNone 1 -limitPerRow 11
}

proc LEUTL_SetupForUndulatorHallStudies {args} {
    set SCRFile ""
    set turnOffLTPAndPTB 1
    set cycles 4
    set supplyList "LTP:Q LTP:V LTP:H PB:Q PB:V PB:H PTB:Q PTB:V PTB:H BB:Q BB:V BB:H BB:BM BB:BD:Q1 LA:Q LS:Q LS:V LS:H LS:BM LU:Q LU:V LU:H"
    foreach supply $supplyList {
	set $supply 1
	set Condition$supply 1
    }
    foreach supply "LS:BM" {
	set $supply 0
	set Condition$supply 0
    }
    APSStrictParseArguments {SCRFile cycles turnOffLTPAndPTB LTP:Q LTP:V LTP:H PB:Q PB:V PB:H PTB:Q PTB:V PTB:H BB:Q BB:V BB:H BB:BM BB:BD:Q1 LA:Q LS:Q LS:V LS:H LS:BM LU:Q LU:V LU:H ConditionLTP:Q ConditionLTP:V ConditionLTP:H ConditionPB:Q ConditionPB:V ConditionPB:H ConditionPTB:Q ConditionPTB:V ConditionPTB:H ConditionBB:Q ConditionBB:V ConditionBB:H ConditionBB:BM ConditionBB:BD:Q1 ConditionLA:Q ConditionLS:Q ConditionLS:V ConditionLS:H ConditionLS:BM ConditionLU:Q ConditionLU:V ConditionLU:H}

    global APSMpLControlPS execMode

    if {$execMode == "Manual"} {
	set prefix "Press Continue to "
    } else {
	set prefix ""
    }
    
    set arrayName APSMpLControlPS
    APSLGenericPSArraySetup -arrayName $arrayName \
	-SCRFile $SCRFile

    set mode $execMode
    APSMpStep init -promptDialog \
	"APSLGenericPSDialog -packProc LEUTL_SetupForUndulatorHallStudiesDialog -chooseSCR 1 -arrayName $arrayName -frame " -vars "turnOffLTPAndPTB LTP:Q LTP:V LTP:H PB:Q PB:V PB:H PTB:Q PTB:V PTB:H BB:Q BB:V BB:H BB:BM BB:BD:Q1 LA:Q LS:Q LS:V LS:H LS:BM LU:Q LU:V LU:H ConditionLTP:Q ConditionLTP:V ConditionLTP:H ConditionPB:Q ConditionPB:V ConditionPB:H ConditionPTB:Q ConditionPTB:V ConditionPTB:H ConditionBB:Q ConditionBB:V ConditionBB:H ConditionBB:BM ConditionBB:BD:Q1 ConditionLA:Q ConditionLS:Q ConditionLS:V ConditionLS:H ConditionLS:BM ConditionLU:Q ConditionLU:V ConditionLU:H"

    set SCRFile $APSMpLControlPS(Filename)

    set paramString ""
    foreach param {SCRFile cycles turnOffLTPAndPTB LTP:Q LTP:V LTP:H PB:Q PB:V PB:H PTB:Q PTB:V PTB:H BB:Q BB:V BB:H BB:BM BB:BD:Q1 LA:Q LS:Q LS:V LS:H LS:BM LU:Q LU:V LU:H ConditionLTP:Q ConditionLTP:V ConditionLTP:H ConditionPB:Q ConditionPB:V ConditionPB:H ConditionPTB:Q ConditionPTB:V ConditionPTB:H ConditionBB:Q ConditionBB:V ConditionBB:H ConditionBB:BM ConditionBB:BD:Q1 ConditionLA:Q ConditionLS:Q ConditionLS:V ConditionLS:H ConditionLS:BM ConditionLU:Q ConditionLU:V ConditionLU:H} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure LEUTL_SetupForUndulatorHallStudies -action initialize -state ok -parameters $paramString}

    if {(![file exists $SCRFile])} {
	APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: No SCR file has been choosen"
    }

    if [catch {APSLinkToLINACPVs} result] {
	APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $result"
    }

    APSMpStep "Check that the linac-to-LEUTL (double stop) is open"
    if [catch {exec cavget -list=ACIS:LAO_LTB_2S_CLSD -num} result] {
	APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $result"
    }
    if {$result != 0} {
        if {[APSPEMTKDialog .warningDialog -text "The Linac to LEUTL double stop is not open."] == 1} {
	    APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: the Linac to LEUTL double stop is not open"
	}
    }
    
    APSMpStep "Check that the booster-to-LEUTL (radiation stop) is open"
    if [catch {exec cavget -list=ACIS:UAOI_BS6_CLOSED -num} result] {
	APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $result"
    }
    if {$result != 0} {
        if {[APSPEMTKDialog .warningDialog -text "The Booster to LEUTL radiation stop is not open."] == 1} {
	    APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: the Booster to LEUTL radiation stop is not open"
	}
    }

    if {$turnOffLTPAndPTB} {
	set failed 1
	set step 0
	while {$failed} {
	    APSMpStep "Turn off LTP and PTB dipoles"
	    incr step
	    if {$step > 4} {
                if {[APSPEMTKDialog .warningDialog -text "Unable to turn off LTP and PTB dipoles."] == 1} {
		    APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: Unable to turn off LTP and PTB dipoles"
		}
		break
	    }
	    if [catch {APSDevSend \
			   -releaseLinks 1 \
			   -group LTPToEndPSOps \
			   -operation SetCurrent \
			   -deviceList {"LTP:B1" "PTB:B1" "PTB:B2"} \
			   -valueList {0 0 0} \
			   -timeout 0} result] {
		APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $result"
	    }
	    if [catch {APSDevSend \
			   -releaseLinks 1 \
			   -group LTPToEndPSOps \
			   -operation TurnOff \
			   -deviceList {"LTP:B1" "PTB:B1" "PTB:B2"} \
			   -timeout 0} result] {
		APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $result"
	    }
	    APSWaitWithUpdate -waitSeconds 5
	    if [catch {APSDevSend \
			   -releaseLinks 1 \
			   -group LTPToEndPSOps \
			   -operation QueryOn \
			   -deviceList {"LTP:B1" "PTB:B1" "PTB:B2"}} results] {
		APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $results"
	    }
	    set failed 0
	    foreach result $results {
		if {$result} {
		    set failed 1
		    break
		}
	    }
	}
    }
    
    if {${BB:BM}} {
	set failed 1
	set step 0
	while {$failed} {
	    APSMpStep "Turn on the booster bypass dipoles"
	    incr step
	    if {$step > 4} {
		if {[APSPEMTKDialog .warningDialog -text "Unable to turn on booster bypass dipoles."] == 1} {
		    APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: Unable to turn on booster bypass dipoles"
		}
		break
	    }
	    if [catch {APSDevSend \
			 -releaseLinks 1 \
			 -group LTPToEndPSOps \
			 -operation TurnOn \
			 -deviceList {"BB:BM1" "BB:BM2"} \
			 -timeout 0} result] {
		APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $result"
	    }
	    APSWaitWithUpdate -waitSeconds 5
	    if [catch {APSDevSend \
			 -releaseLinks 1 \
			 -group LTPToEndPSOps \
			 -operation QueryOn \
			 -deviceList {"BB:BM1" "BB:BM2"}} results] {
		APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $results"
	    }
	    set failed 0
	    foreach result $results {
		if {!$result} {
		    set failed 1
		    break
		}
	    }
	}    
    }	

#    set powerSupplies "LTP:Q6 LTP:Q7 LTP:Q8 LTP:Q9 LTP:Q10 LTP:V3 LTP:V4 LTP:H3 LTP:H4 PB:Q1 PB:Q2 PB:Q3 PB:Q4 PB:V1 PB:V2 PB:H1 PB:H2 PTB:Q6 PTB:Q7 PTB:Q8 PTB:Q9 PTB:V3 PTB:V4 PTB:H3 PTB:H4 BB:QE1 BB:QE2 BB:Q1 BB:Q2 BB:Q3 BB:Q4 BB:Q5 BB:Q6 BB:V1 BB:V2 BB:H2 BB:H3 BB:BM1 BB:BM2 BB:BD:Q1 LA:Q1 LA:Q2 LS:Q1 LS:Q2 LS:Q3 LS:Q4 LS:V1 LS:H1 LS:H2 LS:BM LU:Q0 LU:Q1 LU:Q2 LU:Q3 LU:Q4 LU:Q5 LU:Q6 LU:Q7 LU:Q8 LU:V0 LU:V1 LU:V2 LU:V3 LU:V4 LU:V5 LU:V6 LU:V7 LU:V8 LU:H0 LU:H1 LU:H2 LU:H3 LU:H4 LU:H5 LU:H6 LU:H7 LU:H8"
    set powerSupplies "LTP:Q6 LTP:Q7 LTP:Q8 LTP:Q9 LTP:Q10 LTP:V3 LTP:V4 LTP:H3 LTP:H4 PB:Q1 PB:Q2 PB:Q3 PB:Q4 PB:V1 PB:V2 PB:H1 PB:H2 PTB:Q6 PTB:Q7 PTB:Q8 PTB:Q9 PTB:V3 PTB:V4 PTB:H3 PTB:H4 BB:QE1 BB:QE2 BB:Q1 BB:Q2 BB:Q3 BB:Q4 BB:Q5 BB:Q6 BB:V1 BB:V2 BB:H2 BB:H3 BB:BM1 BB:BM2 BB:BD:Q1 LA:Q1 LA:Q2 LS:Q1 LS:Q2 LS:V1 LS:H1 LU:Q0 LU:Q1 LU:V0 LU:V1 LU:H0 LU:H1 "
    set powerSuppliesTurnOn ""
    set powerSuppliesCondition ""
    foreach supply $powerSupplies {
	foreach group $supplyList {
	    if {[set $group]} {
		if {[string match ${group}* $supply]} {
		    lappend powerSuppliesTurnOn $supply
		}
	    }
	    if {[set Condition${group}]} {
		if {[string match ${group}* $supply]} {
		    lappend powerSuppliesCondition $supply
		    break
		}
	    }
	}
    }

    if {[llength $powerSuppliesTurnOn]} {
	set step 0
	while {1} {
	    APSMpStep "Turn on all needed power supplies"
	    incr step
	    if [catch {APSDevSend \
			   -releaseLinks 1 \
			   -group LTPToEndPSOps \
			   -operation QueryOn \
			   -deviceList $powerSuppliesTurnOn} results] {
		APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $results"
	    }
	    set disabledPowerSupplies ""
	    foreach result $results powerSupply $powerSuppliesTurnOn {
		if {$result != 1} {
		    lappend disabledPowerSupplies $powerSupply
		}
	    }
	    if {$step > 4} {
                if {[APSPEMTKDialog .warningDialog -text "Unable to turn on $disabledPowerSupplies power supplies."] == 1} {
		    APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: Unable to turn on $disabledPowerSupplies power supplies"
		}
		break
	    }
	    
	    if {[llength $disabledPowerSupplies]} {
		if [catch {APSDevSend \
			       -releaseLinks 1 \
			       -group LTPToEndPSOps \
			       -operation TurnOn \
			       -deviceList $disabledPowerSupplies \
			       -timeout 0} result] {
		    APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $result"
		}
		APSWaitWithUpdate -waitSeconds 10
	    } else {
		break
	    }
	}
    }

    if {![llength $powerSuppliesCondition]} {
	APSMpReturn ok
    }
    set option ""
    set i 0
    foreach supply $powerSuppliesCondition {
	if {$i == 0} {
	    append option "-match=column,CurrentControlName=${supply}*"
	    incr i
	} else {
	    append option ",CurrentControlName=${supply}*,|"
	}
    }
    APSMpStep "Starting conditioning" -desc "Starting conditioning"
    set tmpFile /tmp/[APSTmpString]
    set tmpFile2 /tmp/[APSTmpString]
    set Standardize 1
    set Degauss 1
    if [catch {eval exec sddsprocess /home/helios/oagData/controlFiles/LEUTL/LEUTL.std \
		   -pipe=out $option -redefine=col,NumCycles,$cycles,type=long \
		   | sddsxref -pipe $SCRFile \
		   -match=CurrentControlName=ControlName -take=ValueString \
		   | sddsprocess -pipe -delete=column,Value \
		   -scan=column,Value,ValueString,%le \
		   | sddsconvert -pipe=in $tmpFile -delete=column,Finish \
		   -rename=column,Value=Finish} result] {
	APSSetVarAndUpdate status "No magnets to standardize"
	set Standardize 0
#	APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $result"
    }
    set conditioningTime [expr $cycles * 2.5]

    if [catch {exec sddsconvert /home/helios/oagData/controlFiles/LEUTL/LEUTL_degauss.sdds \
                 -pipe=out -delete=col,DecayMinutes,DecaySeconds | \
                 sddsprocess -pipe \
                 "-define=col,DecayTime,$conditioningTime NumDecay /" \
                 "-define=col,DecayMinutes,DecayTime int,type=long" \
                 "-define=col,DecaySeconds,DecayTime DecayMinutes - 60 * int,type=long" | \
                 sddsprocess -pipe $option \
                 | sddsxref -pipe $SCRFile \
                 -match=CurrentControlName=ControlName -take=ValueString \
                 | sddsprocess -pipe -delete=column,Value \
                 -scan=column,Value,ValueString,%le \
                 | sddsconvert -pipe=in $tmpFile2 -delete=column,Finish \
                 -rename=column,Value=Finish} result] {
	APSSetVarAndUpdate status "No magnets to degauss"
	set Degauss 0
#	APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $result"
    }
    global execMode

    if {$Standardize} {
	set standardizeID [APSMpParallel \
			       -procedure "APSPEMExec -command \"standardize $tmpFile\"" \
			       -mode Automatic]
    }
    if {$Degauss} {
	set degaussID [APSMpParallel \
			   -procedure "APSPEMExec -command \"degauss $tmpFile2\"" \
			   -mode Automatic]
    }
    if {$Standardize} {
	if [catch {APSMpJoin $standardizeID} result] {
            if {[APSPEMTKDialog .warningDialog -text "Error in standardizing\n$result."] == 1} {
                file delete -force $tmpFile
                file delete -force $tmpFile2
                APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: Error in standardizing: $result"
            }
	}
    }
    if {$Degauss} {
	if [catch {APSMpJoin $degaussID} result] {
            if {[APSPEMTKDialog .warningDialog -text "Error in degaussing\n$result."] == 1} {
                file delete -force $tmpFile
                file delete -force $tmpFile2
                APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: Error in degaussing: $result"
            }
	}
    }

    APSMpStep "Waiting for conditioning to finish" -desc "Waiting for conditioning to finish"
    set data ""
    set data2 ""
    if {$Standardize} {
	if [catch {exec sdds2stream $tmpFile -col=ControlName,Finish} data] {
	    APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $data"
	}
    }
    if {$Degauss} {
	if [catch {exec sdds2stream $tmpFile2 -col=ControlName,Finish} data2] {
	    APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $data2"
	}
    }
    set names ""
    set values ""
    foreach "name value" $data {
	lappend names $name
	lappend values $value
    }
    set names2 ""
    set values2 ""
    foreach "name value" $data2 {
	lappend names2 $name
	lappend values2 $value
    }
    set names3 "$names $names2"
    if {[llength $names3]} {
	set wait 1
	while {$wait} {
	    set wait 0
	    APSWaitWithUpdate -waitSeconds 5
	    if [catch {APSDevSend \
			   -releaseLinks 1 \
			   -group LTPToEndPSOps \
			   -operation QueryConditioning \
			   -deviceList $names3} results] {
		APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $results"
	    }
	    foreach result $results {
		if {$result} {
		    set wait 1
		    break
		}
	    }
	}
    }

    APSMpStep "Setting final current" -desc "Setting final current"
    if {$Standardize} {
	if [catch {APSDevSend \
		       -releaseLinks 1 \
		       -group LTPToEndPSOps \
		       -operation SetCurrent \
		       -deviceList $names \
		       -valueList $values \
		       -timeout 0} result] {
	    APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $result"
	}
    }
    if {$Degauss} {
	if [catch {APSDevSend \
		       -releaseLinks 1 \
		       -group LTPToEndPSOps \
		       -operation SetCurrent \
		       -deviceList $names2 \
		       -valueList $values2 \
		       -timeout 0} result] {
	    APSMpReturn error "LEUTL_SetupForUndulatorHallStudies: $result"
	}
    }
    file delete -force $tmpFile
    file delete -force $tmpFile2

    APSMpReturn ok
}

#proc LEUTL_ConditionUndulatorPS {args} {
#    set stddir /home/helios/OAG/oagData/controlFiles/LEUTL 
#    set cycles 6

#    for {set i 1} {$i<=${cycles}} {incr i} {
#	exec sddscaramp -rampTo=$stddir/UndulatorPS_to.sdds,steps=15,pause=3
#	exec sddscaramp -rampTo=$stddir/UndulatorPS_from.sdds,steps=15,pause=3
#    }
#    exec sddscaramp -rampTo=$stddir/UndulatorPS.fin,steps=15,pause=3
#    APSMpReturn ok 
#}

proc APSPEMExec {args} {
    set command ""
    APSStrictParseArguments {command}
    if [catch {eval exec $command} results] {
        if {[APSPEMTKDialog .warningDialog -text "APSPEMExec: $results"] == 1} {
            APSMpReturn error "APSPEMExec: $results"
        }
    }
    APSMpReturn ok "$results"
}

proc LEUTL_SetupForOperationsInfo {} {
    return "This procedure does the following:\n\
1. Turns on LTP and PTB dipoles.\n\
2. Turns off the booster bypass dipoles.\n\
3. Runs APSMpPARLETStartUp pem procedure.\n\
4. Checks that the linac-to-LEUTL double stop is closed."
}

proc LEUTL_SetupForOperationsDialog {frame} {
    global APSMpPARLETStartUp

    set frame $frame.f1
    pack [frame $frame]
    APSLabeledEntry .le1 -parent $frame -label "Energy (MeV): " \
      -textVariable LEUTL_SetupForOperations(energy) \
      -contextHelp "Enter the energy of the beam you will be using in MeV."
    APSRadioButtonFrame .rb1 -parent $frame -label "Particle: " \
      -variable LEUTL_SetupForOperations(particle) -buttonList "Positron Electron" \
      -valueList "positron electron" -orientation horizontal \
      -contextHelp "Select the type of particle you are running from the LINAC."

    APSLabeledEntry .le2 -parent $frame -label "Minutes for conditioning: " \
      -textVariable LEUTL_SetupForOperations(conditioningTime) \
      -contextHelp "Enter the number of minutes you want to allow for conditioning.  The actual conditioning time may be longer, since each magnet must be put through at least one ramp cycle."

    if 0 {
    APSCheckButtonFrame .cb1 -parent $frame -label "Systems: " \
      -buttonList {rf DCPS "Pulsed PS"} \
      -variableList {LEUTL_SetupForOperations(rfSystems) LEUTL_SetupForOperations(DCPS) LEUTL_SetupForOperations(PulsedPS)} \
      -orientation vertical -allNone 1 -contextHelp \
      "Use to select or deselect systems to be included in startup."
    }
    APSCheckButtonFrame .cb1 -parent $frame -label "Systems: " \
      -buttonList {DCPS "Pulsed PS"} \
      -variableList {LEUTL_SetupForOperations(DCPS) LEUTL_SetupForOperations(PulsedPS)} \
      -orientation vertical -allNone 1 -contextHelp \
      "Use to select or deselect systems to be included in startup."

    APSRadioButtonFrame .rb2 -parent $frame -label "Standardize LTP:B1: " \
      -variable LEUTL_SetupForOperations(standardizeLTPB1) -buttonList {Yes No} -valueList {1 0} \
      -orientation horizontal -contextHelp \
      "Select whether to include LTP:B1 in the standardiation or not."
}

proc LEUTL_SetupForOperations {args} {
    set energy [APSPARLETDefaultEnergy]
#    set restoreFile PLET-325MeVPreferredRFGun.gz
    set SCRFile ""
    set conditioningTime 5
    set DCPS 1
    set PulsedPS 1
    set rfSystems 0
    set particle electron
    set standardizeLTPB1 1
    set conditionLTP 1
    set conditionPAR 0
    set conditionPTB 1

    APSStrictParseArguments {energy particle SCRFile conditioningTime DCPS PulsedPS rfSystems standardizeLTPB1 conditionLTP conditionPAR conditionPTB}

    global APSMpLControlPS execMode

    if {$execMode == "Manual"} {
	set prefix "Press Continue to "
    } else {
	set prefix ""
    }
    
    set arrayName APSMpLControlPS
    APSLGenericPSArraySetup -arrayName $arrayName -SCRFile $SCRFile

    set mode $execMode
    APSMpStep init -promptDialog \
	"APSLGenericPSDialog -packProc LEUTL_SetupForOperationsDialog -chooseSCR 1 -arrayName $arrayName -system LPL -frame " -vars {energy particle conditioningTime DCPS PulsedPS rfSystems standardizeLTPB1}

    set SCRFile $APSMpLControlPS(Filename)

    set paramString ""
    foreach param {energy SCRFile conditioningTime DCPS PulsedPS rfSystems particle standardizeLTPB1 conditionLTP conditionPAR conditionPTB} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure LEUTL_SetupForOperations -action initialize -state ok -parameters $paramString}

    if {(![file exists $SCRFile])} {
	APSMpReturn error "LEUTL_SetupForOperations: No SCR file has been choosen"
    }

    if [catch {APSLinkToLINACPVs} result] {
	APSMpReturn error "LEUTL_SetupForOperations: $result"
    }
    
    set failed 1
    set step 0
    while {$failed} {
	APSMpStep "Turn on LTP and PTB dipoles"
	incr step
	if {$step > 4} {
            if {[APSPEMTKDialog .warningDialog -text "Unable to turn on LTP and PTB dipoles."] == 1} {
		APSMpReturn error "LEUTL_SetupForOperations: Unable to turn on LTP and PTB dipoles"
	    }
	    break
	}
	if {$standardizeLTPB1} {
	    if [catch {APSDevSend \
			   -releaseLinks 1 \
			   -group LTPToEndPSOps \
			   -operation TurnOn \
			   -deviceList {"LTP:B1" "PTB:B1" "PTB:B2"} \
			   -timeout 0} result] {
		APSMpReturn error "LEUTL_SetupForOperations: $result"
	    }
	    APSWaitWithUpdate -waitSeconds 5
	    if [catch {APSDevSend \
			   -releaseLinks 1 \
			   -group LTPToEndPSOps \
			   -operation QueryOn \
			   -deviceList {"LTP:B1" "PTB:B1" "PTB:B2"}} results] {
		APSMpReturn error "LEUTL_SetupForOperations: $results"
	    }
	} else {
	    if [catch {APSDevSend \
			   -releaseLinks 1 \
			   -group LTPToEndPSOps \
			   -operation TurnOn \
			   -deviceList {"PTB:B1" "PTB:B2"} \
			   -timeout 0} result] {
		APSMpReturn error "LEUTL_SetupForOperations: $result"
	    }
	    APSWaitWithUpdate -waitSeconds 5
	    if [catch {APSDevSend \
			   -releaseLinks 1 \
			   -group LTPToEndPSOps \
			   -operation QueryOn \
			   -deviceList {"PTB:B1" "PTB:B2"}} results] {
		APSMpReturn error "LEUTL_SetupForOperations: $results"
	    }
	}
	set failed 0
	foreach result $results {
	    if {!$result} {
		set failed 1
		break
	    }
	}
    }
    
    set failed 1
    set step 0
    while {$failed} {
	APSMpStep "Turn off the booster bypass dipoles"
	incr step
	if {$step > 4} {
            if {[APSPEMTKDialog .warningDialog -text "Unable to turn off booster bypass dipoles."] == 1} {
		APSMpReturn error "LEUTL_SetupForOperations: Unable to turn off booster bypass dipoles"
	    }
	    break
	}
	if [catch {APSDevSend \
		       -releaseLinks 1 \
		       -group LTPToEndPSOps \
		       -operation SetCurrent \
		       -deviceList {"BB:BM1" "BB:BM2"} \
		       -valueList {0 0} \
		       -timeout 0} result] {
	    APSMpReturn error "LEUTL_SetupForOperations: $result"
	}
	if [catch {APSDevSend \
		       -releaseLinks 1 \
		       -group LTPToEndPSOps \
		       -operation TurnOff \
		       -deviceList {"BB:BM1" "BB:BM2"} \
		       -timeout 0} result] {
	    APSMpReturn error "LEUTL_SetupForOperations: $result"
	}
	APSWaitWithUpdate -waitSeconds 5
	if [catch {APSDevSend \
		       -releaseLinks 1 \
		       -group LTPToEndPSOps \
		       -operation QueryOn \
		       -deviceList {"BB:BM1" "BB:BM2"}} results] {
	    APSMpReturn error "LEUTL_SetupForOperations: $results"
	}
	set failed 0
	foreach result $results {
	    if {$result} {
		set failed 1
		break
	    }
	}
    }
    
    APSMpStep "Starting conditioning" -desc "Start APSMpPARLETStartUp" -proc "APSMpPARLETStartUp"
    if [catch {APSMpPARLETStartUp -energy $energy -particle $particle -restoreFile [file tail $SCRFile] -conditioningTime $conditioningTime -DCPS $DCPS -PulsedPS $PulsedPS -rfSystems $rfSystems -standardizeLTPB1 $standardizeLTPB1 -conditionLTP $conditionLTP -conditionPAR $conditionPAR -conditionPTB $conditionPTB} results] {
        if {[APSPEMTKDialog .warningDialog -text "Error encountered while running APSMpPARLETStartUp\n$results"] == 1} {
            APSMpReturn error "LEUTL_SetupForOperations: $results"
        }
    }

    APSMpStep "Check that the linac-to-LEUTL (double stop) is closed"
    if [catch {exec cavget -list=ACIS:LAO_LTB_2S_CLSD -num} result] {
	APSMpReturn error "LEUTL_SetupForOperations: $result"
    }
    if {$result != 1} {
        if {[APSPEMTKDialog .warningDialog -text "The Linac to LEUTL double stop is not closed"] == 1} {
	    APSMpReturn error "LEUTL_SetupForOperations: the Linac to LEUTL double stop is not closed"
	}
    }

    APSMpReturn ok

}

proc LEUTL_SetupForPARBypassToBoosterInfo {} {
    return "This procedure does the following:\n\
1. Checks that the linac-to-LEUTL double stop is open.\n\
2. Checks that the booster-to-LEUTL radiation stop is closed.\n\
3. Turns on LTP and PTB dipoles.\n\
4. Degauss and standardize all LTP, PTB, and ByPass\n\
magnets to their values from a selected save set."
}

proc LEUTL_SetupForPARBypassToBoosterDialog {frame} {
    set frame $frame.f1
    pack [frame $frame]

    APSCheckButtonFrame .cb1 -parent $frame -label "Turn On" \
	-buttonList {LTP:Q LTP:V LTP:H LTP:B PB:Q PB:V PB:H PTB:Q PTB:V PTB:H PTB:B} \
	-variableList {LEUTL_SetupForPARBypassToBooster(LTP:Q) LEUTL_SetupForPARBypassToBooster(LTP:V) LEUTL_SetupForPARBypassToBooster(LTP:H) LEUTL_SetupForPARBypassToBooster(LTP:B) LEUTL_SetupForPARBypassToBooster(PB:Q) LEUTL_SetupForPARBypassToBooster(PB:V) LEUTL_SetupForPARBypassToBooster(PB:H) LEUTL_SetupForPARBypassToBooster(PTB:Q) LEUTL_SetupForPARBypassToBooster(PTB:V) LEUTL_SetupForPARBypassToBooster(PTB:H) LEUTL_SetupForPARBypassToBooster(PTB:B)} \
	-orientation horizontal -allNone 1 -limitPerRow 6

    APSCheckButtonFrame .cb2 -parent $frame -label "Condition" \
	-buttonList {LTP:Q LTP:V LTP:H LTP:B PB:Q PB:V PB:H PTB:Q PTB:V PTB:H PTB:B} \
	-variableList {LEUTL_SetupForPARBypassToBooster(ConditionLTP:Q) LEUTL_SetupForPARBypassToBooster(ConditionLTP:V) LEUTL_SetupForPARBypassToBooster(ConditionLTP:H) LEUTL_SetupForPARBypassToBooster(ConditionLTP:B) LEUTL_SetupForPARBypassToBooster(ConditionPB:Q) LEUTL_SetupForPARBypassToBooster(ConditionPB:V) LEUTL_SetupForPARBypassToBooster(ConditionPB:H) LEUTL_SetupForPARBypassToBooster(ConditionPTB:Q) LEUTL_SetupForPARBypassToBooster(ConditionPTB:V) LEUTL_SetupForPARBypassToBooster(ConditionPTB:H) LEUTL_SetupForPARBypassToBooster(ConditionPTB:B)} \
	-orientation horizontal -allNone 1 -limitPerRow 6
}

proc LEUTL_SetupForPARBypassToBooster {args} {
    set SCRFile ""
    set supplyList "LTP:Q LTP:V LTP:H LTP:B PB:Q PB:V PB:H PTB:Q PTB:V PTB:H PTB:B"
    foreach supply $supplyList {
	set $supply 1
	set Condition$supply 1
    }

    APSStrictParseArguments {SCRFile}

    global APSMpLControlPS execMode

    if {$execMode == "Manual"} {
	set prefix "Press Continue to "
    } else {
	set prefix ""
    }
    
    set arrayName APSMpLControlPS
    APSLGenericPSArraySetup -arrayName $arrayName \
	-SCRFile $SCRFile

    set mode $execMode
    APSMpStep init -promptDialog \
	"APSLGenericPSDialog -packProc LEUTL_SetupForPARBypassToBoosterDialog -chooseSCR 1 -arrayName $arrayName -frame " -vars "LTP:Q LTP:V LTP:H LTP:B PB:Q PB:V PB:H PTB:Q PTB:V PTB:H PTB:B ConditionLTP:Q ConditionLTP:V ConditionLTP:H ConditionLTP:B ConditionPB:Q ConditionPB:V ConditionPB:H ConditionPTB:Q ConditionPTB:V ConditionPTB:H ConditionPTB:B"

    set SCRFile $APSMpLControlPS(Filename)

    set paramString ""
    foreach param {SCRFile LTP:Q LTP:V LTP:H LTP:B PB:Q PB:V PB:H PTB:Q PTB:V PTB:H PTB:B ConditionLTP:Q ConditionLTP:V ConditionLTP:H ConditionLTP:B ConditionPB:Q ConditionPB:V ConditionPB:H ConditionPTB:Q ConditionPTB:V ConditionPTB:H ConditionPTB:B} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure LEUTL_SetupForPARBypassToBooster -action initialize -state ok -parameters $paramString}

    if {(![file exists $SCRFile])} {
	APSMpReturn error "LEUTL_SetupForPARBypassToBooster: No SCR file has been choosen"
    }

    if {[catch {APSLinkToLINACPVs} result]} {
	APSMpReturn error "LEUTL_SetupForPARBypassToBooster: $result"
    }

    APSMpStep "Check that the linac-to-LEUTL (double stop) is open"
    if {[catch {exec cavget -list=ACIS:LAO_LTB_2S_CLSD -num} result]} {
	APSMpReturn error "LEUTL_SetupForPARBypassToBooster: $result"
    }
    if {$result != 0} {
        if {[APSPEMTKDialog .warningDialog -text "The Linac to LEUTL double stop is not open."] == 1} {
	    APSMpReturn error "LEUTL_SetupForPARBypassToBooster: the Linac to LEUTL double stop is not open"
	}
    }
    
    APSMpStep "Check that the booster-to-LEUTL (radiation stop) is closed"
    if {[catch {exec cavget -list=ACIS:UAOI_BS6_CLOSED -num} result]} {
	APSMpReturn error "LEUTL_SetupForPARBypassToBooster: $result"
    }
    if {$result != 1} {
        if {[APSPEMTKDialog .warningDialog -text "The Booster to LEUTL radiation stop is not closed."] == 1} {
	    APSMpReturn error "LEUTL_SetupForPARBypassToBooster: the Booster to LEUTL radiation stop is not closed"
	}
    }

    set powerSupplies "LTP:Q6 LTP:Q7 LTP:Q8 LTP:Q9 LTP:Q10 LTP:V3 LTP:V4 LTP:H3 LTP:H4 LTP:B1 PB:Q1 PB:Q2 PB:Q3 PB:Q4 PB:V1 PB:V2 PB:H1 PB:H2 PTB:Q6 PTB:Q7 PTB:Q8 PTB:Q9 PTB:Q10 PTB:Q11 PTB:V3 PTB:V4 PTB:H3 PTB:H4 PTB:B1 PTB:B2"
    set powerSuppliesTurnOn ""
    set powerSuppliesCondition ""
    foreach supply $powerSupplies {
	foreach group $supplyList {
	    if {[set $group]} {
		if {[string match ${group}* $supply]} {
		    lappend powerSuppliesTurnOn $supply
		}
	    }
	    if {[set Condition${group}]} {
		if {[string match ${group}* $supply]} {
		    lappend powerSuppliesCondition $supply
		    break
		}
	    }
	}
    }

    if {[llength $powerSuppliesTurnOn]} {
	set step 0
	while {1} {
	    APSMpStep "Turn on all needed power supplies"
	    incr step
	    if {[catch {APSDevSend \
			    -releaseLinks 1 \
			    -group LTPToEndPSOps \
			    -operation QueryOn \
			    -deviceList $powerSuppliesTurnOn} results]} {
		APSMpReturn error "LEUTL_SetupForPARBypassToBooster: $results"
	    }
	    set disabledPowerSupplies ""
	    foreach result $results powerSupply $powerSuppliesTurnOn {
		if {$result != 1} {
		    lappend disabledPowerSupplies $powerSupply
		}
	    }
	    if {$step > 4} {
                if {[APSPEMTKDialog .warningDialog -text "Unable to turn on $disabledPowerSupplies power supplies."] == 1} {
		    APSMpReturn error "LEUTL_SetupForPARBypassToBooster: Unable to turn on $disabledPowerSupplies power supplies"
		}
		break
	    }

	    if {[llength $disabledPowerSupplies]} {
		if {[catch {APSDevSend \
				-releaseLinks 1 \
				-group LTPToEndPSOps \
				-operation TurnOn \
				-deviceList $disabledPowerSupplies \
				-timeout 0} result]} {
		    APSMpReturn error "LEUTL_SetupForPARBypassToBooster: $result"
		}
		APSWaitWithUpdate -waitSeconds 15
	    } else {
		break
	    }
	}
    }

    if {[llength $powerSuppliesCondition]} {
	APSMpStep "Starting conditioning" -desc "Starting conditioning"
	set tmpFile /tmp/[APSTmpString]
	set tmpFile2 /tmp/[APSTmpString]
	
	set i 0
	foreach supply $powerSuppliesCondition {
	    if {$i == 0} {
		append option "-match=column,CurrentControlName=${supply}*"
		incr i
	    } else {
		append option ",CurrentControlName=${supply}*,|"
	    }
	}
	set Standardize 1
	set Degauss 1
	if [catch {eval exec sddsprocess /home/helios/oagData/controlFiles/LEUTL/LEUTL.std \
		       -pipe=out $option \
		       | sddsxref -pipe $SCRFile \
		       -match=CurrentControlName=ControlName -take=ValueString \
		       | sddsprocess -pipe -delete=column,Value \
		       -scan=column,Value,ValueString,%le \
		       | sddsconvert -pipe=in $tmpFile -delete=column,Finish \
		       -rename=column,Value=Finish} result] {
	    APSSetVarAndUpdate status "No magnets to standardize"
	    set Standardize 0
#	    APSMpReturn error "LEUTL_SetupForPARBypassToBooster: $result"
	}
	if [catch {eval exec sddsprocess /home/helios/oagData/controlFiles/LEUTL/LEUTL_degauss.sdds \
		       -pipe=out $option \
		       | sddsxref -pipe $SCRFile \
		       -match=CurrentControlName=ControlName -take=ValueString \
		       | sddsprocess -pipe -delete=column,Value \
		       -scan=column,Value,ValueString,%le \
		       | sddsconvert -pipe=in $tmpFile2 -delete=column,Finish \
		       -rename=column,Value=Finish} result] {
	    APSSetVarAndUpdate status "No magnets to degauss"
	    set Degauss 0
#	    APSMpReturn error "LEUTL_SetupForPARBypassToBooster: $result"
	}
	global execMode
	if {$Standardize} {
	    set standardizeID [APSMpParallel \
				   -procedure "APSPEMExec -command \"standardize $tmpFile\"" \
				   -mode Automatic]
	}
	if {$Degauss} {
	    set degaussID [APSMpParallel \
			       -procedure "APSPEMExec -command \"degauss $tmpFile2\"" \
			       -mode Automatic]
	}
	if {$Standardize} {
	    if {[catch {APSMpJoin $standardizeID} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error encountered while standardizing power supplies\n$result"] == 1} {
                    file delete -force $tmpFile
                    file delete -force $tmpFile2
                    APSMpReturn error "LEUTL_SetupForPARBypassToBooster: Error in standardizing: $result"
                }
	    }
	}
	if {$Degauss} {
	    if {[catch {APSMpJoin $degaussID} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error encountered while degaussing power supplies\n$result"] == 1} {
                    file delete -force $tmpFile
                    file delete -force $tmpFile2
                    APSMpReturn error "LEUTL_SetupForPARBypassToBooster: Error in degaussing: $result"
                }
	    }
	}
	APSMpStep "Waiting for conditioning to finish" -desc "Waiting for conditioning to finish"
	set data ""
	set data2 ""
	if {$Standardize} {
	    if {[catch {exec sdds2stream $tmpFile -col=ControlName,Finish} data]} {
		APSMpReturn error "LEUTL_SetupForPARBypassToBooster: $data"
	    }
	}
	if {$Degauss} {
	    if {[catch {exec sdds2stream $tmpFile2 -col=ControlName,Finish} data2]} {
		APSMpReturn error "LEUTL_SetupForPARBypassToBooster: $data2"
	    }
	}
	set names ""
	set values ""
	foreach "name value" $data {
	    lappend names $name
	    lappend values $value
	}
	set names2 ""
	set values2 ""
	foreach "name value" $data2 {
	    lappend names2 $name
	    lappend values2 $value
	}
	set names3 "$names $names2"
	if {[llength $names3]} {
	    set wait 1
	    while {$wait} {
		set wait 0
		APSWaitWithUpdate -waitSeconds 5
		if {[catch {APSDevSend \
				-releaseLinks 1 \
				-group LTPToEndPSOps \
				-operation QueryConditioning \
				-deviceList $names3} results]} {
		    APSMpReturn error "LEUTL_SetupForPARBypassToBooster: $results"
		}
		foreach result $results {
		    if {$result} {
			set wait 1
			break
		    }
		}
	    }
	}
    }

    APSMpStep "Setting final current" -desc "Setting final current"
    if {$Standardize} {
	if {[catch {APSDevSend \
			-releaseLinks 1 \
			-group LTPToEndPSOps \
			-operation SetCurrent \
			-deviceList $names \
			-valueList $values \
			-timeout 0} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Error encountered while setting final current for $names\n$result"] == 1} {
                APSMpReturn error "LEUTL_SetupForPARBypassToBooster: $result"
            }
	}
    }
    if {$Degauss} {
	if {[catch {APSDevSend \
			-releaseLinks 1 \
			-group LTPToEndPSOps \
			-operation SetCurrent \
			-deviceList $names2 \
			-valueList $values2 \
			-timeout 0} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Error encountered while setting final current for $names2\n$result"] == 1} {
                APSMpReturn error "LEUTL_SetupForPARBypassToBooster: $result"
            }
	}
    }

    file delete -force $tmpFile
    file delete -force $tmpFile2

    APSMpReturn ok
}
