
proc PCGUN_ChangeTimingInfo {} {
    return "PCGUN Change Timing Procedure\n\
\n\
This procedure is called by:\n\
PCGUN_StartupWithPS\n\
\n\
This procedure does the following:\n\
1. Changes the beam trigger timing to 2Hz.\n\
2. Changes the timing on the linac injection sequence screen.\n\
3. Changes the beam trigger timing to 6Hz.\n\
4. Sets laser trigger to LINAC Beam.\n\
5. Sets timing source to LI Beam Rate.\n\
6. Depresses the \"Set Timing for PC-Gun\" button.\n\
7. Depresses the \"PC-Gun\" Trig On button."
}

proc PCGUN_ChangeTimingDialog {frame} {
    APSSetVarAndUpdate status "Click OK to set timing for PC-Gun"
    pack [message $frame.msg -aspect 300 -justify left \
	    -text "Click OK to set timing for PC-Gun"]
    return
}

proc PCGUN_ChangeTiming {args} {
    global execMode

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

    APSMpStep init -promptDialog PCGUN_ChangeTimingDialog

    if [catch {APSLinkToLINACPVs} result] {
	APSMpReturn error "PCGUN_ChangeTiming: $result"
    }
    #1
#    APSMpStep "${prefix}Change the Beam Trigger Timing to 2Hz on the Linac Injection Sequence Screen" -desc "Change the beam trigger timing to 2Hz on the linac injection sequence screen"
#    if [catch {APSLINAC_SetBeamTriggerRate -state "--2Hz--"} result] {
#        if {[APSPEMTKDialog .warningDialog -text "Unable to change the beam trigger timing to 2Hz on the linac injection sequence screen\n$result"] == 1} {
#            APSMpReturn error "PCGUN_ChangeTiming: $result"
#        }
#    }
    #2    
    APSMpStep "${prefix}Change the Timing Reference Source to Linac RF" \
      -desc "Change the Timing Reference Source to Linac RF"
    if [catch {APSLINAC_SetInjectionTimingTrigger -state Linac} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to change the Timing Reference Source to Linac RF\n$result"] == 1} {
            APSMpReturn error "PCGUN_ChangeTiming: $result"
        }
	#	APSMpReturn error "PCGUN_ChangeTiming: $result"
    }
    #3
#    APSMpStep "${prefix}Change the Beam Trigger Timing to 6Hz on the Linac Injection Sequence Screen" -desc "Change the beam trigger timing to 6Hz on the linac injection sequence screen"
#    if [catch {APSLINAC_SetBeamTriggerRate -state "--6Hz--"} result] {
#        if {[APSPEMTKDialog .warningDialog -text "Unable to change the beam trigger timing to 6Hz on the linac injection sequence screen\n$result"] == 1} {
#            APSMpReturn error "PCGUN_ChangeTiming: $result"
#        }
#    }
    #4
    APSMpStep "${prefix}Set Laser trigger to LINAC Beam" \
      -desc "Set laser trigger to LINAC Beam"
    if [catch {APSPCGUN_SetLaserTrigger -state "LinacBeam"} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to set laser trigger to LINAC Beam\n$result"] == 1} {
            APSMpReturn error "PCGUN_ChangeTiming: $result"
        }
	#	APSMpReturn error "PCGUN_ChangeTiming: $result"
    }

    APSMpStep "${prefix}Set timing source to LI Beam Rate" \
      -desc "Set timing source to LI Beam Rate"
    if [catch {APSLINAC_SetTimingSource -state "LIBeamPG1" -deviceList 3} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to set timing source to LI Beam Rate\n$result"] == 1} {
            APSMpReturn error "PCGUN_ChangeTiming: $result"
        }
	#	APSMpReturn error "PCGUN_ChangeTiming: $result"
    }

    APSWaitWithUpdate -waitSeconds 2 
    #5
    APSMpStep "${prefix}Depress the \"Set Timing for PC-Gun\" button" \
      -desc "Depress the \"Set Timing for PC-Gun\" button"
    if [catch {APSPCGUN_SetTimingForPCGun} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to set timing for PC-Gun\n$result"] == 1} {
            APSMpReturn error "PCGUN_ChangeTiming: $result"
        }
	#	APSMpReturn error "PCGUN_ChangeTiming: $result"	
    }
    #6
    APSMpStep "${prefix}Depress the \"PC-Gun\" Trig On button on the timingSetup screen" \
      -desc "Depress the \"PC-Gun\" Trig On button on the timingSetup screen"
    if [catch {APSPCGUN_SetPCGunTriggerOnOff -state on} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable turn on the PC-Gun Trigger\n$result"] == 1} {
            APSMpReturn error "PCGUN_ChangeTiming: $result"
        }
	#	APSMpReturn error "PCGUN_ChangeTiming: $result"	
    }
    APSMpReturn ok
}

proc PCGUN_StartupWithPSInfo {} {
    return "This procedure calls PCGUN_Startup and APSMpLStartUpPS.\n\n\
This procedure will shutdown the RFGUN,\n\
startup the PCGUN, and condition the\n\
needed power supplies in the linac.\n\
You may also want to run the\n\
LEUTL_SetupForUndulatorHallStudies procedure\n\
to condition the power supplies beyond the linac."
}

proc PCGUN_StartupWithPS {args} {
    set turnOnList [list L1:PC1 L1:RG1:LFA:TRM L1:RG2:LFA:TRM L1:SC L1:H L1:V L1:Q L2:SC L2:QM L3:CHICANE L3:MATCHING L3:AM1T L4:SC L4:QM L5:SC L5:QM L5:AM] 
    set conditionList [list L1:PC1 L1:RG1:LFA:TRM L1:RG2:LFA:TRM L1:SC L1:H L1:V L1:Q L2:SC L2:QM L3:CHICANE L3:MATCHING L3:AM1T L4:SC L4:QM L5:SC L5:QM L5:AM]
    set SCRFile ""
    set sectors "L1 L2 L3 L4 L5"
    set PCGUN 1
    set PowerSupplies 1
    set cycles 4
    foreach sector $sectors {
	set $sector 1
    }

    APSStrictParseArguments {turnOnList conditionList SCRFile PCGUN PowerSupplies L1 L2 L3 L4 L5 cycles}
    global APSMpLControlPS execMode

    if {$execMode == "Manual"} {
	set prefix "Press Continue to "
    } else {
	set prefix ""
    }
    
    if {[catch {APSLinkToLINACPVs} result]} {
	APSMpReturn error "PCGUN_StartupWithPS $result"
    }
    set tld [APSMpLConvertDeviceNames -operation TurnOn -deviceList $turnOnList]
#    lappend tld L1:PG1:SC2:VL L1:PG1:SC2:HZ
#    lappend turnOnList L1:PG1:SC
    set cld [APSMpLConvertDeviceNames -operation StartConditioning -deviceList $conditionList]
#    lappend cld L1:PG1:SC2:VL L1:PG1:SC2:HZ
#    lappend conditionList L1:PG1:SC
    
    set arrayName APSMpLControlPS
    APSLGenericPSArraySetup -arrayName $arrayName \
      -turnOnList $turnOnList \
      -turnOnListDetailed $tld \
      -conditionList $conditionList \
      -conditionListDetailed $tld \
      -SCRFile $SCRFile \
      -cycles $cycles
    


    APSMpStep init -promptDialog \
      "APSLGenericPSDialog -packProc PCGUN_StartupWithPSPackProc -turnOn 1 -condition 1 -chooseSCR 1 -arrayName $arrayName -frame " -vars {L1 L2 L3 L4 L5 PCGUN PowerSupplies}

    set SCRFile $APSMpLControlPS(Filename)
    set turnOnList [APSLGenericPSArrayQuery -arrayName $arrayName -operation TurnOn]
    set turnOnListDetailed [APSMpLConvertDeviceNames -operation TurnOn -deviceList $turnOnList]
    set turnOnListDetailed [APSMpLConvertDetailedDeviceNames -operation TurnOn -deviceList $turnOnListDetailed -arrayName $arrayName]
    set conditionList [APSLGenericPSArrayQuery -arrayName $arrayName -operation StartConditioning]
    set conditionListDetailed [APSMpLConvertDeviceNames -operation StartConditioning -deviceList $conditionList]
    set conditionListDetailed [APSMpLConvertDetailedDeviceNames -operation StartConditioning -deviceList $conditionListDetailed -arrayName $arrayName]

    set cycles [set ${arrayName}(StartConditioningInfo,cycles)]

    set paramString ""
    foreach param {L1 L2 L3 L4 L5 turnOnList conditionList SCRFile PCGUN PowerSupplies} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure PCGUN_StartupWithPS -action initialize -state ok -parameters $paramString}

    if {[catch {exec sddsselect $SCRFile /home/helios/oagData/pem/linac/filterFile -match=ControlName -pipe=out | sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
	APSMpReturn error "PCGUN_StartupWithPS: Invalid SCR file"
    }
    set RFSwitchMode ""
    set SelectedGun ""
    foreach {controlName valueString} $results {
	if {$controlName == "LRFSCS:modeM"} {
            set RFSwitchMode $valueString
        } elseif {$controlName == "LRFSCS:gunM"} {
            set SelectedGun $valueString
        }
    }
    if {[catch {APSDevSend \
		  -group LinacRFGun \
		  -operation ReadRFCurrentMode \
		  -deviceList 0} linacMode]} {
	return -code error "PCGUN_StartupWithPS: $linacMode"
    }
    set RFSwitchMode [join $RFSwitchMode]
    set SelectedGun [join $SelectedGun]
    set linacMode [join $linacMode]
    if {$RFSwitchMode != $linacMode} {
        if {[APSPEMTKDialog .warningDialog -text "The Linac RF Switching mode is different from that in the SCR file.\n${SCRFile}\n(SCR file: ${RFSwitchMode})\n(Current value: ${linacMode})"] == 1} {
            APSMpReturn error "PCGUN_StartupWithPS: The Linac RF Switching mode is different from that in the SCR file."
        }
    }
    if {$SelectedGun != "PG 1"} {
        if {[APSPEMTKDialog .warningDialog -text "The PC Gun is not the selected gun in the SCR file.\n${SCRFile}\n(SCR file: ${SelectedGun})"] == 1} {
            APSMpReturn error "PCGUN_StartupWithPS: The Linac Gun is different from that in the SCR file."
        }
    }
    
    if {$PCGUN} {
        APSMpStep "${prefix}Start up PCGUN" -desc "Start up PCGUN" -proc PCGUN_Startup
        set id2 [APSMpParallel \
		   -procedure "PCGUN_Startup -SCRFile $SCRFile -L1 $L1 -L2 $L2 -L3 $L3 -L4 $L4 -L5 $L5" \
		   -mode "Automatic"]
    }

    if {$PowerSupplies} {
        if {$PCGUN} {
            #WAIT 50 seconds before conditioning PS. This is to give L1:PC1:BM1:PS and L1:PC1:GV2 enough time to do their thing in the PCGUN section
            APSWaitWithUpdate -waitSeconds 50
        }
        APSMpStep "${prefix}Start up power supplies" -desc "Start up power supplies" -proc APSMpLStartUpPS
        set id1 [APSMpParallel \
		   -procedure "APSMpLStartUpPS -turnOnList \"$turnOnList\" -conditionList \"$conditionList\" -turnOnListDetailed \"$turnOnListDetailed\" -conditionListDetailed \"$conditionListDetailed\" -SCRFile $SCRFile -cycles $cycles" \
		   -mode "Automatic"]
    }
    #    APSMpAbort all -onError 1
    if {$PowerSupplies} {
        if [catch {APSMpJoin $id1} results] {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured in power supply startup\nPCGUN_StartupWithPS: $results"] == 1} {
                APSMpReturn error "PCGUN_StartupWithPS: $results"
            }
        }
    }
    if {$PCGUN} {
        if [catch {APSMpJoin $id2} results] {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured in pcgun startup\nPCGUN_StartupWithPS: $results"] == 1} {
                APSMpReturn error "PCGUN_StartupWithPS: $results"
            }
	    #            APSMpReturn error "PCGUN_StartupWithPS: $results"
        }
    }
    if [catch {APSDevSend -releaseLinks 1 \
                 -group LinacPS \
                 -operation TurnOn \
                 -deviceList "L1:RG2:LFA:TRM"} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to turn on L1:RG2:LFA:TRM\nPCGUN_StartupWithPS: $result"] == 1} {
            APSMpReturn error "PCGUN_StartupWithPS: $result"
        }
    }
    if [catch {APSDevSend -releaseLinks 1 \
                 -group LinacPS \
                 -operation SetCurrent \
                 -valueList ".2" \
                 -deviceList "L1:RG2:LFA:TRM" \
                 -timeout 0} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to set the current for L1:RG2:LFA:TRM\nPCGUN_StartupWithPS: $result"] == 1} {
            APSMpReturn error "PCGUN_StartupWithPS: $result"
        }
    }
    APSMpReturn ok
}

