
# RFGun Startup from Standby of Fault Mode.
# This procedure is to be used when restoring the RFGun to
# operation from standby mode or in a case when you would
# experience a vacuum, BL or TW trip or rad monitor trip.
#
# Warning: Make sure the RFGun Interlock Monitor is no longer running

proc RFGUN_StartupInfo {} {
    return "RFGun Startup from Standby or Fault Mode.\
This procedure is to be used when restoring the RFGun to\
operation from standby mode or in a case when you would\
experience a vacuum, BL or TW trip or rad monitor trip."
}

proc RFGUN_Startup {args} {
    set SCRFile ""
    set CathodeHeaterSetpoint ""
    set CathodeHeaterWatts ""
    set KLYFwdPwr ""
    set KickerSetpoint ""
    set resumeRFPowerControlLaws 1
    set bypassMode 0
    set resumeSmartMonitor 1
    set high 0
    set sectors "L1 L2 L3 L4 L5"
    set changeBypassState 0
    set changeMode 0
    set skipLLRFChecks 0
    set Modulators 0
    foreach sector $sectors {
	set $sector 1
    }

    global execMode

    if {$execMode == "Manual"} {
	set prefix "Press Continue to "
    } else {
	set prefix ""
    }

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

    if {[catch {APSRFGUN_DetectSelectedGun} gun]} {
	APSMpReturn error "RFGUN_Startup: $gun"
    }
    APSParseArguments {gun SCRFile high L1 L2 L3 L4 L5 skipLLRFChecks Modulators}
    if {$gun == "RG2"} {
	set deviceList 2
	set KLYFwdPwrMin 8.0e6
#	if {[catch {exec cavget -list=L:RFG:smartMonitorParm7C -pend=20} SectFwdPwrMin]} {
#	    set SectFwdPwrMin 8e+06
#	}
    } elseif {$gun == "RG1"} {
	set deviceList 1
	set KLYFwdPwrMin 8.0e6
	#if {[catch {exec cavget -list=L:RFG:smartMonitorParm6C -pend=20} SectFwdPwrMin]} {
	#    set SectFwdPwrMin 5e+06
	#}
#        set SectFwdPwrMin 6.8e+06
    } else {
	APSMpReturn error "RFGUN_Startup: Unable to detect which Gun is selected. Check the LINAC RF Switching System State to ensure it is set to RUNNING and not LOCAL SWITCH or REMOTE SWITCH."
    }
#    set SectFwdPwrMin [expr {$SectFwdPwrMin + 100000}]
    global APSMpLControlPS
    
    set arrayName APSMpLControlPS
    
    APSLGenericPSArraySetup -arrayName $arrayName -SCRFile $SCRFile

    if {(![file exists $SCRFile]) && ($execMode == "Automatic")} {
	set execMode "Semi-Automatic"
    }

    APSMpStep init -promptDialog \
      "APSLGenericPSDialog -chooseSCR 1 -arrayName $arrayName -frame "
    
    set SCRFile $APSMpLControlPS(Filename)
    if {![file exists $SCRFile]} {
	APSMpReturn error "RFGUN_Startup: No SCR file selected"
    }
    if {[catch {exec sdds2stream $SCRFile -parameter=SnapshotDescription -page=1 -noquotes} results]} {
	APSMpReturn error "RFGUN_Startup: Invalid SCR file"
    }    
    if {[string first "Limited save:" $results] != -1} {
        if {[catch {exec sddssort $SCRFile -pipe=out -column=Beamline -unique | sdds2stream -pipe=in -col=Beamline} results]} {
            APSMpReturn error "RFGUN_Startup: Problem reading beamlines categories from the SCR file"
        } else {
            if {([lsearch -exact $results L1] == -1) || \
                  ([lsearch -exact $results L2] == -1) || \
                  ([lsearch -exact $results L3] == -1) || \
                  ([lsearch -exact $results L4] == -1) || \
                  ([lsearch -exact $results L5] == -1) || \
                  ([lsearch -exact $results rfGun] == -1) || \
                  ([lsearch -exact $results rfGun1] == -1) || \
                  ([lsearch -exact $results rfGun2] == -1)} {
                APSMpReturn error "RFGUN_Startup: LIMITED SAVE SCR file does not include all the Linac and rfGun beamline categories"
            }
        }
    }

    if {[catch {exec sddsselect $SCRFile /home/helios/oagData/pem/linac/filterFile -match=ControlName -pipe=out | sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
	APSMpReturn error "RFGUN_Startup: Invalid SCR file"
    }

    set gateStartTime 0
    set gateWidth 0
    set rfgForwardPowerSCR 0
    foreach {controlName valueString} $results {
        if {[string range $controlName end-3 end] == ".VAL"} {
            set controlName [string range $controlName 0 end-4]
        }
	if {$controlName == "L1:${gun}:HTR:CurrentAO"} {
	    set CathodeHeaterSetpoint [expr 2.75 * $valueString]
	} elseif {$controlName == "L1:${gun}:HTR:VoltageAO"} {
	    set CathodeHeaterSetpoint $valueString
	} elseif {$controlName == "L1:${gun}:HTR:PowerCC"} {
	    set CathodeHeaterWatts $valueString
	} elseif {$controlName == "L1:KY:DC2ARF"} {
	    set KLYFwdPwr $valueString
	} elseif {$controlName == "L3:KY:DC2ARF"} {
	    set KLYFwdPwr3 $valueString
	} elseif {$controlName == "L1:${gun}:KIK:VoltSetSendAO"} {
	    set KickerSetpoint $valueString
	} elseif {"L1:TM:RFG:RF:startTimeAO" == $controlName} {
	    set gateStartTime $valueString
	} elseif {"L1:TM:RFG:RF:widthAO" == $controlName} {
	    set gateWidth $valueString
	} elseif {"L:BPD:L1P1:RFGUN1:SetpointAO" == $controlName} {
	    set rg1phasesetpoint $valueString
	} elseif {"L:BPD:L1P1:RFGUN2:SetpointAO" == $controlName} {
	    set rg2phasesetpoint $valueString
	} elseif {"L:BPD:L1P1:L2AS1:SetpointAO" == $controlName} {
	    set l2phasesetpoint $valueString
	} elseif {"L:BPD:L3P3:L4AS1:SetpointAO" == $controlName} {
	    set l4phasesetpoint $valueString
	} elseif {"L:BPD:L3P3:L4AS1:SetpointAO" == $controlName} {
	    set l5phasesetpoint $valueString
	} elseif {"L1:RFG:DC2ARF" == $controlName} {
	    set rfgForwardPowerSCR $valueString
	} elseif {"L1:RFG:DC2ARF.VAL" == $controlName} {
	    set rfgForwardPowerSCR $valueString
	}
    }

    APSStrictParseArguments {CathodeHeaterSetpoint CathodeHeaterWatts KLYFwdPwr KickerSetpoint resumeRFPowerControlLaws bypassMode resumeSmartMonitor changeBypassState changeMode}

    if {[catch {APSDevSend \
                  -group LinacRFGun \
                  -operation ReadRFCurrentMode \
                  -deviceList 0} linacMode]} {
	APSMpReturn error "RFGUN_Startup: $linacMode"
    }
    if {[join $linacMode] == "K1 Down"} {
        set L1SectorSource 3
        set L2SectorSource 2
        set KLYFwdPwr $KLYFwdPwr3
    } elseif {[join $linacMode] == "K2 Down"} {
        set L1SectorSource 1
        set L2SectorSource 3
    } else {
        set L1SectorSource 1
        set L2SectorSource 2
    }

    if {($CathodeHeaterSetpoint == "")} {
	APSMpReturn error "RFGUN_Startup: No Cathode Heater Voltage setpoint found. Invalid SCR file"
    }
    if {($CathodeHeaterWatts == "")} {
	APSMpReturn error "RFGUN_Startup: No Cathode Heater Power setpoint found. Invalid SCR file"
    }
    if {($KLYFwdPwr == "")} {
	APSMpReturn error "RFGUN_Startup: No Klystron Forward Power setpoint found. Invalid SCR file"
    }
    if {$CathodeHeaterWatts < 9} {
        APSMpStep "Cathode Heater Power Warning" -desc "Cathode Heater Power Warning"
        if {[APSPEMTKDialog .warningDialog -text "The heater power level in the SCR file you chose is only $CathodeHeaterWatts, which may indicate an inappropriate SCR file was chosen."] == 1} {
            APSMpReturn error "RFGUN_Startup: Invalid SCR file (heater power too low)"
        }
    }

    set CathodeHeaterWattsMin [expr {$CathodeHeaterWatts * .5}]
    set CathodeHeaterWattsMax [expr {$CathodeHeaterWatts * 1.042}]


    set klystronList ""
    foreach sector "1 2 3" {
        if {[set L$sector]} {
            append klystronList "$sector "
        }
    }
    if {[llength $klystronList]} {
        APSMpStep "${prefix}Suspend $klystronList Power Control Stabilizer" -desc "Suspend L1, L2 and L3 power control stabilizers"
        if {[catch {APSLSuspendResumeRFPowerControllaws -klystronList $klystronList -mode suspend} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Error while suspending $klystronList power controllaws \n$result"] == 1} {
                APSMpReturn error "RFGUN_Startup: $result"
            }
        }
    }
    
    APSMpStep "${prefix}Suspend linac RF phase controllaw" -desc "Suspend linac RF phase controllaw"
    if {[catch {exec cavput -list=L:BPD:RFGUN1:L1L2L4L5RC.SUSP=1,L:BPD:RFGUN1:L1L2L4L5RC.SUSP=1} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem suspending the linac RF phase controllaw\nRFGUN_Startup: $result"] == 1} {
            APSMpReturn error "Problem suspending the linac RF phase controllaw: RFGUN_Startup: $result"
        }
    }
    if {[catch {exec cavput -list=L:BPD:RFGUN1RC.ABRT=1,L:BPD:RFGUN2RC.ABRT=1,L:BPD:RFGUN2K1DnRC.ABRT=1,L:BPD:RFGUN2K2DnRC.ABRT=1,L:BPD:L3P3:L4AS1RC.ABRT=1,L:BPD:L4P1:L5AS1RC.ABRT=1} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem suspending the linac RF phase controllaw\nRFGUN_Startup: $result"] == 1} {
            APSMpReturn error "Problem suspending the linac RF phase controllaw: RFGUN_Startup: $result"
        }
    }

    APSMpStep "${prefix}Set script control button Available" -desc "Set script control button to Available"
    if {[catch {APSDevSend \
                  -group LinacRFGun \
                  -operation SetActiveScript \
                  -deviceList 0 \
                  -value "Available"} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while setting the script control button to Available \n$result"] == 1} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
    }
    
    #modify here
    if {[join $linacMode] != "K1 Down"} {
        if {[catch {APScavget -list=L1:MO:LowPFNvSP} PFNLowTripValue]} {
            set PFNLowTripValue 22
        }
	APSMpStep "${prefix}Check PFN voltage for L1" -desc "Check that PFN voltage for L1 is above $PFNLowTripValue volts"
	if {[catch {APSLINAC_CheckModulatorCurrents -deviceList "1" -minValueList "$PFNLowTripValue"} result]} {
	    if {$execMode != "Automatic"} {
		bell
                if {[APSPEMTKDialog .warningDialog -text "L1 PFN voltage is less then $PFNLowTripValue Volts."] == 1} {
		    APSMpReturn error "RFGUN_Startup: Operation aborted by user"
		}
	    }
	}
    }
    #L1SectorSource can only be 1 or 3
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation QueryACISPermit400WAmp \
                  -deviceList $L1SectorSource} permit]} {
        APSMpReturn error "RFGUN_Startup: $permit"
    }
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation QueryACISLatch400WAmp \
                  -deviceList $L1SectorSource} latch]} {
        APSMpReturn error "RFGUN_Startup: $latch"
    }
    if {(!$permit) || (!$latch)} {
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ResetACIS400WAmp \
                      -deviceList $L1SectorSource -releaseLinks 1} result]} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
        APSWaitWithUpdate -waitSeconds 2
    }
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation Query400WAmpOn \
                  -deviceList $L1SectorSource} result]} {
        APSMpReturn error "RFGUN_Startup: $result"
    }
    if {!$result} {
        APSMpStep "${prefix}Turn 400W RF Amp On" -desc "Reset 400 watt amp if needed"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation Reset400WAmp \
                      -deviceList $L1SectorSource -releaseLinks 1} result]} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
    }
    #L1SectorSource can only be 1 or 3
    APSMpStep "${prefix}Set Klystron Forward Power" -desc "Set Klystron forward power"
    if {[catch {APSLINAC_SetKlystronForwardPower \
                  -deviceList $L1SectorSource \
                  -KLYFwdPwr $KLYFwdPwr} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while setting klystron forward power \n$result"] == 1} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
    }

    APSMpStep "${prefix}Turn on heater power" -desc "Turn the heater on"
    if {[catch {APSDevSend \
                  -group LinacRFGun \
                  -operation QueryHeaterPowerOn \
                  -deviceList $deviceList} result]} {
	APSMpReturn error "RFGUN_Startup: $result"
    }
    #This pv is backwards
    if {$result} {
	if {[catch {APSDevSend \
                      -group LinacRFGun \
                      -operation TurnOnHeaterPower \
                      -deviceList $deviceList} result]} {
	    APSMpReturn error "RFGUN_Startup: $result"
	}
        if {[catch {APSRFGUN_SetCathodeHeaterCurrent \
                      -value 0.0 \
                      -deviceList $deviceList} result]} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
        set changeMode 0
        if {[catch {APSDevSend \
                      -group LinacRFGun \
                      -operation QueryHeaterPowerOn \
                      -deviceList $deviceList} result]} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
        set steps 0
        while {$result} {
            incr steps
            if {$steps > 20} {
                if {[APSPEMTKDialog .warningDialog -text "Please turn on the cathode heater power supply."] == 1} {
                    APSMpReturn error "RFGUN_Startup: Operation aborted by user"
                }
                break
            }
            after 1000
            if {[catch {APSDevSend \
                          -group LinacRFGun \
                          -operation QueryHeaterPowerOn \
                          -deviceList $deviceList} result]} {
                APSMpReturn error "RFGUN_Startup: $result"
            }
        }
    }

    if {!$skipLLRFChecks} {
        APSMpStep "${prefix}Check if L$L1SectorSource LLRF is on" -desc "Check if L1 is on"
        if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
            if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
                APSMpReturn error "RFGUN_Startup: $result"
            }
        }
    }

    if {[catch {APScavput -list=L1:RG${deviceList}:HTR:ACISResetSEQ.PROC=1} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem occured while resetting the ACIS Interlock: $result"] == 1} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
    }

    if {!$changeMode} {
        if {[catch {exec cavget -list=L1:RG${deviceList}:HTR:VoltageAO} cathodeHeaterVoltageValue]} {
            set cathodeHeaterVoltageValue 0
        }
        if {$cathodeHeaterVoltageValue < [expr {$CathodeHeaterSetpoint / 8.0}]} {
            APSMpStep "${prefix}Set RFGun cathode heater current to 1/8 value" \
              -desc "Set RFGun cathode heater current to 1/8 value"
            if {[catch {APSRFGUN_SetCathodeHeaterCurrent \
                          -value [expr {$CathodeHeaterSetpoint / 8.0}] \
                          -deviceList $deviceList} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while setting RFGun cathode heater current to 1/8 value \n$result"] == 1} {
                    APSMpReturn error "RFGUN_Startup: $result"
                }
            }
            
            if {$bypassMode} {
                for {set i 0} {$i < 3} {incr i} {
                    APSMpStep "${prefix}Wait 30 seconds for cathode heater current to stabilize" \
                      -desc "Wait 30 seconds for cathode heater current to stabilize"
                    APSWaitWithUpdate -waitSeconds 10
                    if {!$skipLLRFChecks} {
                        if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
                            if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
                                APSMpReturn error "RFGUN_Startup: $result"
                            }
                        }
                    }
                }
            } else {
                for {set i 0} {$i < 3} {incr i} {
                    APSMpStep "${prefix}Wait 15 seconds for cathode heater current to stabilize" \
                      -desc "Wait 15 seconds for cathode heater current to stabilize"
                    APSWaitWithUpdate -waitSeconds 5
                    if {!$skipLLRFChecks} {
                        if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
                            if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
                                APSMpReturn error "RFGUN_Startup: $result"
                            }
                        }
                    }
                }
            }
        }
        if {$cathodeHeaterVoltageValue < [expr {$CathodeHeaterSetpoint / 4.0}]} {
            APSMpStep "${prefix}Set RFGun cathode heater current to 1/4 value" \
              -desc "Set RFGun cathode heater current to 1/4 value"
            if {[catch {APSRFGUN_SetCathodeHeaterCurrent \
                          -value [expr {$CathodeHeaterSetpoint / 4.0}] \
                          -deviceList $deviceList} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while setting RFGun cathode heater current to 1/4 value \n$result"] == 1} {
                    APSMpReturn error "RFGUN_Startup: $result"
                }
            }
            
            if {$bypassMode} {
                for {set i 0} {$i < 3} {incr i} {
                    APSMpStep "${prefix}Wait 30 seconds for cathode heater current to stabilize" \
                      -desc "Wait 30 seconds for cathode heater current to stabilize"
                    APSWaitWithUpdate -waitSeconds 10
                    if {!$skipLLRFChecks} {
                        if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
                            if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
                                APSMpReturn error "RFGUN_Startup: $result"
                            }
                        }
                    }
                }
            } else {
                for {set i 0} {$i < 3} {incr i} {
                    APSMpStep "${prefix}Wait 15 seconds for cathode heater current to stabilize" \
                      -desc "Wait 15 seconds for cathode heater current to stabilize"
                    APSWaitWithUpdate -waitSeconds 5
                    if {!$skipLLRFChecks} {
                        if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
                            if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
                                APSMpReturn error "RFGUN_Startup: $result"
                            }
                        }
                    }
                }
            }
        }


        if {$cathodeHeaterVoltageValue < [expr {3.0 * $CathodeHeaterSetpoint / 8.0}]} {
            APSMpStep "${prefix}Set RFGun cathode heater current to 3/8 value" \
              -desc "Set RFGun cathode heater current to 3/8 value"
            if {[catch {APSRFGUN_SetCathodeHeaterCurrent \
                          -value [expr {3.0 * $CathodeHeaterSetpoint / 8.0}] \
                          -deviceList $deviceList} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while setting RFGun cathode heater current to 3/8 value \n$result"] == 1} {
                    APSMpReturn error "RFGUN_Startup: $result"
                }
            }
            
            if {$bypassMode} {
                for {set i 0} {$i < 3} {incr i} {
                    APSMpStep "${prefix}Wait 30 seconds for cathode heater current to stabilize" \
                      -desc "Wait 30 seconds for cathode heater current to stabilize"
                    APSWaitWithUpdate -waitSeconds 10
                    if {!$skipLLRFChecks} {
                        if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
                            if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
                                APSMpReturn error "RFGUN_Startup: $result"
                            }
                        }
                    }
                }
            } else {
                for {set i 0} {$i < 3} {incr i} {
                    APSMpStep "${prefix}Wait 15 seconds for cathode heater current to stabilize" \
                      -desc "Wait 15 seconds for cathode heater current to stabilize"
                    APSWaitWithUpdate -waitSeconds 5
                    if {!$skipLLRFChecks} {
                        if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
                            if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
                                APSMpReturn error "RFGUN_Startup: $result"
                            }
                        }
                    }
                }
            }
        }



        if {$cathodeHeaterVoltageValue < [expr {$CathodeHeaterSetpoint / 2.0}]} {
            APSMpStep "${prefix}Set RFGun cathode heater current to half value" \
              -desc "Set RFGun cathode heater current to half value"
            if {[catch {APSRFGUN_SetCathodeHeaterCurrent \
                          -value [expr {$CathodeHeaterSetpoint / 2.0}] \
                          -deviceList $deviceList} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while setting RFGun cathode heater current to half value \n$result"] == 1} {
                    APSMpReturn error "RFGUN_Startup: $result"
                }
            }
            if {$bypassMode} {
                for {set i 0} {$i < 3} {incr i} {
                    APSMpStep "${prefix}Wait 30 seconds for cathode heater current to stabilize" \
                      -desc "Wait 30 seconds for cathode heater current to stabilize"
                    APSWaitWithUpdate -waitSeconds 10
                    if {!$skipLLRFChecks} {
                        if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
                            if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
                                APSMpReturn error "RFGUN_Startup: $result"
                            }
                        }
                    }
                }
            } else {
                for {set i 0} {$i < 3} {incr i} {
                    APSMpStep "${prefix}Wait 15 seconds for cathode heater current to stabilize" \
                      -desc "Wait 15 seconds for cathode heater current to stabilize"
                    APSWaitWithUpdate -waitSeconds 5
                    if {!$skipLLRFChecks} {
                        if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
                            if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
                                APSMpReturn error "RFGUN_Startup: $result"
                            }
                        }
                    }
                }
            }
        }


        if {$cathodeHeaterVoltageValue < [expr {5.0 * $CathodeHeaterSetpoint / 8.0}]} {
            APSMpStep "${prefix}Set RFGun cathode heater current to 5/8 value" \
              -desc "Set RFGun cathode heater current to 5/8 value"
            if {[catch {APSRFGUN_SetCathodeHeaterCurrent \
                          -value [expr {5.0 * $CathodeHeaterSetpoint / 8.0}] \
                          -deviceList $deviceList} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while setting RFGun cathode heater current to 5/8 value \n$result"] == 1} {
                    APSMpReturn error "RFGUN_Startup: $result"
                }
            }
            
            for {set i 0} {$i < 3} {incr i} {
                APSMpStep "${prefix}Wait 30 seconds for cathode heater current to stabilize" \
                  -desc "Wait 30 seconds for cathode heater current to stabilize"
                APSWaitWithUpdate -waitSeconds 10
                if {!$skipLLRFChecks} {
                    if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
                        if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
                            APSMpReturn error "RFGUN_Startup: $result"
                        }
                    }
                }
            }
        }



        if {$cathodeHeaterVoltageValue < [expr {$CathodeHeaterSetpoint * .75}]} {
            APSMpStep "${prefix}Set RFGun cathode heater current to 3/4 value" \
              -desc "Set RFGun cathode heater current to 3/4 value"
            if {[catch {APSRFGUN_SetCathodeHeaterCurrent \
                          -value [expr {$CathodeHeaterSetpoint * .75}] \
                          -deviceList $deviceList} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while setting RFGun cathode heater current to 3/4 value \n$result"] == 1} {
                    APSMpReturn error "RFGUN_Startup: $result"
                }
            }
            for {set i 0} {$i < 3} {incr i} {
                APSMpStep "${prefix}Wait 30 seconds for cathode heater current to stabilize" -desc "Wait 30 seconds for cathode heater current to stabilize"
                APSWaitWithUpdate -waitSeconds 10
                if {!$skipLLRFChecks} {
                    if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
                        if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
                            APSMpReturn error "RFGUN_Startup: $result"
                        }
                    }
                }
            }
        }


        if {$cathodeHeaterVoltageValue < [expr {7.0 * $CathodeHeaterSetpoint / 8.0}]} {
            APSMpStep "${prefix}Set RFGun cathode heater current to 7/8 value" \
              -desc "Set RFGun cathode heater current to 7/8 value"
            if {[catch {APSRFGUN_SetCathodeHeaterCurrent \
                          -value [expr {7.0 * $CathodeHeaterSetpoint / 8.0}] \
                          -deviceList $deviceList} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while setting RFGun cathode heater current to 7/8 value \n$result"] == 1} {
                    APSMpReturn error "RFGUN_Startup: $result"
                }
            }
            for {set i 0} {$i < 3} {incr i} {
                APSMpStep "${prefix}Wait 30 seconds for cathode heater current to stabilize" -desc "Wait 30 seconds for cathode heater current to stabilize"
                APSWaitWithUpdate -waitSeconds 10
                if {!$skipLLRFChecks} {
                    if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
                        if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
                            APSMpReturn error "RFGUN_Startup: $result"
                        }
                    }
                }
            }
        }
    }



    APSMpStep "${prefix}Set RFGun cathode heater current" -desc "Set RFGun cathode heater current"
    if {[catch {APSRFGUN_SetCathodeHeaterCurrent \
                  -value $CathodeHeaterSetpoint \
                  -deviceList $deviceList} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while setting RFGun cathode heater current \n$result"] == 1} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
    }

    APSWaitWithUpdate -waitSeconds 5
    if {[catch {APSDevSend \
                  -group LinacRFGun \
                  -operation ReadCathodeHeaterCurrent \
                  -deviceList $deviceList} result]} {
	APSMpReturn error "RFGUN_Startup: $result"
    }
    if {$result < 0.1} {
        if {[APSPEMTKDialog .warningDialog -text "Please reset RFgun Smart Monitor and turn on the cathode heater power supply."] == 1} {
	    APSMpReturn error "RFGUN_Startup: Operation aborted by user"
	}
    }
        
    APSMpStep "${prefix}Select LLRF ON" -desc "Turn L${L1SectorSource} LLRF on"
    if {[catch {APSLINAC_LLRFOnOff -button "On" -deviceList $L1SectorSource} result]} {
	if {[APSPEMTKDialog .warningDialog -text "Error while turning on LLRF for sector $L1SectorSource \n$result"] == 1} {
	    APSMpReturn error "RFGUN_Startup: $result"
	}
    }

    #APSMpStep "Resume power control scripts for sector $L1SectorSource" -desc "Resume power control script"
    #if {[catch {LMOCS_PowerControlLawSetup -mode high -deviceList L$L1SectorSource} result]} {
#	if {[APSPEMTKDialog .warningDialog -text "Error while setting L$L1SectorSource power controllaw into high mode \n$result"] == 1} {
#	    APSMpReturn error "RFGUN_Startup: $result"
#	}
#    }
    #if {[catch {APSLSuspendResumeRFPowerControllaws -klystronList $L1SectorSource -mode resume} result]} {
#	if {[APSPEMTKDialog .warningDialog -text "Error while resuming power control scripts for sector $L1SectorSource \n$result"] == 1} {
#	    APSMpReturn error "RFGUN_Startup: $result"
#	}
#    }	

#    set KLYFwdPwrMin [expr {$KLYFwdPwr - 100000}]
#    APSMpStep "${prefix}Wait for Klystron forward power to reach $KLYFwdPwrMin" -desc "Wait for Klystron forward power to reach a minimum value"
    if {0} {
        if {[catch {APSMpLWaitForMinimumValue \
                      -deviceList $L1SectorSource \
                      -group LinacKlystron \
                      -operation ReadForwardPower \
                      -minValue $KLYFwdPwrMin \
                      -intervalLimit 900 \
                      -intervalTime 1} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Error while waiting for Klystron forward power to reach $KLYFwdPwrMin \n$result"] == 1} {
                APSMpReturn error "RFGUN_Startup: $result"
            }
        }
    }
#    if {[catch {LMOCS_PowerControlLawSetup -mode low -deviceList L$L1SectorSource} result]} {
#	if {[APSPEMTKDialog .warningDialog -text "Error while setting L$L1SectorSource power controllaw into high mode \n$result"] == 1} {
#	    APSMpReturn error "RFGUN_Startup: $result"
#	}
#    }
    #done



    APSMpStep "${prefix}Set gate valves" -desc "Set gate valves"
    if {[catch {
	APSRFGUN_OpenCloseGateValve -deviceList L1GV1 -value Close -group LinacValves
	APSRFGUN_OpenCloseGateValve -deviceList L1GV2 -value Open -group LinacValves
	if {$gun == "RG2"} {
	    APSRFGUN_OpenCloseGateValve -deviceList 2 -value Open -group LinacRFGun
	    APSRFGUN_OpenCloseGateValve -deviceList 1 -value Close -group LinacRFGun
	} else {
	    APSRFGUN_OpenCloseGateValve -deviceList 2 -value Close -group LinacRFGun
	    APSRFGUN_OpenCloseGateValve -deviceList 1 -value Open -group LinacRFGun
	}
    } result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while setting up the gate valves \n$result"] == 1} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
    }

    APSMpStep "${prefix}Turn the kicker charge pulse off" -desc "Turn the kicker charge pulse off"
    if {[catch {exec cavput -list=L1:RG1:KIK:chargeTrigC=0,L1:RG2:KIK:chargeTrigC=0 -num -pend=20} results]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while turning the kicker charge pulse off \n$results"] == 1} {
            APSMpReturn error "RFGUN_Startup: $results"
        }
    }

    APSMpStep "${prefix}Check if L$L1SectorSource LLRF is on" -desc "Check if L1 is on"
    if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
	if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
	    APSMpReturn error "RFGUN_Startup: $result"
	}
    }

    APSMpStep "${prefix}Check that the RFGun cathode heater power reaches $CathodeHeaterWattsMin but is below $CathodeHeaterWattsMax" -desc "Check that the RFGun cathode heater power reaches a minimum value"
    if {[catch {APSRFGUN_CathodeHeaterPower -deviceList $deviceList -wattsMin $CathodeHeaterWattsMin -watts $CathodeHeaterWatts -wattsMax $CathodeHeaterWattsMax} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while checking that the RFGun cathode heater power reaches a minimum value \n$result"] == 1} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
    }
    
    APSMpStep "${prefix}Reset Timing System" -desc "Reset Timing System"
    if {[catch {APSRFGUN_ResetTimingSystem} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while reseting the timing system \n$result"] == 1} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
    }

    APSMpStep "${prefix}Check if L$L1SectorSource LLRF is on" -desc "Check if L1 is on"
    if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
	if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on"] == 1} {
	    APSMpReturn error "RFGUN_Startup: $result"
	}
    }

    if {0} {
        APSMpStep "${prefix}Wait for power controllaw to increase the power in L$L1SectorSource" -desc "Wait for power controllaw to increase the power"
        while 1 {
            if {[catch {exec cavget -list=L${L1SectorSource}:KY:DC2ARF:ErrorM -num -pend=20} errorValue]} {
                APSMpReturn error "RFGUN_Startup: $errorValue"
            }
            if {[expr abs($errorValue)] < 1000e3} {
                break
            } else {
                APSMpStep "${prefix}Wait for L$L1SectorSource power control to increase power ([clock format [clock seconds] -format %T])" -desc "Wait for L$L1SectorSource power control to increase power"
                if {[catch {APSDevSend \
                              -group LinacKlystron \
                              -operation QueryLLRFOn \
                              -deviceList $L1SectorSource} result]} {
                    APSMpReturn error "RFGUN_Startup: $result"
                }
                if {!$result} {
                    if {[APSPEMTKDialog .warningDialog -text "RFGUN_Startup: L$L1SectorSource LLRF tripped. Please fix."] == 1} {
                        APSMpReturn error "RFGUN_Startup: L$L1SectorSource LLRF tripped."
                    }
                }
                if [catch {APSDevSend \
                             -group LinacKlystron \
                             -operation QueryPowerControlRunning \
                             -deviceList $L1SectorSource} results] {
                    APSMpReturn error "RFGUN_Startup: $results"
                }
                if {$results != 1} {
                    set answer [APSPEMTKDialog .warningDialog -text "RFGUN_Startup: sector $L1SectorSource power control is not running. Please fix." -strings {Continue Recheck "Abort Procedure"}]
                    if {$answer == 2} {
                        APSMpReturn error "RFGUN_Startup:  sector $L1SectorSource power control is not running."
                    }
                    if {$answer == 0} {
                        break
                    }
                }
            }
            APSWaitWithUpdate -waitSeconds 5
        }
    }

    set rfgForwardPowerSCR [expr $rfgForwardPowerSCR * .9]
    set step 0
    APSMpStep "${prefix}Wait for L1:RFG:DC2ARF to reach $rfgForwardPowerSCR" -desc "Wait for L1:RFG:DC2ARF to reach 90% full power"
    while 1 {
        if {[catch {exec cavget -list=L1:RFG:DC2ARF -num -pend=20} rfgForwardPower]} {
            APSMpReturn error "RFGUN_Startup: $rfgForwardPower"
        }
        if {$rfgForwardPower > $rfgForwardPowerSCR} {
            break
        }
        incr step
        if {$step > 84} {
            set answer [APSPEMTKDialog .warningDialog -text "L1:RFG:DC2ARF has not reached $rfgForwardPowerSCR" -strings {Continue "Wait Longer" "Abort Procedure"}]
            if {$answer == 2} {
                APSMpReturn error "RFGUN_Startup: L1:RFG:DC2ARF has not reached $rfgForwardPowerSCR"
            }
            if {$answer == 1} {
                set step 0
            }
            if {$answer == 0} {
                break
            }
        }
        APSWaitWithUpdate -waitSeconds 5
        APSMpStep "${prefix}Wait for L1:RFG:DC2ARF to reach $rfgForwardPowerSCR"
    }

    APSMpStep "${prefix}Resume fixedCurrent" -desc "Resume fixedCurrent"
    if {[catch {APSMpLSuspendResumeRunControl \
                  -value "Resume" \
                  -name "FixedCurrent" \
                  -group "LinacRFGun" \
                  -deviceList 0 \
                  -port 4579 \
                  -executable "fixedCurrent -start 1"} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while resuming the hold current script \n$result"] == 1} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
    }	        


    set CathodeHeaterWattsMin [expr {$CathodeHeaterWatts * .9}]
    APSMpStep "${prefix}Check that the RFGun cathode heater power reaches $CathodeHeaterWattsMin but is below $CathodeHeaterWattsMax" -desc "Check that the RFGun cathode heater reaches a minimum value"
    if {[catch {APSRFGUN_CathodeHeaterPower -deviceList $deviceList -wattsMin $CathodeHeaterWattsMin -watts $CathodeHeaterWatts -wattsMax $CathodeHeaterWattsMax} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while checking that the RFGun cathode heater power reaches a minimum value \n$result"] == 1} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
    }

    if {$resumeSmartMonitor} {
	if 0 {
	APSMpStep "${prefix}Resume Smart Monitor" -desc "Resume Smart Monitor"
	catch {exec cavput -list=L:RFG:smartMonitorOnC.PROC=1 -num -pend=20}
        APSWaitWithUpdate -waitSeconds 3
	catch {exec cavput -list=L:RFG:smartMonitorResetC=1 -num -pend=20}
        APSWaitWithUpdate -waitSeconds 3
        if {[catch {exec cavget -list=L:RFG:smartMonitorAlarmM -num -pend=20} result]} {
            if {$result != 0} {
                if {[APSPEMTKDialog .warningDialog -text "Problem resuming the smart monitor"] == 1} {
                    APSMpReturn error "RFGUN_Startup: $result"
                }
            }
        }
	}
    }

    APSMpStep "${prefix}Check if L$L1SectorSource LLRF is on" -desc "Check if L1 is on"
    if [catch {APSLINAC_CheckLLRFStatus -desiredState on -deviceList $L1SectorSource} result] {
	if {[APSPEMTKDialog .warningDialog -text "L$L1SectorSource LLRF is not on. Check smart monitor reset, check vacuum or water faults, check 400W amp trip"] == 1} {
	    APSMpReturn error "RFGUN_Startup: $result"
	}
    }



    APSMpStep "${prefix}Set Linac Phase Control Points from SCR File" -desc "${prefix}Set Linac Phase Control Points from SCR File"
    if {[info exists rg1phasesetpoint]} {
        if {[catch {APScavput -list=L:BPD:L1P1:RFGUN1:SetpointAO=$rg1phasesetpoint} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured while setting linac phase control points: $result"] == 1} {
                APSMpReturn error "RFGUN_Startup: $result"
            }
        }
    }
    if {[info exists rg2phasesetpoint]} {
        if {[catch {APScavput -list=L:BPD:L1P1:RFGUN2:SetpointAO=$rg2phasesetpoint} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured while setting linac phase control points: $result"] == 1} {
                APSMpReturn error "RFGUN_Startup: $result"
            }
        }
    }
    if {[info exists l2phasesetpoint]} {
        if {[catch {APScavput -list=L:BPD:L1P1:L2AS1:SetpointAO=$l2phasesetpoint} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured while setting linac phase control points: $result"] == 1} {
                APSMpReturn error "RFGUN_Startup: $result"
            }
        }
    }
    if {[info exists l4phasesetpoint]} {
        if {[catch {APScavput -list=L:BPD:L3P3:L4AS1:SetpointAO=$l4phasesetpoint} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured while setting linac phase control points: $result"] == 1} {
                APSMpReturn error "RFGUN_Startup: $result"
            }
        }
    }
    if {[info exists l5phasesetpoint]} {
        if {[catch {APScavput -list=L:BPD:L4P1:L5AS1:SetpointAO=$l5phasesetpoint} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured while setting linac phase control points: $result"] == 1} {
                APSMpReturn error "RFGUN_Startup: $result"
            }
        }
    }

    if {!$changeBypassState} {
        APSMpStep "${prefix}Resume linac RF phase controllaw" -desc "Resume linac RF phase controllaw"
        if {$gun == "RG1"} {
            if {[catch {exec cavput -list=L:BPD:RFGUN1:L1L2L4L5RC.SUSP=0} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Problem resuming the linac RF phase controllaw\nRFGUN_Startup: $result"] == 1} {
                    APSMpReturn error "Problem resuming the linac RF phase controllaw: RFGUN_Startup: $result"
                }
            }
            after 3000
            if {[catch [APScavget -noquote -list=L:BPD:RFGUN1:L1L2L4L5RC.PID] result]} {
            } else {
                if {[llength $result] != 1} {
                    exec cavput -list=L:BPD:RFGUN1:L1L2L4L5RC.CLR=1
                    set dir [pwd]
                    cd /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5
                    if {[catch {exec ./linacBeamRfPhase-L1RFGun1-L2-L4-L5Options -rcPV L:BPD:RFGUN1:L1L2L4L5RC} options]} {
                        APSMpReturn error "Unable to start linac RF phase controllaw: $options"
                    }
                    if {[catch {eval exec sddscontrollaw $options >& /dev/null &} result]} {
                        if {[APSPEMTKDialog .warningDialog -text "Unable to start linac RF phase controllaw: $result"] == 1} {
                            APSMpReturn error "Unable to start linac RF phase controllaw: $result"
                        }
                    }
                    cd $dir
                }
            }
        } else {
            if {[catch {exec cavput -list=L:BPD:RFGUN2:L1L2L4L5RC.SUSP=0} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Problem resuming the linac RF phase controllaw\nRFGUN_Startup: $result"] == 1} {
                    APSMpReturn error "Problem resuming the linac RF phase controllaw: RFGUN_Startup: $result"
                }
            }
            after 3000
            if {[catch [APScavget -noquote -list=L:BPD:RFGUN2:L1L2L4L5RC.PID] result]} {
            } else {
                if {[llength $result] != 1} {
                    exec cavput -list=L:BPD:RFGUN2:L1L2L4L5RC.CLR=1
                    set dir [pwd]
                    cd /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5
                    if {[catch {exec ./linacBeamRfPhase-L1RFGun2-L2-L4-L5Options -rcPV L:BPD:RFGUN2:L1L2L4L5RC} options]} {
                        APSMpReturn error "Unable to start linac RF phase controllaw: $options"
                    }
                    if {[catch {eval exec sddscontrollaw $options >& /dev/null &} result]} {
                        if {[APSPEMTKDialog .warningDialog -text "Unable to start linac RF phase controllaw: $result"] == 1} {
                            APSMpReturn error "Unable to start linac RF phase controllaw: $result"
                        }
                    }
                    cd $dir
                }
            }
        }
    }
    
    #    catch {exec cavput -list=L:RFG:smartMonitorEnableC=1 -num -pend=20}

    APSMpStep "${prefix}Set Kicker Setpoint" -desc "Set Kicker setpoint"
    if {[catch {APSDevSend \
                  -group LinacRFGun \
                  -operation SetKickerVoltage \
                  -deviceList $deviceList \
                  -value $KickerSetpoint} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while setting the kicker setpoint \n$result"] == 1} {
            APSMpReturn error "RFGUN_Startup: $result"
        }
    }

    APSMpStep "${prefix}Restore values from SCR file" -desc "Restore SCR file"

    set options "-match=column,ControlName=*MO:PFN*,!"
    set options2 "-match=column,Beamline=LINAC,Beamline=LI,|,Beamline=rfGun,|,Beamline=rfGun1,|,Beamline=rfGun2,|"

    if {$L1SectorSource == 3} {
        append options " -match=column,ControlName=L1:MO:PFN*,!"
        set options2 "-match=column,Beamline=L2,Beamline=L3,|,Beamline=LINAC,|,Beamline=LI,|,Beamline=rfGun,|,Beamline=rfGun1,|,Beamline=rfGun2,|"
    }
    if {$L2SectorSource == 3} {
        append options " -match=column,ControlName=L2:MO:PFN*,!"
        set options2 "-match=column,Beamline=L1,Beamline=L3,|,Beamline=LINAC,|,Beamline=LI,|,Beamline=rfGun,|,Beamline=rfGun1,|,Beamline=rfGun2,|"
    }
    if {$Modulators} {
        if {$L1} {
            append options2 ",Beamline=L1,|"
        }
        if {$L2} {
            append options2 ",Beamline=L2,|"
        }
        if {$L3} {
            append options2 ",Beamline=L3,|"
        }
        if {$L4} {
            append options2 ",Beamline=L4,|"
        }
        if {$L5} {
            append options2 ",Beamline=L5,|"
        }
    } else {
        if {$L1SectorSource == 3} {
            append options2 ",Beamline=L2,|,Beamline=L3,|"
        } elseif {$L2SectorSource == 3} {
            append options2 ",Beamline=L1,|,Beamline=L3,|"
        } else {
            append options2 ",Beamline=L1,|,Beamline=L2,|,Beamline=L3,|"
        }
        if {$L4} {
            append options2 ",Beamline=L4,|"
        }
        if {$L5} {
            append options2 ",Beamline=L5,|"
        }
    }

    if {[string length $SCRFile]} {
	APSMpStep RestoringSCRValues 
	set tmpFile /tmp/[APSTmpString]

	if {[catch {eval exec sddsprocess $SCRFile $tmpFile \
                      -match=column,IsReadOnly=+n \
                      -match=column,IsProtected=+n \
                      -match=column,Category=Diag,Category=Gun,|,Category=InTiming,|,Category=PulsedPS,|,Category=RF,|,Category=RFConstants,|,Category=Scrapers,|,Category=SteeringSetpoint,|,Category=Timing,| \
                      $options \
                      $options2 \
                      -match=col,ControlType=,! -match=col,ControlName=,! \
                      -match=column,ControlName=L:L?Stabilizer:SDDS*,!
	    exec sddscasr -restore $tmpFile} result]} {
            APSPEMTKDialog .warningDialog -strings Continue -default 0 -text "Problem restoring SCR file: RFGUN_Startup: $result"
            catch {APSSendEMail -address soliday \
                     -subject "Problem restoring SCR file."  \
                     -message "Problem restore SCR file\nRFGUN_Startup\n$SCRFile\n$result"} 
	}
	file delete $tmpFile

    }
    
    APSMpStep "${prefix}Turn the kicker on" -desc "Turn the kicker on"
    if {$gun == "RG1"} {
	if {[catch {APSRFGUN_TurnKickerOnOff -deviceList 1 -value 0 -state "on"} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Unable to turn off rfgun 1 kicker\n$result"] == 1} {
                APSMpReturn error "RFGUN_SwitchWith: $result"
            }
	}
    } elseif {$gun == "RG2"} {
	if {[catch {APSRFGUN_TurnKickerOnOff -deviceList 2 -value 0 -state "on"} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Unable to turn off rfgun 2 kicker\n$result"] == 1} {
                APSMpReturn error "RFGUN_SwitchWith: $result"
            }
	}
    }


    APSMpReturn ok
}

proc APSLINACFindMostRecentSCRFile {} {
    set machine LPL
    set oldDir [pwd]
    set snapDir /home/helios/oagData/SCR/snapshots/$machine
    cd $snapDir
    set time [clock seconds]
    if {[file exists collapsed]} {
        set collapsedDirectoryFound 1
        cd collapsed
    } else {
        set collapsedDirectoryFound 0
    }
    set fileList [APSFindFilesBetweenDates -directory . -rootname c$machine -tailsOnly 1 \
                    -startDateList [clock format [expr {$time - 5184000}] -format "%Y %j %m %d"] \
                    -endDateList [clock format $time -format "%Y %j %m %d"] \
                    -extensionList {""}]
    if {[llength $fileList]==0} {
        cd $oldDir
        return -code ok ""
    }
    set fileList [lindex [lsort $fileList] end]
    if {[catch {exec sdds2stream $fileList -column=SnapshotFilename} result]} {
        cd $oldDir
        return -code ok ""
    }
    set result [file join $snapDir $result]
    if {![file exists $result]} {
	set result ${result}.gz
	if {![file exists $result]} {
	    cd $oldDir
	    return -code ok ""
	}	
    }
    cd $oldDir
    return -code ok $result
}

proc APSRFGUN_ResetTimingSystem {} {
    if {[catch {exec cavput -list=L1:KY:DC2ARF.SPD=On,L1:KY:DC2ARF.AQWF=On} result]} {
	return -code error "APSRFGUN_ResetTimingSystem: $result"
    }
    APSWaitWithUpdate -waitSeconds 2
}

#Suspend or Resume Run Controls
proc APSMpLSuspendResumeRunControl {args} {
    set value ""
    set name ""
    set group ""
    set deviceList ""
    set waitSeconds 4
    set port ""
    set executable ""
    APSStrictParseArguments {value name group deviceList waitSeconds port executable}
    if {($value != "Resume") && ($value != "Suspend")} {
	return -code error "APSMpLSuspendResumeRunControl: value must be Resume or Suspend"
    }
    if {(![llength $name]) || (![llength $group])} {
	return -code error "APSMpLSuspendResumeRunControl: invalid arguments passed"
    }
    if {[catch {APSDevSend \
                  -group $group \
                  -operation ${value}${name} \
                  -deviceList $deviceList} result]} {
	return -code error "APSMpLSuspendResumeRunControl: $result"
    }

    if {$value == "Resume"} {
	APSWaitWithUpdate -waitSeconds $waitSeconds

	if {[catch {APSDevSend \
                      -group $group \
                      -operation Query${name}Running \
                      -deviceList $deviceList} result]} {
	    return -code error "APSMpLSuspendResumeRunControl: $result"
	}
	if {$result != 1} {
	    if {[llength $port] == 1} {		
		if {![catch {socket localhost $port} sid]} {
		    APSWaitWithUpdate -waitSeconds [expr {3 + $waitSeconds}]
		    if {[catch {APSDevSend \
                                  -group $group \
                                  -operation Query${name}Running \
                                  -deviceList $deviceList} result]} {
			return -code error "APSMpLSuspendResumeRunControl: $result"
		    }
		    if {$result == 1} {
			return -code ok
		    }
		}
	    }
	    if {[llength $executable]} {
		if {![catch {eval exec $executable &} result]} {		    
		    APSWaitWithUpdate -waitSeconds [expr {3 + $waitSeconds}]
		    if {[catch {APSDevSend \
                                  -group $group \
                                  -operation Query${name}Running \
                                  -deviceList $deviceList} result]} {
			return -code error "APSMpLSuspendResumeRunControl: $result"
		    }
		    if {$result == 1} {
			return -code ok
		    }
		}
	    }
	    bell
            if {[APSPEMTKDialog .warningDialog -text "Unable to automatically resume runcontrol ${name}."] == 1} {
		return -code error "APSMpLSuspendResumeRunControl: Operation aborted by user"
	    }
	}
    }
}

#Verify that the macropulse repetition rate is RFG 10 Hz or less 
proc APSRFGUN_Macropulse {args} {
    set i 1
    while {$i} {
	set i 0
	if {[catch {APSDevSend \
                      -group LinacTiming \
                      -operation ReadBeamTriggerRate \
                      -deviceList 0} result]} {
	    return -code error "APSRFGUN_Macropulse: $result"
	}
	if {($result != {{RFG 10Hz}}) && ($result != "--10Hz--") && ($result != "--6Hz--") && ($result != "--4Hz--") && ($result != "--2Hz--")} {
	    set i 1
            if {[APSPEMTKDialog .warningDialog -text "Macropulse repetition rate is not <= 10Hz. Lower rate and click Continue when finished"] == 1} {
		return -code error "APSRFGUN_Macropulse: Macropulse repetition rate is not <= 10Hz"
	    }
	}
    }
    update
}

#Verify that the Gun's cathode heater power is 12W +- .2W
#Do not proceed until this condition is met.
proc APSRFGUN_CathodeHeaterPower {args} {
    set deviceList ""
    set wattsMin 11.8
    set watts 12.0
    set wattsMax 12.5
    APSStrictParseArguments {deviceList wattsMin watts wattsMax}

    if {[catch {APSDevSend \
                  -group LinacRFGun \
                  -operation ReadCathodeHeaterPower \
                  -deviceList $deviceList} result]} {
	return -code error "APSRFGUN_CathodeHeaterPower: $result"
    }
    #    set previous $result

    if {($result < $wattsMin) || ($result > $wattsMax)} {
	set i 1
	while {$i} {
	    set i 0
	    set timeLimit 380
	    set time 0
	    while {$time < $timeLimit} {
		after 1000
		update
		if {[catch {APSDevSend \
                              -group LinacRFGun \
                              -operation ReadCathodeHeaterPower \
                              -deviceList $deviceList} result]} {
		    return -code error "APSRFGUN_CathodeHeaterPower: $result"
		}
		if {($result > $wattsMin) && ($result < $wattsMax)} {
		    break
		}
		#		set change [expr $result - $previous]
		#		if {$change == 0} { set change .001 }
		#		set estimatedTime [expr ($wattsMin - $result) / $change]
		#		set previous $result
		#		APSSetVarAndUpdate status "$estimatedTime seconds left"
		incr time
	    }
	    if {$time >= $timeLimit} {
		set i 1
                set answer [APSPEMTKDialog .warningDialog -strings {Continue Ignore "Abort Procedure"} -text "Timed out waiting to reach $wattsMin Watts in the cathode heater"]
                if {$answer == 2} {
		    return -code error "APSRFGUN_CathodeHeaterPower: Timed out waiting to reach $wattsMin Watts"
		}
                if {$answer == 1} {
                    break
                }
	    }
	}
    }
    update
}

proc APSMpLWaitForMinimumValue {args} {
    set deviceList ""
    set group ""
    set operation ""
    set minValue ""
    set intervalLimit 60
    set intervalTime 1
    APSStrictParseArguments {deviceList group operation minValue intervalLimit intervalTime}
    if {[llength deviceList] != 1} {return -code error "APSMpLWaitForMinimumValue: Only one device allowed"}
    if {[catch {APSDevSend \
                  -group $group \
                  -operation $operation \
                  -deviceList $deviceList} result]} {
	return -code error "APSMpLWaitForMinimumValue: $result"
    }

    if {$result < $minValue} {
	set i 1
	while {$i} {
	    set i 0
	    set time 0
	    while {$time < $intervalLimit} {
		APSWaitWithUpdate -waitSeconds $intervalTime
		if {[catch {APSDevSend \
                              -group $group \
                              -operation $operation \
                              -deviceList $deviceList} result]} {
		    return -code error "APSMpLWaitForMinimumValue: $result"
		}
		if {$result > $minValue} {
		    break
		}
		incr time
	    }
	    if {$time >= $intervalLimit} {
		set i 1
		set answer [APSPEMTKDialog .warningDialog -strings {Continue Ignore "Abort Procedure"} -text "Timed out waiting for L${deviceList} $operation to reach $minValue"]
                if {$answer == 2} {
		    return -code error "APSMpLWaitForMinimumValue: Timed out waiting for $deviceList $operation to reach $minValue"
		}
                if {$answer == 1} {
                    break
                }
	    }
	}
    }
    update
}

proc APSLINAC_LLRFOnOff {args} {
    set button ""
    set deviceList ""
    APSStrictParseArguments {button deviceList}
    if {($button != "On") && ($button != "Off")} {
	return -code error "APSLINAC_LLRFOnOff: Invalid button"
    }
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation QueryLLRFOn \
                  -deviceList $deviceList} results]} {
	return -code error "APSLINAC_LLRFOnOff: $results"
    }
    foreach result $results sector $deviceList {
	if {($button == "On") && (!$result)} {
            

	    if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation TurnOnLLRF \
                          -deviceList $sector} result]} {
		return -code error "APSLINAC_LLRFOnOff: $result"
	    }
	}
	
	if {($button == "Off") && ($result)} {
	    if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation TurnOffLLRF \
                          -deviceList $sector} result]} {
		return -code error "APSLINAC_LLRFOnOff: $result"
	    }
	}
    }
    APSWaitWithUpdate -waitSeconds 4
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation QueryLLRFOn \
                  -deviceList $deviceList} results]} {
	return -code error "APSLINAC_LLRFOnOff: $results"
    }
    foreach result $results sector $deviceList {
	if {($button == "On") && (!$result)} {
            if {[APSPEMTKDialog .warningDialog -text "LLRF in sector $sector is not on."] == 1} {
		return -code error "APSLINAC_LLRFOnOff: RF is not on"
	    }
	}
	if {($button == "Off") && ($result)} {
            if {[APSPEMTKDialog .warningDialog -text "LLRF in sector $sector is not off."] == 1} {
		return -code error "APSLINAC_LLRFOnOff: RF is not off"
	    }
	}
    }
    update
}