proc PCGUN_StartupWithPSPackProc {frame} {
    pack [frame $frame.top]
    APSCheckButtonFrame .selectSystems \
      -parent $frame.top -label "Select Systems to Startup" \
      -variableList {PCGUN_StartupWithPS(PCGUN) PCGUN_StartupWithPS(PowerSupplies)} \
      -buttonList {"PCGUN" "Power Supplies"} \
      -allNone 1 \
      -packOption {-side top} \
      -orientation vertical
    APSCheckButtonFrame .selectSectors \
      -parent $frame.top -label "Select Modulators To Use" \
      -variableList {PCGUN_StartupWithPS(L1) PCGUN_StartupWithPS(L2) PCGUN_StartupWithPS(L3) PCGUN_StartupWithPS(L4) PCGUN_StartupWithPS(L5)} \
      -buttonList {K1 K2 K3 K4 K5} \
      -allNone 1 \
      -packOption {-side top} \
      -orientation horizontal
}

proc PCGUN_StartupInfo {} {
    return "PCGUN Startup Procedure\n\
This procedure does the following:\n\
1. Runs the RFGUN_Shutdown PEM.\n\
2. Set the timing for the \"PC-GUN\".\n\
3. Adjust the L1 Kly Drive to 15 Mega Watts of forward power."
}

proc PCGUN_StartupDialog {frame} {
    pack [frame $frame.top]
    APSCheckButtonFrame .selectSectors \
      -parent $frame.top -label "Select Modulators To Use" \
      -variableList {PCGUN_Startup(L1) PCGUN_Startup(L2) PCGUN_Startup(L3) PCGUN_Startup(L4) PCGUN_Startup(L5)} \
      -buttonList {K1 K2 K3 K4 K5} \
      -allNone 1 \
      -packOption {-side top} \
      -orientation horizontal
}