proc APSLINAC_CheckModulatorCurrents {args} {
    set deviceList ""
    set minValueList ""
    APSStrictParseArguments {deviceList minValueList}
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation SetPFNVoltage \
                  -deviceList $deviceList \
                  -forceRead 1} results]} {
	return -code error "APSLINAC_CheckModulatorCurrents: $results"
    }
    foreach result $results sector $deviceList minValue $minValueList {
	if {$result < $minValue} {
	    bell
            if {[APSPEMTKDialog .warningDialog -text "PFN voltage set point in modulator $sector is below $minValue KV."] == 1} {
		return -code error "APSLINAC_CheckModulatorCurrents: PFN voltage set point in modulator $sector is below $minValue KV"
	    }
	}
    }
}

proc APSLINAC_SetKlystronForwardPower {args} {
    set deviceList ""
    set KLYFwdPwr 13000000
    APSStrictParseArguments {deviceList KLYFwdPwr}
    
    #This is only called for devices 1 and 3

    set oldDeviceList ""
    set newDeviceList ""
    foreach device $deviceList {
        if {$device == 2} {
            lappend newDeviceList $device
        } else {
            lappend oldDeviceList $device
        }
    }
    foreach device $oldDeviceList {
        if {[catch {APScavget -list=L${device}:MO:LowPFNvSP} PFNLowTripValue]} {
            set PFNLowTripValue 22
        }
        if {[catch {APSLINAC_CheckModulatorCurrents -deviceList $device -minValueList $PFNLowTripValue} result]} {
            return -code error "APSLINAC_SetKlystronForwardPower: $result"
        }
    }
    if {[llength $oldDeviceList]} {
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryReadyToPulseOn \
                      -deviceList $deviceList} results]} {
            return -code error "APSLINAC_SetKlystronForwardPower: $result"
        }
        foreach result $results device $deviceList {
            if {$result != 1} {
                if {[APSPEMTKDialog .warningDialog -text "Not ready to pulse in sector L$device."] == 1} {
                    return -code error "APSLINAC_SetKlystronForwardPower: Not ready to pulse in sector L$device."
                }
            }
        }
    }
    if {[llength $newDeviceList]} {
        foreach device $newDeviceList {
            if {[catch {APSPEMCheckPVs -pvList L-K${device}:Mod:State-RB \
                          -desiredList 13 \
                          -greaterThanOrEqualTo 1 \
                          -allowContinue 0 \
                          -allowRecheck 0 \
                          -message "K${device} K400 State found to be less than 13, unable to continue."} k400state]} {
                return -code error $k400state
            }
        }
    }
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation SetForwardPowerSetpoint \
                  -deviceList $deviceList \
                  -value $KLYFwdPwr} result]} {
	return -code error "APSLINAC_SetKlystronForwardPower: $result"
    }
    update
}


proc RestartLinacRFPhaseControllaw {args} {
    set SCRFile ""
    APSStrictParseArguments {SCRFile}

    if {[catch {APSLinkToLINACPVs} result]} {
	APSMpReturn error "RestartLinacRFPhaseControllaw: $result"
    }
    if {[catch {APSRFGUN_DetectSelectedGun} gun]} {
	APSMpReturn error "Unable to detect selected gun: $gun"
    }
    if {[catch {APSDevSend \
                  -group LinacRFGun \
                  -operation ReadRFCurrentMode \
                  -deviceList 0} linacMode]} {
	APSMpReturn error "Unable to detect linac mode: $linacMode"
    }
    set linacMode [join $linacMode]

    if {[catch {exec sddsselect $SCRFile /home/helios/oagData/pem/linac/filterFile -match=ControlName -pipe=out | sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
	APSMpReturn error "RestartLinacRFPhaseControllaw: Invalid SCR file"
    }
    foreach {controlName valueString} $results {
	if {"L:BPD:L1P1:RFGUN1:SetpointAO" == $controlName} {
	    set rg1phasesetpoint $valueString
	} elseif {"L:BPD:L1P1:RFGUN2:SetpointAO" == $controlName} {
	    set rg2phasesetpoint $valueString
	} elseif {"L:BPD:L1P1:L2AS1:SetpointAO" == $controlName} {
	    set l2phasesetpoint $valueString
	} elseif {"L:BPD:L3P3:L4AS1:SetpointAO" == $controlName} {
	    set l4phasesetpoint $valueString
	} elseif {"L:BPD:L3P3:L4AS1:SetpointAO" == $controlName} {
	    set l5phasesetpoint $valueString
	}
    }


    APSMpStep "Abort linac RF phase controllaw"
    if {[catch {exec cavput -list=L:BPD:RFGUN1:L1L2L4L5RC.ABRT=1,L:BPD:RFGUN2:L1L2L4L5RC.ABRT=1,L:BPD:RFGUN1RC.ABRT=1,L:BPD:RFGUN2RC.ABRT=1,L:BPD:RFGUN2K1DnRC.ABRT=1,L:BPD:RFGUN2K2DnRC.ABRT=1,L:BPD:L3P3:L4AS1RC.ABRT=1,L:BPD:L4P1:L5AS1RC.ABRT=1} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem aborting the linac RF phase controllaw: $result"] == 1} {
            APSMpReturn error "Problem aborting the linac RF phase controllaw: $result"
        }
    }
    APSMpStep "Relink RF phase controllaw input files"
    if {$linacMode == "K1 Down"} {
        if {[catch {
            exec ln -fs /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5/linacBeamRfPhase-L1RFGun1-L2-L4-L5_K1Dn.def \
              /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5/linacBeamRfPhase-L1RFGun1-L2-L4-L5.def
            exec ln -fs /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5/linacBeamRfPhase-L1RFGun2-L2-L4-L5_K1Dn.def \
              /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5/linacBeamRfPhase-L1RFGun2-L2-L4-L5.def
            exec ln -fs /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5/linacBeamRfPhase-L1RFGun1-L2-L4-L5_K1Dn.tests \
              /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5/linacBeamRfPhase-L1RFGun1-L2-L4-L5.tests
            exec ln -fs /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5/linacBeamRfPhase-L1RFGun2-L2-L4-L5_K1Dn.tests \
              /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5/linacBeamRfPhase-L1RFGun2-L2-L4-L5.tests
        } result]} {
            if {[APSPEMTKDialog .warningDialog -text "Unable to relink RF phase controllaw input file for K1 down mode: $result"] == 1} {
                APSMpReturn error "Unable to relink RF phase controllaw input file for K1 down mode: $result"
            }
        }
    } elseif {$linacMode == "K2 Down"} {
        if {[catch {
            exec ln -fs /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5/linacBeamRfPhase-L1RFGun1-L2-L4-L5_K2Dn.def \
              /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5/linacBeamRfPhase-L1RFGun1-L2-L4-L5.def
            exec ln -fs /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5/linacBeamRfPhase-L1RFGun2-L2-L4-L5_K2Dn.def \
              /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5/linacBeamRfPhase-L1RFGun2-L2-L4-L5.def
            exec ln -fs /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5/linacBeamRfPhase-L1RFGun1-L2-L4-L5_K2Dn.tests \
              /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5/linacBeamRfPhase-L1RFGun1-L2-L4-L5.tests
            exec ln -fs /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5/linacBeamRfPhase-L1RFGun2-L2-L4-L5_K2Dn.tests \
              /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5/linacBeamRfPhase-L1RFGun2-L2-L4-L5.tests
        } result]} {
            if {[APSPEMTKDialog .warningDialog -text "Unable to relink RF phase controllaw input file for K2 down mode: $result"] == 1} {
                APSMpReturn error "Unable to relink RF phase controllaw input file for K2 down mode: $result"
            }
        }
    } else {
        if {[catch {
            exec ln -fs /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5/linacBeamRfPhase-L1RFGun1-L2-L4-L5_K3Dn.def \
              /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5/linacBeamRfPhase-L1RFGun1-L2-L4-L5.def
            exec ln -fs /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5/linacBeamRfPhase-L1RFGun2-L2-L4-L5_K3Dn.def \
              /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5/linacBeamRfPhase-L1RFGun2-L2-L4-L5.def
            exec ln -fs /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5/linacBeamRfPhase-L1RFGun1-L2-L4-L5_K3Dn.tests \
              /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5/linacBeamRfPhase-L1RFGun1-L2-L4-L5.tests
            exec ln -fs /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5/linacBeamRfPhase-L1RFGun2-L2-L4-L5_K3Dn.tests \
              /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5/linacBeamRfPhase-L1RFGun2-L2-L4-L5.tests
        } result]} {
            if {[APSPEMTKDialog .warningDialog -text "Unable to relink RF phase controllaw input file for K3 down mode: $result"] == 1} {
                APSMpReturn error "Unable to relink RF phase controllaw input file for K3 down mode: $result"
            }
        }
    }

    APSMpStep "Set Linac Phase Control Points from SCR File" -desc "Set Linac Phase Control Points from SCR File"
    if {[info exists rg1phasesetpoint]} {
        if {[catch {APScavput -list=L:BPD:L1P1:RFGUN1:SetpointAO=$rg1phasesetpoint} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured while setting linac phase control points: $result"] == 1} {
                APSMpReturn error "RestartLinacRFPhaseControllaw: $result"
            }
        }
    }
    if {[info exists rg2phasesetpoint]} {
        if {[catch {APScavput -list=L:BPD:L1P1:RFGUN2:SetpointAO=$rg2phasesetpoint} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured while setting linac phase control points: $result"] == 1} {
                APSMpReturn error "RestartLinacRFPhaseControllaw: $result"
            }
        }
    }
    if {[info exists l2phasesetpoint]} {
        if {[catch {APScavput -list=L:BPD:L1P1:L2AS1:SetpointAO=$l2phasesetpoint} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured while setting linac phase control points: $result"] == 1} {
                APSMpReturn error "RestartLinacRFPhaseControllaw: $result"
            }
        }
    }
    if {[info exists l4phasesetpoint]} {
        if {[catch {APScavput -list=L:BPD:L3P3:L4AS1:SetpointAO=$l4phasesetpoint} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured while setting linac phase control points: $result"] == 1} {
                APSMpReturn error "RestartLinacRFPhaseControllaw: $result"
            }
        }
    }
    if {[info exists l5phasesetpoint]} {
        if {[catch {APScavput -list=L:BPD:L4P1:L5AS1:SetpointAO=$l5phasesetpoint} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured while setting linac phase control points: $result"] == 1} {
                APSMpReturn error "RestartLinacRFPhaseControllaw: $result"
            }
        }
    }

    if {$gun == "RG1"} {
        if {[catch {exec cavput -list=L:BPD:RFGUN1:L1L2L4L5RC.SUSP=0} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem connecting to RF phase controllaw run control: $result"] == 1} {
                APSMpReturn error "Problem connecting to RF phase controllaw run control: $result"
            }
        }
        after 3000
        exec cavput -list=L:BPD:RFGUN1:L1L2L4L5RC.CLR=1
        set dir [pwd]
        cd /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun1_L2_L4_L5
        if {[catch {exec ./linacBeamRfPhase-L1RFGun1-L2-L4-L5Options -rcPV L:BPD:RFGUN1:L1L2L4L5RC} options]} {
            APSMpReturn error "Unable to start linac RF phase controllaw: $options"
        }
        if {[catch {eval exec sddscontrollaw $options >& /dev/null &} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Unable to start linac RF phase controllaw: $result"] == 1} {
                APSMpReturn error "Unable to start linac RF phase controllaw: $result"
            }
        }
        cd $dir
    } else {
        if {[catch {exec cavput -list=L:BPD:RFGUN2:L1L2L4L5RC.SUSP=0} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem connecting to RF phase controllaw run control: $result"] == 1} {
                APSMpReturn error "Problem connecting to RF phase controllaw run control: $result"
            }
        }
        after 3000
        exec cavput -list=L:BPD:RFGUN2:L1L2L4L5RC.CLR=1
        set dir [pwd]
        cd /home/helios/oagData/controllaw/linacBeamRfPhase/L1RFGun2_L2_L4_L5
        if {[catch {exec ./linacBeamRfPhase-L1RFGun2-L2-L4-L5Options -rcPV L:BPD:RFGUN2:L1L2L4L5RC} options]} {
            APSMpReturn error "Unable to start linac RF phase controllaw: $options"
        }
        if {[catch {eval exec sddscontrollaw $options >& /dev/null &} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Unable to start linac RF phase controllaw: $result"] == 1} {
                APSMpReturn error "Unable to start linac RF phase controllaw: $result"
            }
        }
        cd $dir
    }
    APSMpReturn ok
}