proc PCGUN_Startup {args} {
    set SCRFile ""
    set sectors "L1 L2 L3 L4 L5"
    foreach sector $sectors {
	set $sector 1
	set ${sector}PFN 0
    }
    APSStrictParseArguments {L1 L2 L3 L4 L5 SCRFile}


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

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

    if {[catch {APSDevSend \
                  -group LinacRFGun \
                  -operation ReadRFCurrentMode \
                  -deviceList 0} linacMode]} {
	APSMpReturn error "LPL_Startup: $linacMode"
    }
    set linacMode [join $linacMode]

    set arrayName APSMpLControlPS
    APSLGenericPSArraySetup -arrayName $arrayName -SCRFile $SCRFile
    
    if {(![file exists $SCRFile]) && ($execMode == "Automatic")} {
	set execMode "Semi-Automatic"
    }
    APSMpStep init -promptDialog \
      "APSLGenericPSDialog -packProc PCGUN_StartupDialog -chooseSCR 1 -arrayName $arrayName -frame " -vars {L1 L2 L3 L4 L5}
    
    set SCRFile $APSMpLControlPS(Filename)

    if [catch {exec sddsselect $SCRFile /home/helios/oagData/pem/linac/filterFile -match=ControlName -pipe=out | sdds2stream -column=ControlName,ValueString -pipe=in} results] {
	APSMpReturn error "PCGUN_Startup: Invalid SCR file"
    }
    set gateStartTime 0
    set gateWidth 0
    foreach {controlName valueString} $results {
        if {[string range $controlName end-3 end] == ".VAL"} {
            set controlName [string range $controlName 0 end-4]
        }
	if {[regexp -- L\[1-5\]:MO:PFNvAO $controlName]} {
	    set L[string index $controlName 1]PFN $valueString
	} elseif {"L1:KY:DC2ARF" == $controlName} {
	    set L1AttnSetPoint $valueString
	    set L1AttnVar "L1:KY:DC2ARF:SetpointP"
	} elseif {"L3:KY:DC2ARF" == $controlName} {
	    set L3AttnSetPoint $valueString
	    set L3AttnVar "L3:KY:DC2ARF:SetpointP"
	} elseif {"L2:SD:DC1ARF" == $controlName} {
	    set L2AttnSetPoint $valueString
	    set L2AttnVar "L2:SD:DC1ARF:SetpointP"
	} elseif {"L-K2:LLRF:SD:Fwd_PkPwrRemoteM" == $controlName} {
	    set L2AttnSetPoint $valueString
	    set L2AttnVar "L2:SD:DC1ARF:SetpointP"
	} elseif {"L4:SD:DC1ARF" == $controlName} {
	    set L4AttnSetPoint $valueString
	    set L4AttnVar "L4:SD:DC1ARF:SetpointP"
	} elseif {"L5:SD:DC1ARF" == $controlName} {
	    set L5AttnSetPoint $valueString
	    set L5AttnVar "L5:SD:DC1ARF:SetpointP"
	} elseif {"L5:TM:sledTrigAO" == $controlName} {
	    set L5sledTrig $valueString
	    set L5sledTrigVar "L5:TM:sledTrigAO"
	} elseif {"L4:TM:sledTrigAO" == $controlName} {
	    set L4sledTrig $valueString
	    set L4sledTrigVar "L4:TM:sledTrigAO"
	} elseif {"L1:TM:RFG:RF:startTimeAO" == $controlName} {
	    set gateStartTime $valueString
	} elseif {"L1:TM:RFG:RF:widthAO" == $controlName} {
	    set gateWidth $valueString
	}

    }
    APSStrictParseArguments {L1PFN L2PFN L3PFN L4PFN L5PFN}

    foreach sector $sectors {
	if {[set $sector]} {
            if {$sector == "L2"} {
                continue
            }
	    if {([set ${sector}PFN] < 5) || ([set ${sector}PFN] > 50)} {
                if {[APSPEMTKDialog .warningDialog -text "Value for sector $sector PFN is [set ${sector}PFN] (not valid)\nIf you are sure this PFN value is correct\nyou may click continue"] == 1} {
		    APSMpReturn error "PCGUN_Startup: Value for sector $sector PFN is [set ${sector}PFN] (not valid)"
		}
	    } 
	    if {([info exists ${sector}AttnSetPoint] != 1) || ([info exists ${sector}AttnVar] != 1)} {
		APSMpReturn error "PCGUN_Startup: Value for sector $sector Attn set point does not exist in SCR file"
	    }
	}
    }
    foreach sector "L4 L5" {
	if {[set $sector]} {
	    if {([info exists ${sector}sledTrig] != 1) || ([info exists ${sector}sledTrigVar] != 1)} {
		APSMpReturn error "PCGUN_Startup: Value for sector $sector sled trig does not exist"
	    }
	}
    }

    catch {exec cavput -list=L1:SCOPE1:chan1EnableBO=0,L1:SCOPE1:chan2EnableBO=1,L1:SCOPE1:chan3EnableBO=1,L1:SCOPE1:chan4EnableBO=0 -num}

    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 -pend=20} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Unable to turn the kicker charge pulse off\n$result"] == 1} {
            APSMpReturn error "PCGUN_Shutdown: $result"
        }
    }

    APSMpStep "${prefix}Close RG gate valves" -desc "Close RG gate values"
    if [catch {APSRFGUN_OpenCloseGateValve \
		 -deviceList "1 2" \
		 -value Close \
		 -group LinacRFGun} result] {
        if {[APSPEMTKDialog .warningDialog -text "Gate valves failed to close"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $result"
	}
    }

    APSMpStep "${prefix}Close shutter 4" -desc "Close shutter 4"
    if [catch {APSDevSend \
		 -group LinacLaser \
		 -operation CloseLRShutter \
		 -deviceList "4"} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error while closing shutter 4 \n$result"] == 1} {
            APSMpReturn error "PCGUN_Startup: $result"
        }
    }

    APSMpStep "${prefix}Turning on L1:PC1:BM1:PS" -desc "Turning on L1:PC1:BM1:PS"
    if {[catch {exec cavput -list=L1:PC1:BM1:PS:ResetSEQ=1} results]} {
        if {[APSPEMTKDialog .warningDialog -text "Failed to turn on L1:PC1:BM1:PS \n$results"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $results"
	}
    }
    APSWaitWithUpdate -waitSeconds 5
    APSMpStep "${prefix}Setting L1:PC1:BM1:PS to 4" -desc "Setting L1:PC1:BM1:PS to 4"
    if {[catch {exec cavput -list=L1:PC1:BM1:PS:CurrentAO=4} results]} {
        if {[APSPEMTKDialog .warningDialog -text "Failed to set L1:PC1:BM1:PS to 4 \n$results"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $results"
	}
    }
    APSWaitWithUpdate -waitSeconds 15
    APSMpStep "${prefix}Resetting Misc L3 interlock" -desc "Resetting Misc L3 interlock"
    if {[catch {exec cavput -list=L3:IC1:MiscResetC=1} results]} {
        if {[APSPEMTKDialog .warningDialog -text "Failed to reset Misc L3 interlock \n$results"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $results"
	}
    }
    APSWaitWithUpdate -waitSeconds 15

    APSMpStep "${prefix}Open L1:VVC1 valves" -desc "Open L1:VVC1 valves"
    if {[catch {exec cavput -list=L1:PC1:GV1:openCmdBO=1,L1:GV1:openCmdBO=1,L1:PC1:GV2:openCmdBO=1} results]} {
        if {[APSPEMTKDialog .warningDialog -text "Failed to open L1:VVC1 \n$results"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $results"
	}
    }
    APSWaitWithUpdate -waitSeconds 10
    APSMpStep "${prefix}Resetting Misc L3 interlock" -desc "Resetting Misc L3 interlock"
    if {[catch {exec cavput -list=L3:IC1:MiscResetC=1} results]} {
        if {[APSPEMTKDialog .warningDialog -text "Failed to reset Misc L3 interlock \n$results"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $results"
	}
    }
    APSWaitWithUpdate -waitSeconds 10
  

    APSMpStep "${prefix}Run RFGun_Shutdown PEM" -desc "Run RFGUN Shutdown PEM" -proc RFGUN_Shutdown
    if [catch {RFGUN_Shutdown -L1VVC1 0} result] {
        if {[APSPEMTKDialog .warningDialog -text "Problem occured while shuting down the RFGUN\n$result"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $result"
	}
    }

    APSMpStep "${prefix}Suspend L1, L2, and L3 Power Control Stabilizer" \
      -desc "Suspend L1, L2, and L3 Power Control Stabilizer"
    if [catch {APSLSuspendResumeRFPowerControllaws -klystronList "1 2 3" -mode suspend} result] {
        if {[APSPEMTKDialog .warningDialog -text "Failed to automatically suspend L1, L2, or L3 power control law"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $result"
	}
    }

    APSMpStep "${prefix}Ramp down the L1-L3 LLRF" \
      -desc "Ramp down the L1-L3 LLRF"
    if [catch {APSLReduceKlystronOutputPower -klystronList "1 2 3"} result] {
        if {[APSPEMTKDialog .warningDialog -text "Failed to automatically ramp down L1-L3 LLRF"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $result"
	}
    }

    APSMpStep "${prefix}Select LLRF Off" -desc "Turn L1, L2, L3 LLRF off"
    if [catch {APSLINAC_LLRFOnOff -button "Off" -deviceList {1 2 3}} result] {
        if {[APSPEMTKDialog .warningDialog -text "Failed to automatically turn off L1, L2, L3 LLRF"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $result"
	}
    }

    APSMpStep "${prefix}Suspend X Linac ControlLaw" -desc "Suspend X Linac ControlLaw"
    if [catch {APSMpLSuspendResumeRunControl \
		 -value "Suspend" \
		 -name "LinacControlLaw" \
		 -group "RunControlGroup" \
		 -deviceList X} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error while suspending X Linac controllaw \n$result"] == 1} {
            APSMpReturn error "PCGUN_Startup: $result"
        }
    }
    APSMpStep "${prefix}Suspend Y Linac ControlLaw" -desc "Suspend Y Linac ControlLaw"
    if [catch {APSMpLSuspendResumeRunControl \
		 -value "Suspend" \
		 -name "LinacControlLaw" \
		 -group "RunControlGroup" \
		 -deviceList Y} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error while suspending Y Linac controllaw \n$result"] == 1} {
            APSMpReturn error "PCGUN_Startup: $result"
        }
    }
    APSMpStep "${prefix}Suspend X LTP ControlLaw" -desc "Suspend X LTP ControlLaw"
    if [catch {APSMpLSuspendResumeRunControl \
		 -value "Suspend" \
		 -name "LTPControlLaw" \
		 -group "RunControlGroup" \
		 -deviceList X} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error while suspending X LTP controllaw \n$result"] == 1} {
            APSMpReturn error "PCGUN_Startup: $result"
        }
    }
    APSMpStep "${prefix}Suspend Y LTP ControlLaw" -desc "Suspend Y LTP ControlLaw"
    if [catch {APSMpLSuspendResumeRunControl \
		 -value "Suspend" \
		 -name "LTPControlLaw" \
		 -group "RunControlGroup" \
		 -deviceList Y} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error while suspending Y LTP controllaw \n$result"] == 1} {
            APSMpReturn error "PCGUN_Startup: $result"
        }
    }

    APSMpStep "${prefix}Check vacuum pressure" -desc "Check vacuum pressure"
    if {[catch {exec cavget -list=L1:PC1:GUN:VP:01} results]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while reading L1:PC1:GUN:VP:01\n$results"] == 1} {
            APSMpReturn error "PCGUN_Startup: Error while reading L1:PC1:GUN:VP:01 $results"
        }
    }
    if {$results > 1e-9} {
        if {[APSPEMTKDialog .warningDialog -text "Vacuum pressure L1:PC1:GUN:VP:01 not within range"] == 1} {
	    APSMpReturn error "PCGUN_Startup: Vacuum pressure L1:PC1:GUN:VP:01 not within range"
	}
    }

    APSMpStep "${prefix}Close RG gate valves" -desc "Close RG gate values"
    if [catch {APSRFGUN_OpenCloseGateValve \
		 -deviceList "1 2" \
		 -value Close \
		 -group LinacRFGun} result] {
        if {[APSPEMTKDialog .warningDialog -text "Gate valves failed to close"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $result"
	}
    }

    APSWaitWithUpdate -waitSeconds 10

    APSMpStep "${prefix}Open gate valves" -desc "Open gate values"
    if [catch {APSRFGUN_OpenCloseGateValve \
		 -deviceList "L1PG1GV2 L1GV1 L1GV2" \
		 -value Open \
		 -group LinacValves} result] {
        if {[APSPEMTKDialog .warningDialog -text "Gate valves failed to open"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $result"
	}
    }

    APSMpStep "${prefix}Check vacuum pressure" -desc "Check vacuum pressure"
    if {[catch {exec cavget -list=L1:PC1:GUN:VP:01} results]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while reading L1:PC1:GUN:VP:01\n$results"] == 1} {
            APSMpReturn error "PCGUN_Startup: Error while reading L1:PC1:GUN:VP:01 $results"
        }
    }
    if {$results > 1e-9} {
        if {[APSPEMTKDialog .warningDialog -text "Vacuum pressure L1:PC1:GUN:VP:01 not within range"] == 1} {
	    APSMpReturn error "PCGUN_Startup: Vacuum pressure L1:PC1:GUN:VP:01 not within range"
	}
    }



    foreach sector "L1 L3" {
    	APSMpStep "${prefix}Bring modulator $sector down to Ready to Pulse off" -desc "Bring modulators down till Ready to Pulse is off" -proc LMOCS_ShutdownTillReadyToPulseOff
	set id$sector [APSMpParallel -procedure "LMOCS_ShutdownTillReadyToPulseOff -sector $sector -rampPFN 0" -mode Automatic]
    }
    APSMpStep "${prefix}Bring modulator L2 down to Standby mode"
    set id$sector [APSMpParallel -procedure "TurnOffK400 -klystron K2 -leaveInStandby 1" -mode Automatic]
   
    foreach sector "L1 L2 L3" {
	if [catch {APSMpJoin [set id$sector]} result] {
            if {[APSPEMTKDialog .warningDialog -text "Problem brining modulators to Ready to Pulse Off\n$result"] == 1} {
		APSMpReturn error "PCGUN_Startup: Joining LMOCS_ShutdownTillReadyToPulseOff $sector: $result"
	    }
	}
    }

    APSMpStep "${prefix}Check if L1, L2, and L3 LLRF is off" -desc "Check if L1, L2, and L3 LLRF is off"
    if [catch {APSLINAC_CheckLLRFStatus -desiredState off -deviceList "1 2 3"} result] {
        if {[APSPEMTKDialog .warningDialog -text "L1, L2, or L3 LLRF is not off"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $result"
	}
    }
    APSMpStep "${prefix}Ramp down PFN voltage" -desc "Ramp down PFN voltage"
    if {[catch {APSLRampPFNVoltage \
		  -klystronList "1 3" \
		  -rampTo 0.0 \
		  -steps 1} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while ramping down PFN for L1 and L3 \n$result"] == 1} {
	    APSMpReturn error "PCGUN_Startup: $result"
        }
    }

    ##########################   
    global apsScriptHost apsScriptUser
    set oldmethod 1
    if {$apsScriptUser == "asdops"} {
	set oldmethod 0
    } elseif {($apsScriptHost == "echo") || ($apsScriptHost == "echo.aps4.anl.gov") || \
                ($apsScriptHost == "iris") || ($apsScriptHost == "iris.aps4.anl.gov") || \
                ($apsScriptHost == "cadmus") || ($apsScriptHost == "cadmus.aps4.anl.gov") || \
                ($apsScriptHost == "cyclops") || ($apsScriptHost == "cyclops.aps4.anl.gov") || \
                ($apsScriptHost == "auric")  || ($apsScriptHost == "auric.aps4.anl.gov") || \
                ($apsScriptHost == "demeter") || ($apsScriptHost == "demeter.aps4.anl.gov")} {
        set oldmethod 0
    }
    if {($linacMode == "Test Room")} {
	set oldmethod 1
    }
    if {$oldmethod} {
	APSDialogBox .waveguidedialog -name "Operator Interaction"
	destroy .waveguidedialog.buttonRow.cancel.button
	pack [label .waveguidedialog.userFrame.label -text "Wait for operator to switch water load switch"]
	bell
	while 1 {
	    APSMpStep "${prefix}Switch the S-Band RFSwitch to Water Load (LD)" \
	      -desc "Wait for operator to switch water load switch"
	    if [catch {APSPCGUN_ReadRFSwitch1 -desiredState "LD"} result] {
		APSWaitWithUpdate -waitSeconds 10
		continue
	    }
	    break
	}
	destroy .waveguidedialog
    } else {
	APSMpStep "Requesting remote switch control"
	if {[catch {APScavput -list=LRFSCS:MCR:RemoteRequest=1 -pend=20} result]} {
	    if {[APSPEMTKDialog .warningDialog -text "Problem requesting remote switching control: $result"] == 1} {
		APSMpReturn error "Problem requesting remote switching control: $result"
	    }
	}
	APSWaitWithUpdate -waitSeconds 5
	APSMpStep "Verifying remote switch control"
	if {[catch {APScavget -list=LRFSCS:MCR:RemoteEnabled -num -pend=20} result]} {
	    APSMpReturn error "Problem verifying remote switch control"
	}
	if {$result != 1} {
	    if {[APSPEMTKDialog .warningDialog -text "Problem requesting remote switching control"] == 1} {
		APSMpReturn error "Problem requesting remote switching control"
	    }
	}

	if {(($linacMode == "K1 Down") || ($linacMode == "K2 Down"))} {
	    APSMpStep "Switch To Normal mode"
	    if {[catch {APScavput -list=LRFSCS:MCR:SelectNormal=1 -pend=20} result]} {
		if {[APSPEMTKDialog .warningDialog -text "Problem changing to Normal mode: $result"] == 1} {
		    APSMpReturn error "Problem changing to Normal mode: $result"
		}
	    }
	    APSMpStep "Verifying we are now in Normal mode"
	    set tries 0
	    while {$tries <= 25} {
		APSWaitWithUpdate -waitSeconds 1
		if {[catch {APScavget -list=LRFSCS:PLC:ModeState -num -pend=20} modestate]} {
		    APSMpReturn error "Problem getting the mode state: $modestate"
		}
		if {($modestate != 3)} {
		    if {$tries == 25} {
			if {[APSPEMTKDialog .warningDialog -text "Unable to switch to Normal mode"] == 1} {
			    APSMpReturn error "Unable to switch to Normal mode"
			}
		    } else {
			incr tries
		    }
		} else {
		    break
		}
	    }
	    if {[catch {APScavget -list=LRFSCS:PLC:SwitchFault -num -pend=20} switchfault]} {
		APSMpReturn error "Problem getting the mode state: $switchfault"
	    }
	    if {($switchfault != 12)} {
		if {[APSPEMTKDialog .warningDialog -text "Switch faults seen while switching to Normal mode"] == 1} {
		    APSMpReturn error "Switch faults seen while switching to Normal mode"
		}
	    }
	} elseif {($linacMode == "K3 Down") || ($linacMode == "Normal")} {
	    APSMpStep "Switch To Normal mode"
	    if {[catch {APScavput -list=LRFSCS:MCR:SelectNormalWater=1 -pend=20} result]} {
		if {[APSPEMTKDialog .warningDialog -text "Problem changing to Normal mode: $result"] == 1} {
		    APSMpReturn error "Problem changing to Normal mode: $result"
		}
	    }
	    APSMpStep "Verifying we are now in Normal mode"
	    set tries 0
	    while {$tries <= 25} {
		APSWaitWithUpdate -waitSeconds 1
		if {[catch {APScavget -list=LRFSCS:PLC:ModeState -num -pend=20} modestate]} {
		    APSMpReturn error "Problem getting the mode state: $modestate"
		}
		if {($modestate != 5)} {
		    if {$tries == 25} {
			if {[APSPEMTKDialog .warningDialog -text "Unable to switch to Normal mode"] == 1} {
			    APSMpReturn error "Unable to switch to Normal mode"
			}
		    } else {
			incr tries
		    }
		} else {
		    break
		}
	    }
	    if {[catch {APScavget -list=LRFSCS:PLC:SwitchFault -num -pend=20} switchfault]} {
		APSMpReturn error "Problem getting the mode state: $switchfault"
	    }
	    if {($switchfault != 12)} {
		if {[APSPEMTKDialog .warningDialog -text "Switch faults seen while switching to Normal mode"] == 1} {
		    APSMpReturn error "Switch faults seen while switching to Normal mode"
		}
	    }
	}

	APSMpStep "Switch To K3 Down (Water Load) mode"
	if {[catch {APScavput -list=LRFSCS:MCR:SelectNormalWater=1 -pend=20} result]} {
	    if {[APSPEMTKDialog .warningDialog -text "Problem changing to K3 Down (Water Load) mode: $result"] == 1} {
		APSMpReturn error "Problem changing to K2 Down mode: $result"
	    }
	}
	APSMpStep "Verifying we are now in K3 Down (Water Load) mode"
	set tries 0
	while {$tries <= 25} {
	    APSWaitWithUpdate -waitSeconds 1
	    if {[catch {APScavget -list=LRFSCS:PLC:ModeState -num -pend=20} modestate]} {
		APSMpReturn error "Problem getting the mode state: $modestate"
	    }
	    if {($modestate != 5)} {
		if {$tries == 25} {
		    if {[APSPEMTKDialog .warningDialog -text "Unable to switch to K3 Down (Water Load) mode"] == 1} {
			APSMpReturn error "Unable to switch to K3 Down (Water Load) mode"
		    }
		} else {
		    incr tries
		}
	    } else {
		break
	    }
	}
	if {[catch {APScavget -list=LRFSCS:PLC:SwitchFault -num -pend=20} switchfault]} {
	    APSMpReturn error "Problem getting the mode state: $switchfault"
	}
	if {($switchfault != 12)} {
	    if {[APSPEMTKDialog .warningDialog -text "Switch faults seen while switching to K3 Down mode"] == 1} {
		APSMpReturn error "Switch faults seen while switching to K3 Down mode"
	    }
	}


	#Now switch gun
	APSMpStep "Switch To PG1"
	if {[catch {APScavput -list=LRFSCS:MCR:SelectPG1=1 -pend=20} result]} {
	    if {[APSPEMTKDialog .warningDialog -text "Problem changing to PG1: $result"] == 1} {
		APSMpReturn error "Problem changing to PG1: $result"
	    }
	}
	APSMpStep "Verifying we are now in using PG1"
	set tries 0
	while {$tries <= 25} {
	    APSWaitWithUpdate -waitSeconds 1
	    if {[catch {APScavget -list=LRFSCS:PLC:GunState -num -pend=20} gunstate]} {
		APSMpReturn error "Problem getting the gun state: $gunstate"
	    }
	    if {($gunstate != 2)} {
		if {$tries == 25} {
		    if {[APSPEMTKDialog .warningDialog -text "Unable to switch to PG1"] == 1} {
			APSMpReturn error "Unable to switch to PG1"
		    }
		} else {
		    incr tries
		}
	    } else {
		break
	    }
	}
	if {[catch {APScavget -list=LRFSCS:PLC:SwitchFault -num -pend=20} switchfault]} {
	    APSMpReturn error "Problem switching the selected gun: $switchfault"
	}
	if {($switchfault != 12)} {
	    if {[APSPEMTKDialog .warningDialog -text "Switch faults seen while switching to PG1"] == 1} {
		APSMpReturn error "Switch faults seen while switching to PG1"
	    }
	}


	APSMpStep "Run mode switch"
	if {[catch {APScavput -list=LRFSCS:MCR:SelectRun=1 -pend=20} result]} {
	    if {[APSPEMTKDialog .warningDialog -text "Problem running mode switch: $result"] == 1} {
		APSMpReturn error "Problem running mode switch: $result"
	    }
	}
    }
    
    APSWaitWithUpdate -waitSeconds 5
    APSMpStep "${prefix}Click the Fault Reset switch on the L1_WS1 screen" \
      -desc "Click the Fault Reset switch on the L1 water station screen"
    if [catch {exec cavput -list=L1:WS1:pumpResetCmdBO=1} results] {
        if {[APSPEMTKDialog .warningDialog -text "Error while clicking the fault reset switch on the L1_WS1 screen \n$results"] == 1} {
            APSMpReturn error "PCGUN_Startup: $results"
        }
    }
    after 1000
    if [catch {exec cavput -list=L1:WS1:heaterOnCmdBO=1} results] {
        if {[APSPEMTKDialog .warningDialog -text "Error while turning the L1:WS1 heater on \n$results"] == 1} {
            APSMpReturn error "PCGUN_Startup: $results"
        }
    }
    after 15000
    if [catch {exec cavget -list=L1:WS1:heaterOnBI -num} results] {
	APSMpReturn error "PCGUN_Startup: $results"
    }
    if {$results != 1} {
	after 10000
	if [catch {exec cavget -list=L1:WS1:heaterOnBI -num} results] {
	    APSMpReturn error "PCGUN_Startup: $results"
	}
    }
    if {$results != 1} {    
	APSMpStep "${prefix}Wait for operator interaction" \
	  -desc "Wait for operator interaction if Fault Reset switch did not work properly"
	bell
        if {[APSPEMTKDialog .warningDialog -text "Click the Fault Reset switch on the L1_WS1 screen.\nThen click Continue"] == 1} {
	    APSMpReturn error "PCGUN_Startup: Aborting by operator"
	}
    }
    APSMpStep "${prefix}Click the L1:IC1:WS1:ResetC button" \
      -desc "Click the L1:IC1:WS1:ResetC button"
    if [catch {exec cavput -list=L1:IC1:WS1:ResetC=1} results] {
        if {[APSPEMTKDialog .warningDialog -text "Error while resetting L1:IC1:WS1 \n$results"] == 1} {
            APSMpReturn error "PCGUN_Startup: $results"
        }
    }

    APSMpStep "${prefix}Change Timing to PC-Gun" \
      -desc "Change Timing to PC-Gun" -proc "PCGUN_ChangeTiming"
    if [catch {PCGUN_ChangeTiming} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error while changing the timing to PC-Gun \n$result"] == 1} {
            APSMpReturn error "PCGUN_Startup: $result"
        }
    }
    catch {APScavput -list=It:L:B00_enb_bo.VAL=1,It:L:B02_enb_bo.VAL=1,It:L:B04_enb_bo.VAL=1,It:L:B06_enb_bo.VAL=0,It:L:B08_enb_bo.VAL=0 -num -pend=20}

    foreach sector $sectors {
	if {[set $sector]} {
            if {$sector == "L2"} {
                APSMpStep "${prefix}Turn on modulator in sector $sector" \
                  -desc "Turn on modulators"
                set id$sector [APSMpParallel \
                                 -procedure "TurnOnK400 -klystron K2 -SCRFile $SCRFile" \
                                 -mode Automatic]
            } else {
                APSMpStep "${prefix}Turn on modulator in sector $sector" \
                  -desc "Turn on modulators" -proc LMOCS_TurnOn
                if {($sector == "L4") || ($sector == "L5")} {
                    set id$sector [APSMpParallel \
                                     -procedure "LMOCS_TurnOn -sector $sector -PFNFinalValue [set ${sector}PFN] -attnSetPoint [set ${sector}AttnSetPoint] -attnPVName [set ${sector}AttnVar] -sledTrig [set ${sector}sledTrig] -sledTrigVar [set ${sector}sledTrigVar] -resumePCS 0" \
                                     -mode Automatic]
                } else {
                    set id$sector [APSMpParallel \
                                     -procedure "LMOCS_TurnOn -sector $sector -PFNFinalValue [set ${sector}PFN] -attnSetPoint [set ${sector}AttnSetPoint] -attnPVName [set ${sector}AttnVar] -resumePCS 0" \
                                     -mode Automatic]
                }
	    }
	}
    }

    #    APSMpAbort all -onError 1
    foreach sector $sectors {
	if {[set $sector]} {
	    if [catch {APSMpJoin [set id$sector]} result] {
                if {[APSPEMTKDialog .warningDialog -text "Problem brining modulators to full power\n$result"] == 1} {
		    APSMpReturn error "PCGUN_Startup: Joining LMOCS_TurnOn $sector: $result"
		}
	    }
	}
    }


    APSWaitWithUpdate -waitSeconds 3

    #    APSMpStep "${prefix}Set power to saturation level" -desc "Set power to saturation level"
    #    foreach sector $sectors {
    #	if {[set $sector]} {
    #	    if [catch {APSLMOCS_SetSaturatedPower -sector $sector -klyPower ${sector}AttnSetPoint} result] {
    #		APSMpReturn error "PCGUN_Startup: $result"
    #	    }
    #	}
    #    }


    APSMpStep "${prefix}Set LI:AUTO:PH:modeMO to Manual" \
      -desc "Set LI:AUTO:PH:modeMO to Manual"
    if [catch {APSLINAC_SetPhaseControlMode -state Manual} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error while setting LI:AUTO:PH:modeMO to Manual \n$result"] == 1} {
            APSMpReturn error "PCGUN_Startup: $result"
        }
    }

    set matchBeamlines "-match=column,Beamline=LINAC,Beamline=LI,|,Beamline=PCGun1,|,Beamline=rfGun,|,Beamline=rfGun1,|,Beamline=rfGun2,|"
    if {$L1} {
	append matchBeamlines ",Beamline=L1,|"
    }
    if {$L2} {
	append matchBeamlines ",Beamline=L2,|"
    }
    if {$L3} {
	append matchBeamlines ",Beamline=L3,|"
    }
    if {$L4} {
	append matchBeamlines ",Beamline=L4,|"
    }
    if {$L5} {
	append matchBeamlines ",Beamline=L5,|"
    }


    APSMpStep "${prefix}Restore values from SCR file" -desc "Restore SCR file"
    if [string length $SCRFile] {
        APSMpStep RestoringSCRValues 
        set tmpFile /tmp/[APSTmpString]
        if [catch {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,| \
		     -match=column,ControlName=*MO:PFN*,! \
		     -match=column,ControlName=L:L?Stabilizer:SDDS*,!\
		     $matchBeamlines
            exec sddscasr -restore $tmpFile} result] {
            APSPEMTKDialog .warningDialog -strings Continue -default 0 -text "Problem restoring SCR file: PCGUN_Startup: $result"
            catch {APSSendEMail -address soliday \
                     -subject "Problem restoring SCR file."  \
                     -message "Problem restore SCR file\nPCGUN_Startup\n$SCRFile\n$result"} 
        }
	file delete $tmpFile
        if [catch {exec sddsprocess $SCRFile $tmpFile \
		     -match=column,IsReadOnly=+n \
		     -match=column,IsProtected=+n \
		     -match=column,Category=Timing \
		     -match=column,Beamline=PAR
            exec sddscasr -restore $tmpFile} result] {
            APSPEMTKDialog .warningDialog -strings Continue -default 0 -text "Problem restoring SCR file: PCGUN_Startup: $result"
            catch {APSSendEMail -address soliday \
                     -subject "Problem restoring SCR file."  \
                     -message "Problem restore SCR file\nPCGUN_Startup\n$SCRFile\n$result"} 
        }
	file delete $tmpFile
    }

    #    if [catch {exec cavget -list=L1:TM:RFG:RF:startTimeAO,L1:TM:RFG:RF:widthAO -pend=20} results] {
    #	tk_dialog .warningDialog "Warning Message" "Problem reading gate start and width values" warning -1 Continue
    #    } else {
    #	if {($gateStartTime != [lindex $results 0]) || ($gateWidth != [lindex $results 1])} {
    #	    tk_dialog .warningDialog "Warning Message" "Problem setting gate start and width values" warning -1 Continue
    #	}
    #    }
    #Set the timing PVs back to 1 after the SCR most likely set them to 0
    catch {APScavput -list=It:L:B00_enb_bo.VAL=1,It:L:B02_enb_bo.VAL=1,It:L:B04_enb_bo.VAL=1,It:L:B06_enb_bo.VAL=0,It:L:B08_enb_bo.VAL=0 -num -pend=20}

    APSMpStep "${prefix}Launching LMOCS_Recover" -desc "Launch LMOCS_Recover"
    if {$L1} {
        set id1 [APSMpParallel \
                  -procedure "LMOCS_Recover -L1 1 -SCRFile $SCRFile" \
                  -mode Semi-Automatic]
        #exec LinacRFRecovery -RF L1  -SCRFile [file tail $SCRFile] &
    }
    if {$L2} {
        set id2 [APSMpParallel \
                  -procedure "LMOCS_Recover -L1 2 -SCRFile $SCRFile" \
                  -mode Semi-Automatic]
        #exec LinacRFRecovery -RF L2  -SCRFile [file tail $SCRFile] &
    }
    if {$L3} {
        set id3 [APSMpParallel \
                  -procedure "LMOCS_Recover -L1 3 -SCRFile $SCRFile" \
                  -mode Semi-Automatic]
        #exec LinacRFRecovery -RF L3  -SCRFile [file tail $SCRFile] &
    }
    if {$L4} {
        set id4 [APSMpParallel \
                  -procedure "LMOCS_Recover -L1 4 -SCRFile $SCRFile" \
                  -mode Semi-Automatic]
        #exec LinacRFRecovery -RF L4  -SCRFile [file tail $SCRFile] &
    }
    if {$L5} {
        set id5 [APSMpParallel \
                  -procedure "LMOCS_Recover -L1 5 -SCRFile $SCRFile" \
                  -mode Semi-Automatic]
        #exec LinacRFRecovery -RF L5  -SCRFile [file tail $SCRFile] &
    }
    if {$L1} {
        if [catch {APSMpJoin $id1} results] {
            APSMpReturn error "LMOCS_Recover: $results"
        }
    }
    if {$L2} {
        if [catch {APSMpJoin $id2} results] {
            APSMpReturn error "LMOCS_Recover: $results"
        }
    }
    if {$L3} {
        if [catch {APSMpJoin $id3} results] {
            APSMpReturn error "LMOCS_Recover: $results"
        }
    }
    if {$L4} {
        if [catch {APSMpJoin $id4} results] {
            APSMpReturn error "LMOCS_Recover: $results"
        }
    }
    if {$L5} {
        if [catch {APSMpJoin $id5} results] {
            APSMpReturn error "LMOCS_Recover: $results"
        }
    }

#    if {[APSPEMTKDialog .warningDialog -text "Click Continue when the LinacRFRecovery tools are done."] == 1} {
#        APSMpReturn error "PCGUN_Startup: Operation aborted by user"
#    }

    #Set the timing PVs back to 0
    catch {APScavput -list=It:L:B00_enb_bo.VAL=1,It:L:B02_enb_bo.VAL=0,It:L:B04_enb_bo.VAL=0,It:L:B06_enb_bo.VAL=0,It:L:B08_enb_bo.VAL=0 -num -pend=20}

    if {[catch {LMOCS_ResetAutoPhaseControl -SCRFile $SCRFile -L1 $L1 -L2 $L2 -L3 $L3 -L4 $L4 -L5 $L5} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Modulator Phase Control not reset\nPCGUN_Startup: $result"] == 1} {
            APSMpReturn error "Modulator Phase Control not reset: PCGUN_Startup: $result"
        }
    }

    APSMpReturn ok
}

proc APSLINAC_IncreaseAttnCtrl {args} {
    set deviceList ""
    set minAttenuation 0
    APSStrictParseArguments {deviceList minAttenuation}
    
    if {[llength $deviceList] != 1} {
	return -code error "APSLINAC_IncreaseAttnCtrl: invalid arguments passed"
    }
    if [catch {APSDevSend \
		 -group LinacKlystron \
		 -operation ReadRFAttenuatorPosition \
		 -deviceList $deviceList} result] {
        puts "APSLINAC_IncreaseAttnCtrl: $result"
	return -code error "APSLINAC_IncreaseAttnCtrl: $result"
    }
    set step 1

    while {$result < $minAttenuation} {
        incr step
        if {$step == 10} {
            APSMpStep "Increasing Attenuator Control for L$deviceList to $minAttenuation"
            set step 1
        }
	if [catch {APSDevSend \
		     -group LinacKlystron \
		     -operation MoveRFAttenuator \
		     -deviceList $deviceList \
		     -value -1.0} result] {
	    return -code error "APSLINAC_IncreaseAttnCtrl: $result"
	}
	APSWaitWithUpdate -waitSeconds 1
	if [catch {APSDevSend \
		     -group LinacKlystron \
		     -operation ReadRFAttenuatorPosition \
		     -deviceList $deviceList} result] {
	    return -code error "APSLINAC_IncreaseAttnCtrl: $result"
	}
    }
    update
}

proc APSPCGUN_CheckVacuum {args} {
    set deviceList ""
    set maxValueList ""
    APSStrictParseArguments {deviceList maxValueList}

    if {([llength $deviceList] != [llength $maxValueList]) || ([llength $deviceList] == 0)} {
	return -code error "APSPCGUN_CheckVacuum: invalid arguments passed"
    } 
    if [catch {APSDevSend \
		 -deviceList $deviceList \
		 -operation ReadVacuumPressure \
		 -group LinacVacuum} results] {
	return -code error "APSPCGUN_CheckVacuum: $results"
    }
    foreach result $results maxValue $maxValueList device $deviceList {
	if {$result > $maxValue} {
	    bell
            if {[APSPEMTKDialog .warningDialog -text "Vacuum for $device is greater then $maxValue."] == 1} {
		return -code error "APSPCGUN_CheckVacuum: Vacuum for $device is greater then $maxValue."
	    }
	}
    }
}

proc APSPCGUN_CheckThermocouples {args} {
    set maxTemp 108
    set minTemp 101
    set tempRange 6
    set deviceList ""
    APSStrictParseArguments {deviceList maxTemp minTemp tempRange}
    
    if {[llength $deviceList] == 0} {
	return -code error "APSPCGUN_CheckThermocouples: invalid arguments passed"
    }
    if [catch {APSDevSend \
		 -deviceList $deviceList \
		 -operation ReadThermocoupleTemp \
		 -group LinacPCGun} results] {
	return -code error "APSPCGUN_CheckThermocouples: $results"
    }
    set minvalue 10000
    set maxvalue -1000
    foreach result $results device $deviceList {
	if {($result > $maxTemp)} {
	    bell
            if {[APSPEMTKDialog .warningDialog -text "Thermocouple for $device is greater then $maxTemp."] == 1} {
		return -code error "APSPCGUN_CheckThermocouples: Thermocouple for $device is greater then $maxTemp."
	    }
	}
	if {($result < $minTemp)} {
	    bell
            if {[APSPEMTKDialog .warningDialog -text "Thermocouple for $device is less then $maxTemp."] == 1} {
		return -code error "APSPCGUN_CheckThermocouples: Thermocouple for $device is less then $maxTemp."
	    }
	}
	if {$result > $maxvalue} { set maxvalue $result }
	if {$result < $minvalue} { set minvalue $result }
    }
    if {[expr $maxvalue - $minvalue] > $tempRange} {
	bell
        if {[APSPEMTKDialog .warningDialog -text "Thermocouples are not within $tempRange degrees of each other."] == 1} {
	    return -code error "APSPCGUN_CheckThermocouples: Thermocouples are not within $tempRange degrees of each other."
	}
    }
}

proc APSPCGUN_SetMagnetCurrent {args} {
    set deviceList ""
    set value 0
    APSStrictParseArguments {deviceList value}
    if {[llength deviceList] == 0} {
	return -code error "APSPCGUN_SetMagnetCurrent: invalid arguments passed"
    }
    if [catch {APSDevSend \
		 -deviceList $deviceList \
		 -operation SetMagnetCurrent \
		 -group LinacPCGun \
		 -value $value} results] {
	return -code error "APSPCGUN_SetMagnetCurrent: $results"
    }
}

proc APSPCGUN_ReadRFSwitch1 {args} {
    set desiredState ""
    APSStrictParseArguments {desiredState}
    if [catch {APSDevSend \
		 -group LinacRFGun \
		 -operation ReadRFSwitch1 \
		 -deviceList GUN} GUN] {
	return -code error "APSPCGUN_ReadRFSwitch1: $GUN"
    }
    if [catch {APSDevSend \
		 -group LinacRFGun \
		 -operation ReadRFSwitch1 \
		 -deviceList LD} LD] {
	return -code error "APSPCGUN_ReadRFSwitch1: $LD"
    }
    if {[catch {APSDevSend \
		  -group LinacRFGun \
		  -operation ReadRFSwitchState \
		  -deviceList 0} state]} {
	return -code error "APSPCGUN_ReadRFSwitch1: $state"
    }
    if {[llength $desiredState]} {
	if {($desiredState == "GUN") && ($GUN != "Enabled")} {
	    return -code error
	} elseif {($desiredState == "LD") && ($LD != "Enabled")} {
	    return -code error
	}
    }

    if {($GUN == "Enabled") && ($state == "RUNNING")} {
	return -code ok GUN
    }
    if {($LD == "Enabled") && ($state == "RUNNING")} {
	return -code ok LD
    }

    return -code ok "FAULT"

    #    if [catch {APSDevSend -group LinacRFGun -operation ReadRFSwitch1 -deviceList 0} result] {
    #	return -code error "APSPCGUN_ReadRFSwitch1: $result"
    #    }
    #    if {[llength $desiredState]} {
    #	if {$result != $desiredState} {
    #	    return -code error
    #	    bell
    #	    if {[tk_dialog .warningDialog "Warning Message" "RF Switch \#1 is not set to $desiredState." warning -1 Continue "Abort Procedure"] == 1} {
    #		return -code error "APSPCGUN_ReadRFSwitch1: RF Switch \#1 is not set to $desiredState."
    #	    }
    #	}
    #    }
    #    return -code ok $result
}

proc APSLINAC_CheckLLRFStatus {args} {
    set desiredState ""
    set deviceList ""
    APSStrictParseArguments {desiredState deviceList}
    if [catch {APSDevSend \
		 -group LinacKlystron \
		 -operation QueryLLRFOn \
		 -deviceList $deviceList} results] {
	return -code error "APSLINAC_CheckLLRFStatus: $results"
    }
    if {[llength $desiredState]} {
	set desiredState [string tolower $desiredState]
	if {$desiredState == "off"} {
	    set desiredState Off
	} else {
	    set desiredState On
	}
	foreach result $results sector $deviceList {
	    if {$result == 0} {set result Off}
	    if {$result == 1} {set result On}
	    if {$result != $desiredState} {
		bell
                if {[APSPEMTKDialog .warningDialog -text "LLRF in Sector $sector is $result not $desiredState."] == 1} {
		    return -code error "APSLINAC_CheckLLRFStatus: LLRF in Sector $sector is not $desiredState."
		}
	    }
	}
    }
    return -code ok $results
}

proc APSLINAC_CheckLLStatus {args} {
    set desiredState off
    set deviceList ""
    APSStrictParseArguments {desiredState deviceList}
    if [catch {APSDevSend \
		 -group LinacKlystron \
		 -operation ReadLLRFState \
		 -deviceList $deviceList} results] {
	return -code error "APSLINAC_CheckLLStatus: $results"
    }
    if {[llength $desiredState]} {
	set desiredState [string tolower $desiredState]
	if {$desiredState == "off"} {
	    set desiredValue 0
	} else {
	    set desiredValue 1
	    set desiredState on
	}
	foreach result $results sector $deviceList {
	    if {$result != $desiredValue} {
		bell
                if {[APSPEMTKDialog .warningDialog -text "LLRF in Sector One is not $desiredState."] == 1} {
		    return -code error "APSLINAC_CheckLLStatus: LLRF in Sector One is not $desiredState."
		}
	    }
	}
    }
    return -code ok $results
}


proc APSLINAC_SetInjectionTimingTrigger {args} {
    set state linac
    APSStrictParseArguments {state}
    if {[string tolower $state] == "linac"} {
	set state Linac
    } else {
	set state PAR
    }
    if [catch {APSDevSend \
		 -group LinacLaser \
		 -operation SetInjectionTimingTriggerTo$state \
		 -deviceList "0"} result] {
	return -code error "APSLINAC_SetInjectionTimingTrigger: $result"
    }
}

proc APSLINAC_SetBeamTriggerRate {args} {
    set state ""
    APSStrictParseArguments {state}
    set state [string tolower $state]
    switch -- $state {
        "normal" {
	    set value Normal
        } 
        "--2hz--" {
	    set value 2Hz
        }
	"--6hz--" {
	    set value 6Hz
	}
	"--10hz--" {
	    set value 10Hz
	}
	{{rfg 10hz}} {
	    set value RFG10Hz
	}
	{{lin 30hz}} {
	    set value Linac30Hz
	}
	{{par 30hz}} {
	    set value Par30Hz
        }
        default {
            return -code error "APSLINAC_SetBeamTriggerRate: invalid state: $state"
        }
    }
    if [catch {APSDevSend \
		 -group LinacTiming \
		 -operation SetBeamTriggerRate$value \
		 -deviceList "0"} result] {
	return -code error "APSLINAC_SetBeamTriggerRate: $result"
    }
    APSWaitWithUpdate -waitSeconds 2

    if [catch {APSDevSend \
		 -group LinacTiming \
		 -operation ReadBeamTriggerRate \
		 -deviceList "0"} result] {
	return -code error "APSLINAC_SetBeamTriggerRate: $result"
    }
    if {[string tolower $result] != $state} {
	bell
        if {[APSPEMTKDialog .warningDialog -text "Unable to change the Beam Trigger Timing."] == 1} {
	    return -code error "APSLINAC_SetBeamTriggerRate: Unable to change the Beam Trigger Timing to $state.\nFix then click Continue"
	}
    }
}

proc APSPCGUN_SetLaserTrigger {args} {
    set state ""
    APSStrictParseArguments {state}
    switch [string tolower $state] {
        "linacbeam" {
	    set value LinacBeam
        } 
        "stop" {
	    set value Stop
        }
	"teststandrf" {
	    set value TestStandRF
	}
        default {
            return -code error "APSPCGUN_SetLaserTrigger: invalid state: $state"
        }
    }
    if [catch {APSDevSend \
		 -group LinacLaser \
		 -operation SetLaserTrigger$value \
		 -deviceList "0"} result] {
	return -code error "APSPCGUN_SetLaserTrigger: $result"
    }
}

proc APSLINAC_CheckTimingSource {args} {
    set desiredState ""
    set deviceList ""
    APSStrictParseArguments {desiredState deviceList}
    if {[llength $deviceList] != 1} { 
	return -code error "APSLINAC_CheckTimingSource: invalid arguments passed" 
    }
    if [catch {APSDevSend \
		 -group LinacTiming \
		 -operation QueryTimingSource \
		 -deviceList $deviceList} result] {
	return -code error "APSLINAC_CheckTimingSource: $result"
    }
    if {$result != $desiredState} {
        if {[APSPEMTKDialog .warningDialog -text "L$deviceList timing source is not set to $desiredState."] == 1} {
    	    return -code error "APSLINAC_CheckTimingSource: L$deviceList timing source is not set to $desiredState"
	}
    }
}

proc APSLINAC_SetTimingSource {args} {
    set state ""
    set deviceList ""
    APSStrictParseArguments {state deviceList}
    switch [string tolower $state] {
        "lirfrate" { set value LIRFRate } 
        "libeamrate" { set value LIBeamRate }
	"libeamrfg" { set value LIBeamRFG }
	"libeampg1" { set value LIBeamPG1 }
	"asyncrfrate" { set value AsyncRFRate }
        default {
            return -code error "APSLINAC_SetTimingSource: invalid state: $state"
        }
    }
    if [catch {APSDevSend \
		 -group LinacTiming \
		 -operation SetTimingSource$value \
		 -deviceList $deviceList} result] {
	return -code error "APSLINAC_SetTimingSource: $result"
    }
}

proc APSLMOCS_CheckSequence3Status {args} {
    set desiredState off
    set deviceList ""
    APSStrictParseArguments {desiredState deviceList}
    if [catch {APSDevSend \
		 -group LinacKlystron \
		 -operation QuerySequence3Ready \
		 -deviceList $deviceList} results] {
	return -code error "APSLMOCS_CheckSequence3Status: $results"
    }
    if {[llength $desiredState]} {
	set desiredState [string tolower $desiredState]
	if {$desiredState == "off"} {
	    set desiredValue 0
	} else {
	    set desiredValue 1
	    set desiredState on
	}
	foreach result $results sector $deviceList {
	    if {$result != $desiredValue} {
		bell
                if {[APSPEMTKDialog .warningDialog -text "Seq \#3 in sector $sector is not $desiredState."] == 1} {
		    return -code error "APSLMOCS_CheckSequence3Status: Seq \#3 in sector $sector is not $desiredState"
		}
	    }	
	}
    }
    return -code ok $results
}

proc APSPCGUN_SetTimingForPCGun {args} {
    if [catch {APSDevSend \
		 -group LinacLaser \
		 -operation SetTimingForPCGun \
		 -deviceList 0} result] {
	return -code error "APSPCGUN_SetTimingForPCGun: $result"
    }
    APSWaitWithUpdate -waitSeconds 2
    if [catch {APSDevSend \
		 -group LinacLaser \
		 -operation ReadTimingConfiguredForPCGun \
		 -deviceList 0} result] {
	return -code error "APSPCGUN_SetTimingForPCGun: $result"
    }
    if {$result != 1} {
	bell
        if {[APSPEMTKDialog .warningDialog -text "Unable to set the timing for the PC-Gun."] == 1} {
	    return -code error "APSPCGUN_SetTimingForPCGun: Unable to set the timing for the PC-Gun."
	}
    }	
}

proc APSPCGUN_SetTimingForRFGun {args} {
    if [catch {APSDevSend \
		 -group LinacLaser \
		 -operation SetTimingForRFGun \
		 -deviceList 0} result] {
	return -code error "APSPCGUN_SetTimingForRFGun: $result"
    }
    APSWaitWithUpdate -waitSeconds 2
    if [catch {APSDevSend \
		 -group LinacLaser \
		 -operation ReadTimingConfiguredForRFGun \
		 -deviceList 0} result] {
	return -code error "APSPCGUN_SetTimingForRFGun: $result"
    }
    if {$result != 1} {
	bell
        if {[APSPEMTKDialog .warningDialog -text "Unable to set the timing for the RF-Gun."] == 1} {
	    return -code error "APSPCGUN_SetTimingForRFGun: Unable to set the timing for the -Gun."
	}
    }	
}

proc APSPCGUN_SetPCGunTriggerOnOff {args} {
    set state ""
    APSStrictParseArguments {state}
    switch [string tolower $state] {
        "on" {
	    set value On
        } 
        "off" {
	    set value Off
        }
        default {
            return -code error "APSPCGUN_SetPCGunTriggerOnOff: invalid state: $state"
        }
    }
    if [catch {APSDevSend \
		 -group LinacLaser \
		 -operation SetPCGUNTrig$value \
		 -deviceList 0} result] {
	return -code error "APSPCGUN_SetPCGunTriggerOnOff: $result"
    }
}

proc APSLINAC_SetPhaseControlMode {args} {
    set state ""
    set deviceList [list 1 2 3 4 5]
    APSStrictParseArguments {state deviceList}
    switch [string tolower $state] {
        "manual" {
	    set value Manual
        } 
        "autohold" {
	    set value AutoHold
        }
	"autopresets" {
	    set value AutoPresets
	}
        default {
            return -code error "APSLINAC_SetPhaseControlMode: invalid state: $state"
        }
    }
    if [catch {APSDevSend \
		 -group LinacKlystron \
		 -operation SetPhaseControlMode$value \
		 -deviceList $deviceList} result] {
	return -code error "APSLINAC_SetPhaseControlMode: $result"
    }
}












########################################
#
# PCGUN_ModeSwitch is not used anywhere as far as I can tell.
#
########################################
proc PCGUN_ModeSwitchInfo {} {
    return "The purpose of this procedure is to switch between two modes:\n\
PC-gun-to-LEUTL and PC-gun-to-PAR"
}

proc PCGUN_ModeSwitchDialog {frame} {
    APSSetVarAndUpdate status "Click OK to set timing for PC-Gun"
    pack [message $frame.msg -aspect 300 -justify left \
	    -text "Click OK to set timing for PC-Gun"]
    return
}

proc PCGUN_ModeSwitchPackProc {frame} {
    pack [frame $frame.top]
    APSRadioButtonFrame .save \
      -parent $frame.top -label "Save SCR" \
      -variable PCGUN_ModeSwitch(saveSCR) \
      -buttonList "Yes No" \
      -valueList "1 0" \
      -packOption {-side top} \
      -orientation horizontal
    APSRadioButtonFrame .ltp \
      -parent $frame.top -label "LTP Control Law Modulator" \
      -variable PCGUN_ModeSwitch(LTPcontLM) \
      -buttonList "L4 L5" \
      -valueList "L4 L5" \
      -packOption {-side top} \
      -orientation horizontal
}

proc PCGUN_ModeSwitch {args} {
    set SCRFile ""
    set conditionList [list L4:SC L4:QM L5:SC L5:QM]
    set cycles 1
    set saveSCR 1
    APSStrictParseArguments {SCRFile conditionList cycles saveSCR}

    global execMode APSMpLControlPS

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

    if [catch {APSLinkToLINACPVs} result] {
	APSMpReturn error "PCGUN_ModeSwitch: $result"
    }
    if [catch {APSRFGUN_DetectSelectedGun} RGSelected] {
	APSMpReturn error "PCGUN_ModeSwitch: $RGSelected"
    }
    if [catch {APSPCGUN_ReadRFSwitch1} switch] {
	APSMpReturn error "PCGUN_ModeSwitch: $switch"
    }
    if {$switch != "LD"} {
	APSMpReturn error "PCGUN_ModeSwitch: PCGUN is not already running"
    }
    if {[catch {exec cavget -list=L:LTPControlModulator} LTPcontLM]} {
	set LTPcontLM None
    }

    set arrayName APSMpLControlPS
    APSLGenericPSArraySetup \
      -arrayName $arrayName \
      -conditionList $conditionList \
      -SCRFile $SCRFile \
      -cycles $cycles

    APSMpStep init -promptDialog \
      "APSLGenericPSDialog -packProc PCGUN_ModeSwitchPackProc -turnOn 0 -condition 0 -chooseSCR 1 -arrayName $arrayName -frame " -vars {saveSCR LTPcontLM}

    set SCRFile $APSMpLControlPS(Filename)

    set paramString ""
    foreach param {SCRFile conditionList cycles saveSCR} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure PCGUN_ModeSwitch -action initialize -state ok -parameters $paramString}


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

    set RFSwitchMode ""
    set SelectedGun ""
    foreach {controlName valueString} $results {
	if {[regexp -- L\[4-5\]:MO:PFNvAO $controlName]} {
	    set L[string index $controlName 1]PFN $valueString
	} elseif {"LTP:B1:CurrentAO" == $controlName} {
	    set LTPB1 $valueString
	} elseif {"PTB:B1:CurrentAO" == $controlName} {
	    set PTBB1 $valueString
	} elseif {"PTB:B2:CurrentAO" == $controlName} {
	    set PTBB2 $valueString
	} elseif {"L4:SD:DC1ARF:SetpointP" == $controlName} {
	    set L4AttnSetPoint $valueString
	    set L4AttnVar $controlName
	} elseif {"L5:SD:DC1ARF:SetpointP" == $controlName} {
	    set L5AttnSetPoint $valueString
	    set L5AttnVar $controlName
	} elseif {"L4:TM:sledTrigAO" == $controlName} {
	    set L4sledTrig $valueString
	    set L4sledTrigVar $controlName
	} elseif {"L5:TM:sledTrigAO" == $controlName} {
	    set L5sledTrig $valueString
	    set L5sledTrigVar $controlName
	} elseif {[regexp -- L\[4-5\]:AUTO:PH:SetpointAO $controlName]} {
	    set L[string index $controlName 1]PhaseSetPoint $valueString
	    set L[string index $controlName 1]PhaseVar $controlName
	} elseif {[regexp -- L\[4-5\]:PP:phaseAdjAO $controlName]} {
	    set L[string index $controlName 1]PhaseAdjSetPoint $valueString
	    set L[string index $controlName 1]PhaseAdjVar $controlName
	} elseif {"It:LinacTrig2ParIpAO" == $controlName} {
	    set ItLinacTrig $valueString
	    set ItLinacTrigVal $controlName
	} elseif {"It:ListTrig2ParIpAO" == $controlName} {
	    set ItListTrig $valueString
	    set ItListTrigVal $controlName
        } elseif {$controlName == "LRFSCS:modeM"} {
            set RFSwitchMode $valueString
        } elseif {$controlName == "LRFSCS:gunM"} {
            set SelectedGun $valueString
	}
    }
    APSStrictParseArguments {L4PFN L5PFN}

    if {[catch {APSDevSend \
		  -group LinacRFGun \
		  -operation ReadRFCurrentMode \
		  -deviceList 0} linacMode]} {
	return -code error "PCGUN_ModeSwitch: $linacMode"
    }
    if {[catch {APSDevSend \
		  -group LinacRFGun \
		  -operation ReadCurrentGun \
		  -deviceList 0} linacGun]} {
	return -code error "PCGUN_ModeSwitch: $linacGun"
    }
    set RFSwitchMode [join $RFSwitchMode]
    set SelectedGun [join $SelectedGun]
    set linacMode [join $linacMode]
    set linacGun [join $linacGun]
    if {$RFSwitchMode != $linacMode} {
        if {[APSPEMTKDialog .warningDialog -text "The Linac RF Switching mode is different from that in the SCR file.\n${SCRFile}\n(SCR file: ${RFSwitchMode})\n(Current value: ${linacMode})"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: The Linac RF Switching mode is different from that in the SCR file."
        }
    }
    if {$SelectedGun != $linacGun} {
        if {[APSPEMTKDialog .warningDialog -text "The Linac Gun is different from that in the SCR file.\n${SCRFile}\n(SCR file: ${SelectedGun})\n(Current value: ${linacGun})"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: The Linac Gun is different from that in the SCR file."
        }
    }
    foreach sector "L4 L5" {
	lappend PFNvalues [set ${sector}PFN]
	if {([set ${sector}PFN] < 5) || ([set ${sector}PFN] > 50)} {
            if {[APSPEMTKDialog .warningDialog -text "Value for sector $sector PFN is [set ${sector}PFN] (not valid)\nIf you are sure this PFN value is correct\nyou may click continue"] == 1} {
		APSMpReturn error "PCGUN_ModeSwitch: Value for sector $sector PFN is [set ${sector}PFN] (not valid)"
	    }
	}
	if {([info exists ${sector}AttnSetPoint] != 1) || 
	    ([info exists ${sector}AttnVar] != 1)} {
	    APSMpReturn error "PCGUN_ModeSwitch: Value for sector $sector Attn set point does not exist in SRC file"
	}
    }

    APSMpStep "${prefix}Determine current state" \
      -desc "Determine current state"
    if [catch {APSDevSend \
		 -group LTPToEndPSOps \
		 -operation ReadCurrent \
		 -deviceList "LTP:B1 PTB:B1 PTB:B2"} results] {
	APSMpReturn error "PCGUN_ModeSwitch: $results"
    }
    set i 0
    set j 0
    foreach value $results {
	if {$value >= 100} {
	    incr i
	} elseif {$value < .5} {
	    incr j
	}
    }
    if {$i == 3} {
	set beamTarget PAR
    } elseif {$j == 3} {
	set beamTarget LEUTL
    } else {
	bell
	set value [tk_dialog2 .warningDialog "Warning Message" \
		     "Unable to determine current state. The beam is going to:" \
		     warning -1 "LEUTL" "PAR"]
	if {$value == 0} {
	    set beamTarget LEUTL
	} else {
	    set beamTarget PAR
	}
    }

    APSMpStep "${prefix}Determine SCR state" \
      -desc "Determine SCR state"
    set i 0
    set j 0
    foreach value "$LTPB1 $PTBB1 $PTBB2" {
	if {$value >= 100} {
	    incr i
	} elseif {$value < .5} {
	    incr j
	}
    }
    if {$i == 3} {
	set beamTargetSCR PAR
    } elseif {$j == 3} {
	set beamTargetSCR LEUTL
    } else {
	bell
	set value [tk_dialog2 .warningDialog "Warning Message" \
		     "Unable to determine SCR state. The desired target is:" \
		     warning -1 "LEUTL" "PAR"]
	if {$value == 0} {
	    set beamTargetSCR LEUTL
	} else {
	    set beamTargetSCR PAR
	}
    }

    APSMpStep "${prefix}Confirm switch" \
      -desc "Confirm switch"
    bell
    if {[APSPEMTKDialog .warningDialog -appendtext 0 -title "Confirmation Message" -bitmap question -text "Please confirm switch from current state (PCGUN to $beamTarget) to desired state (PCGUN to $beamTargetSCR)"] == 1} {
	APSMpReturn error "PCGUN_ModeSwitch: Aborted by operator"
    }
    global L5:P4:BPM
    if {[pv linkw L5:P4:BPM L5:P4:BPM]} {
	APSMpReturn error "PCGUN_ModeSwitch: Unable to read L5:P4:BPM"
    }

    if {$beamTargetSCR == "PAR"} {
	APSMpStep "${prefix}Check that the charge in the Linac is sufficient" \
	  -desc "Check that the charge in the Linac is sufficient"
	set i 0
	while {$i == 0} {
	    pv getw L5:P4:BPM
	    if {(${L5:P4:BPM} < .002) && (${L5:P4:BPM} > .009)} {
		bell
                set i [APSPEMTKDialog .warningDialog -strings {Continue Ignore "Abort Procedure"} -text "L5:P4:BPM is out of range (.002 to .009). Please adjust"]
		if {$i == 2} {
		    APSMpReturn error "PCGUN_ModeSwitch: Aborted by operator"
		}
	    } else {
		set i 1
	    }
	}
    }

    if {$saveSCR} {
	APSMpStep "${prefix}Make routine system save" -desc "Make routine system save"
	update
	set description "Routine save: PCGUN to ${beamTarget}, [exec whoami]"
	if {[catch {APSSaveMachine -machine LPL -description $description -routine 1} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Error doing routine system save.\n$result"] == 1} {
		APSMpReturn error "PCGUN_ModeSwitch: Error doing save: $result"
	    }
	    #	    APSMpReturn error "PCGUN_ModeSwitch: Error doing save: $result"
	}
    }    

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

    APSMpStep "${prefix}Suspend Linac ControlLaws" \
      -desc "Suspend Linac ControlLaws"
    if [catch {APSMpLSuspendResumeRunControl \
		 -value "Suspend" \
		 -name "LinacControlLaw" \
		 -group "RunControlGroup" \
		 -deviceList "X Y"} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to suspend X and Y linac controllaws.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: $result"
        }
	#	APSMpReturn error "PCGUN_ModeSwitch: $result"
    }

    APSMpStep "${prefix}Suspend LTP ControlLaws" \
      -desc "Suspend LTP ControlLaws"
    if [catch {APSMpLSuspendResumeRunControl \
		 -value "Suspend" \
		 -name "LTPControlLaw" \
		 -group "RunControlGroup" \
		 -deviceList "X Y"} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to suspend X and Y LTP controllaws.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: $result"
        }
	#	APSMpReturn error "PCGUN_ModeSwitch: $result"
    }

    APSMpStep "${prefix}Close shutter 4" -desc "Close shutter 4"
    if [catch {APSDevSend \
		 -group LinacLaser \
		 -operation CloseLRShutter \
		 -deviceList "4"} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to close shutter 4.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: $result"
        }
	#	APSMpReturn error "PCGUN_ModeSwitch: $result"
    }

    APSMpStep "${prefix}Close gate valves" -desc "Close gate valves"
    if [catch {APSRFGUN_OpenCloseGateValve \
		 -deviceList "L1PG1GV2" \
		 -value Close \
		 -group LinacValves} result] {
        if {[APSPEMTKDialog .warningDialog -text "Gate valves failed to close."] == 1} {
	    APSMpReturn error "PCGUN_ModeSwitch: $result"
	}
    }

    set powerSuppliesTurnOn "PB:Q1 PB:Q2 PB:Q3 PB:Q4 PB:V1 PB:V2 PB:H1 PB:H2"
    if {[llength $powerSuppliesTurnOn]} {
	set step 0
	while {1} {
	    APSMpStep "Turn on PB power supplies"
	    incr step
	    if [catch {APSDevSend \
			 -releaseLinks 1 \
			 -group LTPToEndPSOps \
			 -operation QueryOn \
			 -deviceList $powerSuppliesTurnOn} results] {
		APSMpReturn error "PCGUN_ModeSwitch: $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 "PCGUN_ModeSwitch: 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 "PCGUN_ModeSwitch: $result"
		}
		APSWaitWithUpdate -waitSeconds 10
	    } else {
		break
	    }
	}
    }

    set particle electron
    set conditioningTime 5
    set standardizeB1 1
    set energy [APSPARLETDefaultEnergy]

    APSMpStep "LTP: Turn On DCPS" -proc APSMpLTPTurnOnDCPS 
    if [catch APSMpLTPTurnOnDCPS result] {
        if {[APSPEMTKDialog .warningDialog -text "Error turning on LTP DCPS.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Error turning on LTP DCPS: $result"
        }
	#        APSMpReturn error "Error turning on LTP DCPS: $result"
    }

    if {$standardizeB1} {
        if [catch {APSDevSend -group LinacPS -operation QueryOff -deviceList "L3:AM1"} result] {
            APSMpReturn error "PCGUN_ModeSwitch: $result"
        }
        if {$result} {
            if {[catch {APSDevSend \
                          -group LinacPS \
                          -operation TurnOn \
                          -deviceList L3:AM1} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Unable turn on L3:AM1.\nPCGUN_ModeSwitch: $result"] == 1} {
                    APSMpReturn error "Unable turn on L3:AM1: PCGUN_ModeSwitch: $result"
                }
            }
            APSWaitWithUpdate -waitSeconds 5
        }
        if [catch {APSDevSend \
                     -releaseLinks 1 \
                     -group LinacPS \
                     -operation SetCurrent \
                     -deviceList L3:AM1 \
                     -valueList 63 \
                     -timeout 0} result] {
            APSMpReturn error "PCGUN_ModeSwitch: $result"
        }
        set try 10
        while {$try >= 0} {
            incr try -1
            if {[catch {exec cavget -list=L3:AM1:readyCC,L3:AM1:CurrentAI} result]} {
                APSMpReturn error "Unable to read current for L3:AM1: PCGUN_ModeSwitch: $result"
            }
            puts $result
            if {([lindex $result 0] == 1) && ([lindex $result 1] > 60)} {
                break
            }
            APSWaitWithUpdate -waitSeconds 5
        }
    }


    APSMpStep "LTP: Initialize Standardizing" -proc APSMpLTPStandardize 
    if [catch {APSMpLTPStandardize -particle $particle \
		 -energy $energy -conditioningTime $conditioningTime \
		 -B1 $standardizeB1 -restoreFile [file tail $SCRFile]} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error initiating LTP standardization.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Error initiating LTP standardization: $result"
        }
	#        APSMpReturn error "PCGUN_ModeSwitch: Error initiating LTP standardization: $result"
    }

    APSMpStep "LTP: Initialize Degaussing" -proc APSMpLTPDegauss 
    if [catch {APSMpLTPDegauss -degaussTime $conditioningTime} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error initiating LTP degaussing.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Error initiating LTP degaussing: $result"
        }
	#        APSMpReturn error "PCGUN_ModeSwitch: Error initiating LTP degaussing: $result"
    }

    APSMpStep "PTB: Turn On DCPS" -proc "APSMpPTBTurnOnDCPS"
    if [catch APSMpPTBTurnOnDCPS result] {
        if {[APSPEMTKDialog .warningDialog -text "Error turning on PTB DCPS.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Error turning on PTB DCPS: $result"
        }
	#        APSMpReturn error "Error turning on PTB DCPS: $result"
    }

    APSMpStep "PTB: Initiate Standardization" -proc "APSMpPTBStandardize"
    if [catch {APSMpPTBStandardize -energy $energy -restoreFile [file tail $SCRFile] \
                 -conditioningTime $conditioningTime} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error initiating PTB standardization.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Error initiating PTB standardization: $result"
        }
	#        APSMpReturn error "PCGUN_ModeSwitch: Error initiating PTB standardization: $result"
    }

    APSMpStep "PTB: Initiate Degaussing" -proc "APSMpPTBDegauss"
    if [catch {APSMpPTBDegauss -degaussTime $conditioningTime} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error initiating PTB degaussing.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Error initiating PTB degaussing: $result"
        }
	#        APSMpReturn error "PCGUN_ModeSwitch: Error initiating PTB degaussing: $result"
    }

    APSMpStep "L4,L5: Condition needed supplies" -proc APSMpLConditionPS
    if [catch {APSMpLConditionPS -arrayName $arrayName -configured 1 \
		 -SCRFile $SCRFile } conditioning] {
        if {[APSPEMTKDialog .warningDialog -text "Error conditioning Linac power supplies.\n$conditioning"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Error conditioning Linac power supplies: $conditioning"
        }
        set conditioning 1
	#	APSMpReturn error "PCGUN_ModeSwitch: $conditioning"
    }

    APSMpStep "${prefix}Suspend power control scripts" \
      -desc "Suspend power control script"
    if {[catch {APSLSuspendResumeRFPowerControllaws \
		  -klystronList "4 5" \
		  -mode suspend} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Unable to suspend L4 and L5 power controllaw.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Unable to suspend L4 and L5 power controllaw: $result"
        }
	#	APSMpReturn error "PCGUN_ModeSwitch: $result"
    }
    APSMpStep "${prefix}Suspend phase control loops" \
      -desc "Suspend phase control loops"
    if [catch {APSLINAC_SetPhaseControlMode \
		 -deviceList "4 5" \
		 -state manual} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to suspend L4 and L5 phase control loops.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Unable to suspend L4 and L5 phase control loops: $result"
        }
	#	APSMpReturn error "PCGUN_ModeSwitch: $result"
    }

    #    APSMpStep "${prefix}Restore PFN values" -desc "Restore PFN values"
    #    if {[catch {APSLRampPFNVoltage -klystronList "4 5" -rampToList $PFNvalues -steps 5} result]} {
    #	APSMpReturn error "PCGUN_ModeSwitch: $result"
    #    }

    APSMpStep "${prefix}Restore RF Power feedback setpoints" \
      -desc "Restore RF Power feedback setpoints"
    foreach sector "L4 L5" {
	if {([info exists ${sector}sledTrig]) && 
	    ([info exists ${sector}sledTrigVar])} {
	    if {[catch {exec cavput -list=[set ${sector}sledTrigVar]=[set ${sector}sledTrig]} result]} {
	    }
	}
    }
    foreach sector "L4 L5" {
	if {[catch {exec cavput -list=[set ${sector}AttnVar]=[set ${sector}AttnSetPoint]} result]} {
	}
    }

    APSMpStep "${prefix}Restore RF Phase feedback setpoints" \
      -desc "Restore RF Phase feedback setpoints"
    foreach sector "L4 L5" {
	catch {exec cavput -list=[set ${sector}PhaseVar]=[set ${sector}PhaseSetPoint]}
	catch {exec cavput -list=[set ${sector}PhaseAdjVar]=[set ${sector}PhaseAdjSetPoint]}
    }

    APSMpStep "${prefix}Restore PAR/LINAC timing values" \
      -desc "Restore PAR/LINAC timing values"
    catch {exec cavput -list=$ItLinacTrigVal=$ItLinacTrig}
    catch {exec cavput -list=$ItListTrigVal=$ItListTrig}

    APSMpStep "${prefix}Restore steering setpoints" \
      -desc "Restore steering setpoints"
    set tmpFile /tmp/[APSTmpString]
    APSAddToTempFileList $tmpFile
    if {[catch {exec sddsprocess $SCRFile $tmpFile \
		  -match=column,IsReadOnly=+n \
		  -match=column,Category=SteeringSetpoint \
		  -match=column,Beamline=L4,Beamline=L5,|,Beamline=LTP,|,Beamline=LTP1,|,Beamline=LTP2,| \
		  -match=col,ControlType=,! -match=col,ControlName=,!
	exec sddscasr -restore $tmpFile} result]} {
        APSPEMTKDialog .warningDialog -strings Continue -default 0 -text "Problem restoring SCR file: PCGUN_ModeSwitch: $result"
	catch {APSSendEMail -address soliday \
		 -subject "Problem restoring SCR file."  \
		 -message "Problem restore SCR file\nPCGUN_ModeSwitch\n$SCRFile\n$result"}
    }

    APSMpStep "${prefix}Resume power control scripts" \
      -desc "Resume power control script"
    if {[catch {APSLSuspendResumeRFPowerControllaws \
		  -klystronList "4 5" \
		  -mode resume} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Unable to suspend L4 and L5 power controllaws.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Unable to suspend L4 and L5 power controllaws: $result"
        }
	#	APSMpReturn error "PCGUN_ModeSwitch: $result"
    }
    if [catch {APSDevSend \
		 -group LinacKlystron \
		 -operation QueryPowerControlRunning \
		 -deviceList "4 5"} results] {
	APSMpReturn error "PCGUN_ModeSwitch: $results"
    }
    if {[catch {LMOCS_PowerControlLawSetup -deviceList "L4 L5" -mode low} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while setting L4 L5 power controllaws into low mode \n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: $result"
        }
    }
    foreach result $results sec "4 5" {
	if {$result != 1} {
	    if {[catch {exec cavput -list=L:L${sec}Stabilizer:SDDS.CMND=1} result]} {
	    }
	}
    }
    APSWaitWithUpdate -waitSeconds 2
    if [catch {APSDevSend \
		 -group LinacKlystron \
		 -operation QueryPowerControlRunning \
		 -deviceList "4 5"} results] {
	APSMpReturn error "PCGUN_ModeSwitch: $results"
    }
    set errorMessage ""
    foreach result $results sec "4 5" {
	if {$result != 1} {
	    append errorMessage "$sec "
	}
    }
    if {[llength $errorMessage]} {
	bell
        if {[APSPEMTKDialog .warningDialog -text "Unable to automatically resume sector(s) $errorMessage power control."] == 1} {
	    APSMpReturn error "PCGUN_ModeSwitch: Operation aborted by user"
	}
    }

    APSMpStep "${prefix}Resume phase loops" \
      -desc "Resume phase loops"
    if [catch {APSLINAC_SetPhaseControlMode \
		 -deviceList "4 5" \
		 -state autopresets} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to resume L4 and L5 phase control loops.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Unable to resume L4 and L5 phase control loops: $result"
        }
	#	APSMpReturn error "PCGUN_ModeSwitch: $result"
    }

    set conditionListDetailed [APSMpLConvertDeviceNames \
				 -operation StartConditioning \
				 -deviceList $conditionList]
    set conditionListDetailed [APSMpLConvertDetailedDeviceNames \
				 -operation StartConditioning \
				 -deviceList $conditionListDetailed \
				 -arrayName $arrayName]
    if $conditioning {
	if {[catch {APSMpLWaitForConditioningPS -deviceList $conditionListDetailed} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Error while waiting for power supplies to condition \n$result"] == 1} {
                APSMpReturn error "PCGUN_ModeSwitch: $result"
            }
        }
    }

    APSMpStep "LTP: Wait For Conditioning" -proc APSMpLTPWaitForConditioning 
    if [catch {APSMpLTPWaitForConditioning} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error waiting for LTP conditioning.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Error waiting for LTP conditioning: $result"
        }
	#        APSMpReturn error "PCGUN_ModeSwitch: Error waiting for LTP conditioning: $result"
    }

    if {$standardizeB1} {
        if [catch {APSDevSend \
                     -releaseLinks 1 \
                     -group LinacPS \
                     -operation SetCurrent \
                     -deviceList L3:AM1 \
                     -valueList 0 \
                     -timeout 0} result] {
            APSMpReturn error "PCGUN_ModeSwitch: $result"
        }
        set try 30
        while {$try >= 0} {
            APSWaitWithUpdate -waitSeconds 1
            if {[catch {exec cavget -list=L3:AM1:CurrentAI} result]} {
                APSMpReturn error "Unable to read current for L3:AM1: PCGUN_ModeSwitch: $result"
            }
            if {$result <= 3} {
                break
            }
            incr try -1
        }
        if {[catch {APSDevSend \
                      -group LinacPS \
                      -operation TurnOff \
                      -deviceList L3:AM1} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Unable turn off L3:AM1.\nPCGUN_ModeSwitch: $result"] == 1} {
                APSMpReturn error "Unable turn off L3:AM1: PCGUN_ModeSwitch: $result"
            }
        }
    }


    APSMpStep "PTB: Wait For Conditioning" -proc "APSMpPTBWaitForConditioning"
    if [catch {APSMpPTBWaitForConditioning} result] {
        if {[APSPEMTKDialog .warningDialog -text "Error waiting for PTP conditioning.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Error waiting for PTP conditioning: $result"
        }
	#        APSMpReturn error "PCGUN_ModeSwitch: Error waiting for PTB conditioning: $result"
    }


    APSMpStep "${prefix}Restore main and steering power supply setpoints" \
      -desc "Restore main and steering power supply setpoints"
    set tmpFile /tmp/[APSTmpString]
    APSAddToTempFileList $tmpFile
    if {[catch {exec sddsprocess $SCRFile $tmpFile \
		  -match=column,IsReadOnly=+n \
		  -match=column,Category=MainPS,Category=SteeringPS,| \
		  -match=column,Beamline=L3,Beamline=L4,|,Beamline=L5,|,Beamline=LTP,|,Beamline=LTP1,|,Beamline=LTP2,|,Beamline=PTB1,|,Beamline=PTB2,|,Beamline=PTB3,| \
		  -match=col,ControlType=,! -match=col,ControlName=,!
	exec sddscasr -restore $tmpFile} result]} {
        APSPEMTKDialog .warningDialog -strings Continue -default 0 -text "Problem restoring SCR file: PCGUN_ModeSwitch: $result"
	catch {APSSendEMail -address soliday \
		 -subject "Problem restoring SCR file."  \
		 -message "Problem restore SCR file\PCGUN_ModeSwitch\n$SCRFile\n$result"} 
	
    }

    APSMpStep "${prefix}Open gate valves" -desc "Open gate valves"
    if [catch {APSRFGUN_OpenCloseGateValve \
		 -deviceList "L1PG1GV2" \
		 -value Open \
		 -group LinacValves} result] {
        if {[APSPEMTKDialog .warningDialog -text "Gate valves failed to open."] == 1} {
	    APSMpReturn error "PCGUN_ModeSwitch: $result"
	}
    }

    APSMpStep "${prefix}Open shutter 4" -desc "Open shutter 4"
    if [catch {APSDevSend \
		 -group LinacLaser \
		 -operation OpenLRShutter \
		 -deviceList "4"} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to open shutter 4.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Unable to open shutter 4: $result"
        }
	#	APSMpReturn error "PCGUN_ModeSwitch: $result"
    }

    APSWaitWithUpdate -waitSeconds 10
    APSMpStep "${prefix}Check that the charge in the Linac is sufficient" \
      -desc "Check that the charge in the Linac is sufficient"
    set i 0
    while {$i == 0} {
	pv getw L5:P4:BPM
	if {(${L5:P4:BPM} < .002)} {
	    bell
            set i [APSPEMTKDialog .warningDialog -strings {Continue Ignore "Abort Procedure"} -text "L5:P4:BPM is less than .002. Please adjust"]
	    if {$i == 2} {
		APSMpReturn error "PCGUN_ModeSwitch: Aborted by operator"
	    }
	} else {
	    set i 1
	}
    }

    APSMpStep "${prefix}Run BPM Timing Scan" \
      -desc "Run BPM Timing Scan"
    global LI:DIAG:autoTimingNowMI
    if {[pv linkw LI:DIAG:autoTimingNowMI LI:DIAG:autoTimingNowMI]} {
	APSMpReturn error "PCGUN_ModeSwitch: $return"
    }
    set LI:DIAG:autoTimingNowMI "Scan & Set"
    if {[pv putw LI:DIAG:autoTimingNowMI]} {
	APSMpReturn error "PCGUN_ModeSwitch: $return"
    }
    if {$beamTargetSCR == "PAR"} {
        # do LTP timing scan 
        APSLinkToDevicePVs -fileList /home/helios/oagData/deviceConfig/par/LTPBPMOps.pvTable
        set supportedDevList [APSDevSend -releaseLinks 0  -group LTPBPM -operation TurnSetPeakDelayOn]
        APSDevSend -group LTPBPM -operation TurnSetPeakDelayOn -deviceList $supportedDevList
        APSDevSend -group LTPBPM -operation StartTimingScan -deviceList $supportedDevList
    }
    while {1} {
	APSWaitWithUpdate -waitSeconds 10
	if {[pv getw LI:DIAG:autoTimingNowMI]} {
	    APSMpReturn error "PCGUN_ModeSwitch: $return"
	}
	if {[string compare ${LI:DIAG:autoTimingNowMI} "Idle"] == 0} {
	    break
	}
	incr i 10
	APSMpStep "Waiting for BPM scan ($i seconds)" \
	  -desc "Wait for BPM scan"
    }

    APSMpStep "${prefix}Resume Linac ControlLaws" \
      -desc "Resume Linac ControlLaws"
    if [catch {APSMpLSuspendResumeRunControl \
		 -value "Resume" \
		 -name "LinacControlLaw" \
		 -group "RunControlGroup" \
		 -deviceList "X"} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to resume X Linac controllaw.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Unable to resume X Linac controllaw: $result"
        }
	#	APSMpReturn error "PCGUN_ModeSwitch: $result"
    }
    if [catch {APSMpLSuspendResumeRunControl \
		 -value "Resume" \
		 -name "LinacControlLaw" \
		 -group "RunControlGroup" \
		 -deviceList "Y"} result] {
        if {[APSPEMTKDialog .warningDialog -text "Unable to resume Y Linac controllaw.\n$result"] == 1} {
            APSMpReturn error "PCGUN_ModeSwitch: Unable to resume Y Linac controllaw: $result"
        }
	#	APSMpReturn error "PCGUN_ModeSwitch: $result"
    }

    APSMpStep "${prefix}Wait 30 seconds" \
      -desc "Wait 30 seconds"
    APSWaitWithUpdate -waitSeconds 30

    if {$beamTargetSCR == "PAR"} {
	
        if {($LTPcontLM != "L4") && ($LTPcontLM != "L5")} {
            bell
            set LTPcontLM [APSMultipleChoice [APSUniqueName .] -modal 1 \
                             -question "You didn't specify which modulator to use for LTP control and it could not be determined automatically.  Please choose one." \
                             -labelList {L4 L5 "Abort Procedure"} \
                             -returnList {L4 L5 abort}]
            if {($LTPcontLM == "abort")} {
                APSMpReturn error "PCGUN_ModeSwitch: user would not specify LTP controllaw linac sector."
            }
        }

	APSMpStep "${prefix}Suspend power control script for $LTPcontLM" \
	  -desc "Suspend power control script for L4 or L5"
	if {[catch {APSLSuspendResumeRFPowerControllaws \
		      -klystronList [string range $LTPcontLM end end] \
		      -mode suspend} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Unable to suspend $LTPcontLM power controllaw.\n$result"] == 1} {
                APSMpReturn error "PCGUN_ModeSwitch: Unable to suspend $LTPcontLM power controllaw: $result"
            }
	    #	    APSMpReturn error "PCGUN_ModeSwitch: $result"
	}

	APSMpStep "${prefix}Resume LTP ControlLaws" \
	  -desc "Resume LTP ControlLaws"
	if [catch {APSMpLSuspendResumeRunControl \
		     -value "Resume" \
		     -name "LTPControlLaw" \
		     -group "RunControlGroup" \
		     -deviceList "X"} result] {
            if {[APSPEMTKDialog .warningDialog -text "Unable to resume X LTP controllaw.\n$result"] == 1} {
                APSMpReturn error "PCGUN_ModeSwitch: Unable to resume X LTP controllaw: $result"
            }
	    #	    APSMpReturn error "PCGUN_ModeSwitch: $result"
	}
	if [catch {APSMpLSuspendResumeRunControl \
		     -value "Resume" \
		     -name "LTPControlLaw" \
		     -group "RunControlGroup" \
		     -deviceList "Y"} result] {
            if {[APSPEMTKDialog .warningDialog -text "Unable to resume Y LTP controllaw.\n$result"] == 1} {
                APSMpReturn error "PCGUN_ModeSwitch: Unable to resume Y LTP controllaw: $result"
            }
	    #	    APSMpReturn error "PCGUN_ModeSwitch: $result"
	}

	APSMpStep "PAR: Warm Up Pulsed PS"
	set wukID [APSMpParallel -procedure "APSMpWarmupKickers -kickerList {P1IK P2IK P4EK}" -mode Automatic]
	set wusID [APSMpParallel -procedure "APSMpTurnOnSeptum" -mode Automatic]
	
	set wukResult [APSMpJoin $wukID]
	set wusResult [APSMpJoin $wusID]
	
	APSMpStep "PAR: Turn On Kicker HV"
	if [catch {exec cavput -list=P1IK,P2IK,P4EK -list=:OnBO=ON } result] {
            if {[APSPEMTKDialog .warningDialog -text "Unable to turn on Kicker HV.\n$result"] == 1} {
                APSMpReturn error "PCGUN_ModeSwitch: Unable to turn on Kicker HV: $result"
            }
	    #	    APSMpReturn error "PCGUN_ModeSwitch: Error sending on signals: $result"
	}

    } else {

	APSMpStep "${prefix}Suspend Linac ControlLaws" \
	  -desc "Suspend Linac ControlLaws"
	if [catch {APSMpLSuspendResumeRunControl \
		     -value "Suspend" \
		     -name "LinacControlLaw" \
		     -group "RunControlGroup" \
		     -deviceList "X Y"} result] {
            if {[APSPEMTKDialog .warningDialog -text "Unable to suspend X and Y Linac controllaws.\n$result"] == 1} {
                APSMpReturn error "PCGUN_ModeSwitch: Unable to suspend X and Y Linac controllaws: $result"
            }
	    #	    APSMpReturn error "PCGUN_ModeSwitch: $result"
	}
    }

    APSMpStep "Done"
    APSWaitWithUpdate -waitSeconds 3

    APSMpReturn ok
}
