
#
# Linac Modulator Control System PEM.  This program runs through the startup
# and shutdown procedures for the L1, L2, L3, L4, and L5 sectors.  For startup
# it runs through Seq #1, Seq #2, Dump Switchs, Seq #3, Rdy to Pulse, HVPS, 
# LLRF, and finally ramps the PFN Voltage to 30.0kV.

proc LMOCS_Modulator_StartupInfo {} {

    return "Linac Modulator Control System PEM.  This program runs through the startup\
procedures for the L1, L2, L3, L4, and L5 sectors.  It runs through Seq \#1, Seq \#2,\
Dump Switchs, Seq \#3, Rdy to Pulse, HVPS,\
LLRF, and finally ramps the PFN Voltage to SCR value."

}

proc LMOCS_Modulator_ShutdownInfo {} {

    return "Linac Modulator Control System PEM.  This program runs through the shutdown\
procedures for the L1, L2, L3, L4, L5 and L6 sectors.  It ramps down the PFN voltage to 0kV.\
Turns the LLRF, HVPS, Rdy to Pulse, Seq \#3, Dump Switches, and Seq \#2 off."

}

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

proc LMOCS_Modulator_ShutdownDialog {args} {
    set frame ""
    APSStrictParseArguments {frame}
    pack [label $frame.label -text "Select LINAC sections\nto turn off"]

    APSCheckButtonFrame .selectSectors -parent $frame -label "" \
      -variableList {LMOCS_Modulator_Shutdown(L1) LMOCS_Modulator_Shutdown(L2) LMOCS_Modulator_Shutdown(L3) LMOCS_Modulator_Shutdown(L4) LMOCS_Modulator_Shutdown(L5) LMOCS_Modulator_Shutdown(L6)} \
      -buttonList {K1 K2 K3 K4 K5 K6} \
      -allNone 1 \
      -packOption {-side top} \
      -orientation horizontal
}

proc LMOCS_Modulator_Startup {args} {
    set SCRFile ""
    set sectors "L1 L2 L3 L4 L5"
    foreach sector $sectors {
        set $sector 0
        set ${sector}PFN 0
    }
    APSParseArguments {L1 L2 L3 L4 L5 SCRFile}
    global execMode

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

    if {[catch {APSLinkToLINACPVs} result]} {
        APSMpReturn error "LMOCS_Modulator_Startup: $result"
    }
    
    global APSMpLControlPS
    
    set arrayName APSMpLControlPS
    
    APSLGenericPSArraySetup -arrayName $arrayName -SCRFile $SCRFile

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

    set oldExecMode $execMode
    set sectorsSelected 0
    while {!$sectorsSelected} {
        APSMpStep init -promptDialog \
          "APSLGenericPSDialog -packProc LMOCS_Modulator_StartupDialog -chooseSCR 1 -arrayName $arrayName -frame " -vars {L1 L2 L3 L4 L5}
        
        foreach sector $sectors {
            if {[set $sector]} {
                incr sectorsSelected
            }
        }
        if {!$sectorsSelected} {
            tk_dialog2 .warningDialog "Warning Message" "No sectors have been selected\nSelect again" warning -1 Ok
            set execMode "Manual"
        }
    }
    set execMode $oldExecMode

    set SCRFile $APSMpLControlPS(Filename)
    if {![file exists $SCRFile]} {
        APSMpReturn error "LMOCS_Modulator_Startup: No SCR file selected"
    }
    if {[catch {exec sdds2stream $SCRFile -parameter=SnapshotDescription -page=1 -noquotes} results]} {
        APSMpReturn error "LINAC_Modulator_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 "LINAC_Modulator_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 "LINAC_Modulator_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/SCRFilterFile -match=ControlName -pipe=out | sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
        APSMpReturn error "LMOCS_Modulator_Startup: Invalid SCR file"
    }
    set L6PFN 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-6\]: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 {"L-K5:LLRF:SD:Fwd_PkPwrRemoteM" == $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"
        }
    }
    APSParseArguments {L1PFN L2PFN L3PFN L4PFN L5PFN L6PFN}

    foreach sector "L1 L3 L4" {
        if {[set $sector]} {
            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 "LMOCS_Modulator_Startup: Value for sector $sector PFN is [set ${sector}PFN] (not valid)"
                }
            }
        }
    }
    foreach sector "L4 L5" {
        if {[set $sector]} {
            if {([info exists ${sector}sledTrig] != 1) || ([info exists ${sector}sledTrigVar] != 1)} {
                APSMpReturn error "LMOCS_Modulator_Startup: Value for sector $sector sled trig does not exist"
            }
        }
    }
    foreach sector $sectors {
        if {[set $sector]} {
            if {$sector == "L2"} {
                APSMpStep "${prefix}TurnOnK400 $sector" -desc "Turn on selected sector"
                set id$sector [APSMpParallel \
                                 -procedure "TurnOnK400 -klystron K2 -SCRFile $SCRFile" \
                                 -mode $execMode]
            } elseif {$sector == "L5"} {
                APSMpStep "${prefix}TurnOnK400 $sector" -desc "Turn on selected sector"
                set id$sector [APSMpParallel \
                                 -procedure "TurnOnK400 -klystron K5 -SCRFile $SCRFile" \
                                 -mode $execMode]
            } else {
                APSMpStep "${prefix}LMOCS_TurnOn $sector" -desc "Turn on selected sector" -proc "LMOCS_TurnOn"
                if {$sector == "L4"} {
                    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] -SCRFile \"$SCRFile\"" \
                                     -mode $execMode]
                } else {
                    set id$sector [APSMpParallel \
                                     -procedure "LMOCS_TurnOn -sector $sector -PFNFinalValue [set ${sector}PFN] -attnSetPoint [set ${sector}AttnSetPoint] -attnPVName [set ${sector}AttnVar] -SCRFile \"$SCRFile\"" \
                                     -mode $execMode]
                }
            }
        }
    }
    #    APSMpAbort all -onError 1
    foreach sector $sectors {
        if {[set $sector]} {
            if {($sector == "L2") || ($sector == "L5")} {
                if {[catch {APSMpJoin [set id$sector]} result]} {
                    if {[APSPEMTKDialog .warningDialog -text "Error encountered with turning on modulator $sector: $result"] == 1} {
                        APSMpReturn error "LMOCS_Modulator_Startup: Joining TurnOnK400 $sector: $result"
                    }
                }
            } else {
                if {[catch {APSMpJoin [set id$sector]} result]} {
                    if {[APSPEMTKDialog .warningDialog -text "Error encountered with turning on modulator $sector: $result"] == 1} {
                        APSMpReturn error "LMOCS_Modulator_Startup: Joining LMOCS_TurnOn $sector: $result"
                    }
                }
            }
        }
    }

    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\nLMOCS_Modulator_Startup: $result"] == 1} {
            APSMpReturn error "Modulator Phase Control not reset: LMOCS_Modulator_Startup: $result"
        }
    }

    APSMpReturn ok
}

proc LMOCS_Modulator_Shutdown {args} {
    set sectors "L1 L2 L3 L4 L5 L6"
    foreach sector $sectors {
        set $sector 0
    }
    set includeFilament 0
    APSStrictParseArguments {L1 L2 L3 L4 L5 L6 includeFilament}
    global execMode
    
    if {$execMode == "Manual"} {
        set prefix "Press Continue to "
    } else {
        set prefix ""
    }
    
    if {[catch {APSLinkToLINACPVs} result]} {
        APSMpReturn error "LMOCS_Modulator_Shutdown: $result"
    }
    
    set oldExecMode $execMode
    set sectorsSelected 0
    while {!$sectorsSelected} {
        APSMpStep init -promptDialog \
          "LMOCS_Modulator_ShutdownDialog -frame " -vars {L1 L2 L3 L4 L5 L6}
        
        foreach sector $sectors {
            if {[set $sector]} {
                incr sectorsSelected
            }
        }
        if {!$sectorsSelected} {
            tk_dialog2 .warningDialog "Warning Message" "No sectors have been selected\nSelect again" warning -1 Ok
            set execMode "Manual"
        }

    }
    set execMode $oldExecMode

    foreach sector $sectors {
        if {[set $sector]} {
            if {$sector == "L2"} {
                APSMpStep "${prefix}TurnOffK400 $sector" -desc "Turn off selected sector"
                set id$sector [APSMpParallel \
                                 -procedure "TurnOffK400 -klystron K2 -includeFilament $includeFilament -noDialog 1" \
                                 -mode $execMode]

            } elseif {$sector == "L5"} {
                APSMpStep "${prefix}TurnOffK400 $sector" -desc "Turn off selected sector"
                set id$sector [APSMpParallel \
                                 -procedure "TurnOffK400 -klystron K5 -includeFilament $includeFilament -noDialog 1" \
                                 -mode $execMode]

            } else {
                APSMpStep "${prefix}LMOCS_TurnOff $sector" -desc "Turn off selected sector" -proc "LMOCS_TurnOff"
                set id$sector [APSMpParallel \
                                 -procedure "LMOCS_TurnOff -sector $sector" \
                                 -mode $execMode]
            }
        }
    }
    #    APSMpAbort all -onError 1
    foreach sector $sectors {
        if {[set $sector]} {
            if {($sector == "L2") || ($sector == "L5")} {
                if {[catch {APSMpJoin [set id$sector]} result]} {
                    if {[APSPEMTKDialog .warningDialog -text "Error encountered while turning off modulator $sector \n $result"] == 1} {
                        APSMpReturn error "LMOCS_Modulator_Shutdown: Joining TurnOffK400 $sector: $result"
                    }
                }
            } else {
                if {[catch {APSMpJoin [set id$sector]} result]} {
                    if {[APSPEMTKDialog .warningDialog -text "Error encountered while turning off modulator $sector \n $result"] == 1} {
                        APSMpReturn error "LMOCS_Modulator_Shutdown: Joining LMOCS_TurnOff $sector: $result"
                    }
                }
            }
        }
    }
    APSMpReturn ok
}

proc LMOCS_TurnOn {args} {
    APSMpStep init
    if {![llength [info commands blt::bgexec]]} {
        package require BLT
        global blt_library
        lappend auto_path $blt_library
    }
    global status
    
    set sledTrigVar ""
    set sledTrig ""
    set sector ""
    set PFNFinalValue ""
    set attnSetPoint ""
    set attnPVName ""
    set resumePCS 1
    set SCRFile ""
    APSParseArguments {sector attnSetPoint attnPVName sledTrig sledTrigVar resumePCS SCRFile}
    global execMode
    if {$execMode == "Manual"} {
        set prefix "Press Continue to "
    } else {
        set prefix ""
    }

    switch -exact -- $sector {
        L1 {set device 1 ; set attenLevel 4.55 ; set PFNFinalValue 31}
        L3 {set device 3 ; set attenLevel 3.0 ; set PFNFinalValue 33} 
        L4 {set device 4 ; set attenLevel 4.0 ; set PFNFinalValue 34} 
        L6 {set device 6 ; set attenLevel 3.37 ; set PFNFinalValue 0} 
        default {APSMpReturn error "LMOCS_TurnOn: invalid sector $sector"}
    }
    APSParseArguments {PFNFinalValue}
    if {![llength $PFNFinalValue]} {
        APSMpReturn error "LMOCS_TurnOn: no value passed for final voltage of PFN"
    }

    set style new
    
    if {[catch {APSLinkToLINACPVs} result]} {
        APSMpReturn error "LMOCS_TurnOn: $result"
    }

    APSMpStep "${prefix}Check if modulator $sector is already on" -desc "Check if modulator is already on"
    set alreadyOn 1
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation QueryHVPSOn \
                  -deviceList $device} result]} {
        APSMpReturn error "LMOCS_TurnOn: $result"
    }
    if {!$result} {
        set alreadyOn 0
    }

    if {[catch {exec cavget -list=${sector}:DA:AcisEnableBI,${sector}:LL:lockPersonnelAccBI,${sector}:DA:readyBI -num -pend=20} acisState]} {
        APSMpReturn error "LMOCS_TurnOn:: $acisState"
    }
    if {([lindex $acisState 0] == 0)} {
        if {[APSPEMTKDialog .warningDialog \
               -text "Linac acis needs to be reset.\n$sector LMOCS startup on hold till then.\n"] == 1} {
            APSMpReturn error "LMOCS_TurnOn: Linac acis needs to reset."
        }
    }
    if {([lindex $acisState 1] == 0) || ([lindex $acisState 2] == 0)} {
        catch {exec cavput -list=${sector}:DA:AcisResetBO=1}
        after 1000
        catch {exec cavput -list=${sector}:DA:resetBO=1}
        after 1000
        catch {exec cavput -list=${sector}:DA:AcisResetBO=1}
        after 1000
        catch {exec cavput -list=${sector}:DA:resetBO=1}
        after 5000
        if {[catch {exec cavget -list=${sector}:LL:lockPersonnelAccBI,${sector}:DA:readyBI -num -pend=20} acisState]} {
            APSMpReturn error "LMOCS_TurnOn:: $acisState"
        }
        if {($sector == "L1") || ($sector == "L2") || ($sector == "L4")} {
            if {([lindex $acisState 0] == 0)} {
                if {[APSPEMTKDialog .warningDialog \
                       -text "$sector RF amp not ready and the PEM was unable to reset it properly. Please reset RF amp before continuing"] == 1} {
                    APSMpReturn error "LMOCS_TurnOn: $sector RF amp not ready and the PEM was unable to reset it properly."
                }             
            }
        } else {
            if {([lindex $acisState 0] == 0) || ([lindex $acisState 1] == 0)} {
                if {[APSPEMTKDialog .warningDialog \
                       -text "$sector RF amp not ready and the PEM was unable to reset it properly. Please reset RF amp before continuing"] == 1} {
                    APSMpReturn error "LMOCS_TurnOn: $sector RF amp not ready and the PEM was unable to reset it properly."
                }             
            }
        }
        
    }
    
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation ReadPFNVoltage \
                  -deviceList $device} result]} {
        APSMpReturn error "LMOCS_TurnOn: $result"
    }
    if {($result < [expr $PFNFinalValue - 2]) || ($result > [expr $PFNFinalValue + 2])} {
        set alreadyOn 0
    }
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation QueryLLRFOn \
                  -deviceList $device} result]} {
        APSMpReturn error "LMOCS_TurnOn: $result"
    }
    if {!$result} {
        set alreadyOn 0
    }
    if {!$alreadyOn} {
        APSMpStep "${prefix}Suspend power control scripts for sector $sector" -desc "Suspend power control script"
        if {[catch {APSLSuspendResumeRFPowerControllaws -klystronList $device -mode suspend} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Error while suspending power control scripts for sector $sector \n$result"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
        }

        APSMpStep "${prefix}Check $sector Attenuation is above $attenLevel" -desc "Check if attenuation is above a certain level"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ReadRFAttenuatorPosition \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }

        if {$result < $attenLevel} {
            APSWaitWithUpdate -waitSeconds 3
            APSMpStep "${prefix}Increase $sector attenuation to $attenLevel" -desc "Increase attenuation if needed"
            if {[catch {APSLINAC_IncreaseAttnCtrl -deviceList $device -minAttenuation $attenLevel} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while increasing $sector attenuation to $attenLevel \n$result"] == 1} {
                    APSMpReturn error "LMOCS_TurnOn: $result"
                }
            }
        }

        
        # Do a lot of checks to find out if we can initiate sequence #1
        APSMpStep "${prefix}Check for emergency off state in $sector" -desc "Check for emergency shutdown state"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryEmergencyOff \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Emergency Shut Down detected in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: Emergency Shut Down detected in sector $sector"
            }
        }
        
        APSMpStep "${prefix}Check if AC control power is on in $sector" -desc "Check if AC control power is on"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryACControlPowerOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: AC Control Power is not on in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: AC Control Power is not on in sector $sector"
            }
        }
        APSMpStep "${prefix}Check for water flow problems in $sector" -desc "Check for water flow problems for new style modulators"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryKlyCollectorWaterFlowOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Klystron Collector Water Flow problem in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: Klystron Collector Water Flow problem in sector $sector"
            }
        }
        
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryKlyBodyWaterFlowOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Klystron Body Water Flow problem in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: Klystron Body Water Flow problem in sector $sector"
            }
        }
        
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryKlyMagnetWaterFlowOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Magnet Water Flow problem in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: Magnet Water Flow problem in sector $sector"
            }
        }
        
        APSMpStep "${prefix}Check if init sequence is ready in $sector" -desc "Check if init sequence is ready for new style modulators"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryModulatorInitSeqDone \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Init Sequence is not ready in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: Init Sequence is not ready in sector $sector"
            }
        }
        APSMpStep "${prefix}Check if 15 minuite timer is done in $sector" -desc "Check if 15 minute timer is done for new style modulators"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation Query15MinuteTimerDone \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation Query15MinuteTimer \
                          -deviceList $device} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            if {$result} {
                #15 timer already running
                APSMpStep "${prefix}15 minute modulator timer in $sector already running"
            } else {
                # Start 15 minute timer
                APSMpStep "${prefix}Start 15 minute timer in $sector" -desc "Start 15 minute timer if needed for new style modulators"
                if {[catch {APSDevSend \
                              -group LinacKlystron \
                              -operation Reset15MinuteTimer \
                              -deviceList $device -releaseLinks 1} result]} {
                    APSMpReturn error "LMOCS_TurnOn: $result"
                }
                after 510
                if {[catch {APSDevSend \
                              -group LinacKlystron \
                              -operation Toggle15MinuteTimer \
                              -deviceList $device -releaseLinks 1} result]} {
                    APSMpReturn error "LMOCS_TurnOn: $result"
                }
            }
            APSMpStep "${prefix}Wait for 15 minute timer to complete in $sector" -desc "Wait for 15 minute timer to complete if needed for new style modulators"
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation Query15MinuteTimerDone \
                          -deviceList $device \
                          -returnPVList 1} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable cawait \
                          -interval=5 \
                          -waitFor=$result,equalto=1 \
                          -timeLimit=960} result]} {
                if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Unable to initiate sequence \#1 in sector $sector: $result"] == 1} {
                    APSMpReturn error "LMOCS_TurnOn: Unable to initiate sequence \#1 in sector $sector: $result"
                }
            }
        }

        APSMpStep "${prefix}Check if Thyratron heater is on in $sector" -desc "Check if Thyratron heater is on"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryThyratronHeaterOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Thyratron Heater is not on in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: Thyratron Heater is not on in sector $sector"
            }
        }
        
        APSMpStep "${prefix}Check if ion pump is within limits in $sector" -desc "Check if ion pump is withing limits for new style modulators"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryIonPumpCurrentOK \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Ion Pump current is outside limits in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: Ion Pump current is outside limits in sector $sector"
            }
        }
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryIonPumpVoltageOK \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Ion Pump voltage is outside limits in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: Ion Pump voltage is outside limits in sector $sector"
            }
        }

        APSMpStep "${prefix}Check if focus magnets are on in $sector" -desc "Check if the focus magents are on for new style modulators"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryKlyMagnetsOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            APSMpStep "${prefix}Turn focus magnets on in $sector" -desc "Turn on the focus magnets if needed"
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation ResetKlystronMagnets \
                          -deviceList $device -releaseLinks 1} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            after 510
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation ToggleKlystronMagnets \
                          -deviceList $device -releaseLinks 1} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation QueryKlyMagnetsOn \
                          -deviceList $device \
                          -returnPVList 1} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable cawait \
                          -interval=1 \
                          -waitFor=$result,equalto=1 \
                          -timeLimit=10} result]} {
                if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Unable to start focus magnets in sector $sector: $result"] == 1} {
                    APSMpReturn error "LMOCS_TurnOn: Unable to start focus magnets in sector $sector: $result"
                }
            }
        }

        APSMpStep "${prefix}Check if Dump switch is on in $sector" -desc "Check if the Dump switch is on for new style modulators"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryDumpSwitchOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            APSMpStep "${prefix}Turn on Dump switch in $sector" -desc "Turn on the Dump switch if needed"
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation ResetDumpSwitch \
                          -deviceList $device -releaseLinks 1} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            after 510
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation ToggleDumpSwitch \
                          -deviceList $device -releaseLinks 1} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation QueryDumpSwitchOn \
                          -deviceList $device \
                          -returnPVList 1} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable cawait \
                          -interval=1 \
                          -waitFor=$result,equalto=1 \
                          -timeLimit=10} result]} {
                if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Unable to turn dump switches on in sector $sector: $result"] == 1} {
                    APSMpReturn error "LMOCS_TurnOn: Unable to turn dump switches on in sector $sector: $result"
                }
            }
        } 

        APSMpStep "${prefix}Check if Klystron temperature is OK in $sector" -desc "Check the Klystron temperature for new style modulators"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryKlyMagnetTempLimitOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: The Klystron magnet temperature is outside limits in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: The Klystron magnet temperature is outside limits in sector $sector"
            }
        }
        
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryKlyCollectorTempLimitOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: The Klystron collector temperature is outside limits in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: The Klystron collector temperature is outside limits in sector $sector"
            }
        }
        
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryKlyBodyInLimitOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: The Klystron body temperature is outside limits in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: The Klystron body temperature is outside limits in sector $sector"
            }
        }
        
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryKlyBodyOutLimitOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: The Klystron body temperature is outside limits in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: The Klystron body temperature is outside limits in sector $sector"
            }
        }
        
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryKlyBodyDifferenceLimitOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: The Klystron body temperature is outside limits in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: The Klystron body temperature is outside limits in sector $sector"
            }
        }
        
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryKlyOilTankTempLimitOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: The Klystron oil temperature is outside limits in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: The Klystron oil temperature is outside limits in sector $sector"
            }
        }
        
        APSMpStep "${prefix}Check if Modulator passes safety conditions in $sector" -desc "Check if the modulator passes safety conditions for new style modulators"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryACISPermitOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: The ACIS Permit check failed in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: The ACIS Permit check failed in sector $sector"
            }
        }
        if {$device == "6"} {
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation QueryPSCabDoorAndGndStickOn \
                          -deviceList $device} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            if {!$result} {
                if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: The PS Door Hook check failed in sector $sector"] == 1} {
                    APSMpReturn error "LMOCS_TurnOn: The PS Door Hook check failed in sector $sector"
                }
            }
        }
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryPFNDoorAndGndStickLatchOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: The PFN Door Hook check failed in sector $sector"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: The PFN Door Hook check failed in sector $sector"
            }
        }

        APSMpStep "${prefix}Check if ready to pulse in $sector" -desc "Check if Ready to Pulse"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryReadyToPulseOn \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {!$result} {
            APSMpStep "${prefix}Set Ready to Pulse On in $sector" -desc "Set Ready to Pulse on if needed"
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation ResetReadyToPulse \
                          -deviceList $device -releaseLinks 1} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            after 510
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation ToggleReadyToPulse \
                          -deviceList $device -releaseLinks 1} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation QueryReadyToPulseOn \
                          -deviceList $device \
                          -returnPVList 1} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable cawait \
                          -interval=1 \
                          -waitFor=$result,equalto=1 \
                          -timeLimit=10} result]} {
                if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Unable to turn Ready to Pulse on in $sector: $result"] == 1} {
                    APSMpReturn error "LMOCS_TurnOn: Unable to turn Ready to Pulse on: $result"
                }
            }
        }

        set loop 1
        while {$loop} {
            APSMpStep "${prefix}Check if PS Enabled in $sector" -desc "Check if PS is enabled for new style modulators"
            while {1} {
                if {[catch {APSDevSend \
                              -group LinacKlystron \
                              -operation QueryPSEnableOn \
                              -deviceList $device} result]} {
                    APSMpReturn error "LMOCS_TurnOn: $result"
                }
                if {!$result} {
                    APSMpStep "${prefix}Enable PS in $sector" -desc "Enable PS if needed"
                    if {[catch {APSDevSend \
                                  -group LinacKlystron \
                                  -operation ResetPowerSupplyEnable \
                                  -deviceList $device -releaseLinks 1} result]} {
                        APSMpReturn error "LMOCS_TurnOn: $result"
                    }
                    after 510
                    if {[catch {APSDevSend \
                                  -group LinacKlystron \
                                  -operation TogglePowerSupplyEnable \
                                  -deviceList $device -releaseLinks 1} result]} {
                        APSMpReturn error "LMOCS_TurnOn: $result"
                    }
                    if {[catch {APSDevSend \
                                  -group LinacKlystron \
                                  -operation QueryPSEnableOn \
                                  -deviceList $device \
                                  -returnPVList 1} result]} {
                        APSMpReturn error "LMOCS_TurnOn: $result"
                    }
                    if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable cawait \
                                  -interval=1 \
                                  -waitFor=$result,equalto=1 \
                                  -timeLimit=10} result]} {
                        if {[APSPEMTKDialog .warningDialog -text "Unable to enable PS in Modulator sector $sector"] == 1} {
                            APSMpReturn error "LMOCS_TurnOn: Unable to enable PS in Modulator sector $sector"
                        }
                    } else { 
                        break
                    }
                } else {
                    break
                }
            }
            
            APSMpStep "${prefix}Check if HVPS is on in $sector" -desc "Check if HVPS is on for new style modulators"
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation QueryHVPSOn \
                          -deviceList $device} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            if {!$result} {
                set hvpsLoop 0
                while {1} {
                    APSMpStep "${prefix}Turn HVPS on in $sector" -desc "Turn on HVPS if needed"
                    if {[catch {APSDevSend \
                                  -group LinacKlystron \
                                  -operation ResetHVPS \
                                  -deviceList $device -releaseLinks 1} result]} {
                        APSMpReturn error "LMOCS_TurnOn: $result"
                    }
                    after 510
                    if {[catch {APSDevSend \
                                  -group LinacKlystron \
                                  -operation ToggleHVPS \
                                  -deviceList $device -releaseLinks 1} result]} {
                        APSMpReturn error "LMOCS_TurnOn: $result"
                    }
                    if {[catch {APSDevSend \
                                  -group LinacKlystron \
                                  -operation QueryHVPSOn \
                                  -deviceList $device \
                                  -returnPVList 1} result]} {
                        APSMpReturn error "LMOCS_TurnOn: $result"
                    }
                    if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable cawait \
                                  -interval=1 \
                                  -waitFor=$result,equalto=1 \
                                  -timeLimit=10} result]} {
                        #APSMpReturn error "LMOCS_TurnOn: Unable to turn HVPS on in sector $sector: $result"
                    } else {
                        break;
                    }
                    incr hvpsLoop
                    if {$hvpsLoop >= "4"} {
                        if {[APSPEMTKDialog .warningDialog -text "Unable to turn HVPS on in sector $sector"] == 1} {
                            APSMpReturn error "LMOCS_TurnOn: Unable to turn HVPS on in sector $sector"
                        }
                    }
                }
            }

            APSMpStep "${prefix}Check if vacuum is ok in $sector" -desc "Check if the vacuum is ok"
            set vacuumCheck 1
            while {$vacuumCheck} {
                set vacuumCheck 0
                set deviceTemp $device
                if {$device == "6"} {
                    set deviceTemp 3
                }

                if {$device == "1"} {
                    if {[catch {APScavget -list=L1:IC1:VacPermitM -num} result3]} {
                        return -code error "$result3"
                    }
                    set result 1
                    set result2 1
                } else {
                    if {[catch {APSDevSend \
                                  -group LinacKlystron \
                                  -operation QueryTWVacuumOk \
                                  -deviceList $deviceTemp} result]} {
                        APSMpReturn error "LMOCS_TurnOn: $result"
                    }
                    if {[catch {APSDevSend \
                                  -group LinacKlystron \
                                  -operation QueryBLVacuumOk \
                                  -deviceList $deviceTemp} result2]} {
                        APSMpReturn error "LMOCS_TurnOn: $result2"
                    }
                    set result3 1
                }
                if {(!$result) || (!$result2) || (!$result3)} {
                    set answer [APSPEMTKDialog .warningDialog -strings {Continue Ignore "Abort Procedure"} -text "Vacuum fault detected in sector $sector"]
                    if {$answer == 2} {
                        APSMpReturn error "LMOCS_TurnOn: Operation canceled due to vacuum fault"
                    }
                    if {$answer == 0} {
                        set vacuumCheck 1
                    }
                }
            }

            APSMpStep "${prefix}Check for VSWR trip in $sector" -desc "Check for a VSWR trip"
            set tripCheck 1
            while {$tripCheck} {
                set tripCheck 0
                if {[catch {APSDevSend \
                              -group LinacKlystron \
                              -operation QueryAllVSWROk \
                              -deviceList $device} result]} {
                    APSMpReturn error "LMOCS_TurnOn: $result"
                }
                if {!$result} {
                    APSMpStep "${prefix}Fix trip automatically in $sector" -desc "Fix trip"
                    if {[catch {APSDevSend \
                                  -group LinacKlystron \
                                  -operation MiscProtectionReset \
                                  -deviceList $device} result]} {
                        APSMpReturn error "LMOCS_TurnOn: $result"
                    }
                    if {[catch {APSDevSend \
                                  -group LinacKlystron \
                                  -operation QueryAllVSWROk \
                                  -deviceList $device \
                                  -returnPVList 1} result]} {
                        APSMpReturn error "LMOCS_TurnOn: $result"
                    }
                    if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable cawait \
                                  -interval=1 \
                                  -waitFor=$result,equalto=1.0 \
                                  -timeLimit=10} result]} {
                        set answer [APSPEMTKDialog .warningDialog -strings {Continue Ignore "Abort Procedure"} -text "VSWR trip detected in sector $sector."]
                        if {$answer == 2} {
                            APSMpReturn error "LMOCS_TurnOn: Operation canceled due to VSWR trip"
                        }
                        if {$answer == 0} {
                            set tripCheck 1
                        }
                    }
                }
            }
            


            APSMpStep "${prefix}Check PFN voltage in $sector" -desc "Check PFN voltage"
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation ReadPFNVoltage \
                          -deviceList $device} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            if {$result < 10} {
                
                APSMpStep "${prefix}Set PFN to 10kV in $sector" -desc "Increase PFN voltage to 10kV if needed"
                if {[catch {APSLRampPFNVoltage \
                              -klystronList $device \
                              -rampTo 10.0 -checkVacuum 1 \
                              -steps 1} result]} {
                    APSSetVarAndUpdate status $result
                    APSMpStep "${prefix}Turn off HVPS in $sector" -desc "If trip occurs turn off HVPS"
                    if {[catch {APSDevSend \
                                  -group LinacKlystron \
                                  -operation QueryHVPSOn \
                                  -deviceList $device} result]} {
                        APSMpReturn error "LMOCS_TurnOn: $result"
                    }
                    if {$result} {
                        if {[catch {APSDevSend \
                                      -group LinacKlystron \
                                      -operation ResetHVPS \
                                      -deviceList $device -releaseLinks 1} result]} {
                            APSMpReturn error "LMOCS_TurnOn: $result"
                        }
                        after 510
                        if {[catch {APSDevSend \
                                      -group LinacKlystron \
                                      -operation ToggleHVPS \
                                      -deviceList $device -releaseLinks 1} result]} {
                            APSMpReturn error "LMOCS_TurnOn: $result"
                        }
                        if {[catch {APSDevSend \
                                      -group LinacKlystron \
                                      -operation QueryHVPSOn \
                                      -deviceList $device \
                                      -returnPVList 1} result]} {
                            APSMpReturn error "LMOCS_TurnOn: $result"
                        }
                        if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable cawait \
                                      -interval=1 \
                                      -waitFor=$result,equalto=0 \
                                      -timeLimit=10} result]} {
                            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Unable to turn HVPS on in sector $sector: $result"] == 1} {
                                APSMpReturn error "LMOCS_TurnOn: Unable to turn HVPS on in sector $sector: $result"
                            }
                        }   
                    }
                    
                    if {$loop<3} {
                        incr loop
                        continue		
                    } else {
                        APSMpReturn error "LMOCS_TurnOn: Timed out twice while waiting for PFN Voltage to reach 10.0kV.  Giving up"
                    }
                }
            }
            set loop 0
        }

        if {[catch {APScavget -list=${sector}:MO:LowPFNvSP} PFNLowTripValue]} {
            set PFNLowTripValue 22
        }
        #set PFNLowTripValue [expr $PFNLowTripValue + .1]
        APSMpStep "${prefix}Increasing PFN to $PFNLowTripValue in $sector" -desc "Increase PFN voltage to 22"
        if {[catch {APSLRampPFNVoltage \
                      -klystronList $device \
                      -rampTo $PFNLowTripValue \
                      -steps 5  -checkVacuum 1 \
                      -pause 10} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Error while increasing $sector PFN to ${PFNLowTripValue}: $result"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
        }
        
    }
    if {([llength $sledTrig] == 1) && ([llength $sledTrigVar] == 1)} {
        if {[catch {exec cavput -list=${sledTrigVar}=${sledTrig}} result]} {
        }
    }
    if {([llength $attnSetPoint] == 1) && ([llength $attnPVName] == 1)} {
        if {[catch {exec cavput -list=${attnPVName}=${attnSetPoint}} result]} {
        }
    }
    
    if {$sector == "L1"} {
        APSMpStep "${prefix}Perform L1 klystron and sector timing scans" \
          -desc "Perform L1 klystron and sector timing scans"
        if {[catch {exec cavput -list=L1: -list=KY:DC2ARF,SE:DC1ARF -list=.SPD=1} result]} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Problem doing set timing on scan peak for L1: $result"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: Problem doing set timing on scan peak for L1: $result"
            }
        }	
        if {[catch {exec cavput -list=L1: -list=KY:DC2ARF,SE:DC1ARF -list=.AQWF=1} result]} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOn: Problem initiating timing scans for L1: $result"] == 1} {
                APSMpReturn error "LMOCS_TurnOn: Problem initiating timing scans for L1: $result"
            }
        }
    }
    
    
    APSMpStep "${prefix}Check if 400 watt amp is on in $sector" -desc "Check 400 watt amp"
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation Query400WAmpOn \
                  -deviceList $device} result]} {
        APSMpReturn error "LMOCS_TurnOn: $result"
    }
    if {!$result} {
        APSMpStep "${prefix}Turn 400W RF Amp On in $sector" -desc "Reset 400 watt amp if needed"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryACISPermit400WAmp \
                      -deviceList $device} permit]} {
            APSMpReturn error "LMOCS_TurnOn: $permit"
        }
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryACISLatch400WAmp \
                      -deviceList $device} latch]} {
            APSMpReturn error "LMOCS_TurnOn: $latch"
        }
        if {(!$permit) || (!$latch)} {
            if {[catch {APSDevSend \
                          -group LinacKlystron \
                          -operation ResetACIS400WAmp \
                          -deviceList $device -releaseLinks 1} result]} {
                APSMpReturn error "LMOCS_TurnOn: $result"
            }
            APSWaitWithUpdate -waitSeconds 2
        }

        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation Reset400WAmp \
                      -deviceList $device -releaseLinks 1} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        after 510
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation Query400WAmpOn \
                      -deviceList $device \
                      -returnPVList 1} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable$device cawait \
                      -interval=1 \
                      -waitFor=$result,equalto=1 \
                      -timeLimit=10} result]} {
            set result 0
            APSWaitWithUpdate -waitSeconds 10
        } else {
            set result 1
        }
    }

    APSMpStep "${prefix}Turn on LLRF in $sector" -desc "Turn on LLRF"
    if {[catch {APSLINAC_LLRFOnOff \
                  -button On \
                  -deviceList $device} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while turning on LLRF in $sector \n$result"] == 1} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
    }
    if {$resumePCS} {
        if {($device == 4) || ($device == 5)} {
            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 "LMOCS_TurnOn: $result"
                }
            }
            APSMpStep "${prefix}Suspend Y LTP ControlLaw" -desc "Suspend X 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 "LMOCS_TurnOn: $result"
                }
            }
        }
    }

    APSMpStep "${prefix}Check if 400 watt amp is on in $sector" -desc "Check 400 watt amp"
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation QueryACISPermit400WAmp \
                  -deviceList $device} permit]} {
        APSMpReturn error "LMOCS_TurnOn: $permit"
    }
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation QueryACISLatch400WAmp \
                  -deviceList $device} latch]} {
        APSMpReturn error "LMOCS_TurnOn: $latch"
    }
    if {(!$permit) || (!$latch)} {
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ResetACIS400WAmp \
                      -deviceList $device -releaseLinks 1} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        APSWaitWithUpdate -waitSeconds 2
    }
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation Query400WAmpOn \
                  -deviceList $device} result]} {
        APSMpReturn error "LMOCS_TurnOn: $result"
    }
    if {!$result} {
        APSMpStep "${prefix}Turn 400W RF Amp On in $sector" -desc "Reset 400 watt amp if needed"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation Reset400WAmp \
                      -deviceList $device -releaseLinks 1} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        after 510
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation Query400WAmpOn \
                      -deviceList $device \
                      -returnPVList 1} result]} {
            APSMpReturn error "LMOCS_TurnOn: $result"
        }
        if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable$device cawait \
                      -interval=1 \
                      -waitFor=$result,equalto=1 \
                      -timeLimit=10} result]} {
            set result 0
            APSWaitWithUpdate -waitSeconds 10
        } else {
            set result 1
        }
    }

    if {$resumePCS} {
        if {($device == 1) || ($device == 2) || ($device == 3) || ($device == 4) || ($device == 5)} {
            #Call linac recovery here
            #puts "LinacRFRecovery -RF $sector -SCRFile [file tail $SCRFile]"
            #exec LinacRFRecovery -RF $sector -SCRFile [file tail $SCRFile] &
            #Launch as parallel semi-automatic mode so we get a new window
            exec runProcGUI LMOCS_Recover -$sector 1 -SCRFile $SCRFile &
        }
    }

    APSMpStep "${prefix}Finished with $sector"
    APSMpReturn ok
}

proc LMOCS_TurnOff {args} {
    if {![llength [info commands blt::bgexec]]} {
        package require BLT
        global blt_library
        lappend auto_path $blt_library
    }
    global status
    
    set sector ""
    set PFNFinalValue ""
    APSStrictParseArguments {sector}
    global execMode
    if {$execMode == "Manual"} {
        set prefix "Press Continue to "
    } else {
        set prefix ""
    }

    switch -exact -- $sector {
        L1 {set device 1} 
        L3 {set device 3} 
        L4 {set device 4} 
        L6 {set device 6} 
        default {APSMpReturn error "LMOCS_TurnOff: invalid sector $sector"}
    }

    set style new

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

    if {($device == 1) || ($device == 3)} {
        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 "LMOCS_TurnOff: $result"
            }
        }
    }
    
    APSMpStep "${prefix}Shutdown till ready to pulse is off in $sector" -desc "Shutdown till ready to pulse is off" -proc LMOCS_ShutdownTillReadyToPulseOff
    if {[catch {LMOCS_ShutdownTillReadyToPulseOff -sector $sector} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while shutting down to ready to pulse is off in $sector \n$result"] == 1} {
            APSMpReturn error "LMOCS_TurnOff: $result"
        }
    }

    APSMpStep "${prefix}Check PFN voltage in $sector" -desc "Check PFN voltage"
    if {[catch {APSDevSend -group LinacKlystron -operation ReadPFNVoltage -deviceList $device} result]} {
        APSMpReturn error "LMOCS_TurnOff: $result"
    }
    if {$result > 1} {
        APSMpStep "Decreasing PFN to 0 in $sector" -desc "Decrease PFN to 0 if needed"
        if {[catch {APSLRampPFNVoltage -klystronList $device -rampTo 0 -steps 1} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Error while decreasing PFN to 0 in $sector \n$result"] == 1} {
                APSMpReturn error "LMOCS_TurnOff: $result"
            }
        }
    }

    APSMpStep "${prefix}Check if Dump switch is on in $sector" -desc "Check if Dump switch is on for new style modulators"
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation QueryDumpSwitchOn \
                  -deviceList $device} result]} {
        APSMpReturn error "LMOCS_TurnOff: $result"
    }
    if {$result} {
        APSMpStep "${prefix}Turn off Dump switch in $sector" -desc "Turn off Dump switch if needed"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ResetDumpSwitch \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOff: $result"
        }
        after 510
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ToggleDumpSwitch \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOff: $result"
        }
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryDumpSwitchOn \
                      -deviceList $device \
                      -returnPVList 1} result]} {
            APSMpReturn error "LMOCS_TurnOff: $result"
        }
        if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable cawait \
                      -interval=1 \
                      -waitFor=$result,equalto=0 \
                      -timeLimit=10} result]} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOff: Unable to turn dump switches off in sector $sector: $result"] == 1} {
                APSMpReturn error "LMOCS_TurnOff: Unable to turn dump switches off in sector $sector: $result"
            }
        }
    } 
    

    APSMpStep "${prefix}Check if focus magnets are on in $sector" -desc "Check if focus magnets are on for new style modulators"
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation QueryKlyMagnetsOn \
                  -deviceList $device} result]} {
        APSMpReturn error "LMOCS_TurnOff: $result"
    }
    if {$result} {
        APSMpStep "${prefix}Turn focus magnets off in $sector" -desc "Turn off focus magnets if needed"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ResetKlystronMagnets \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOff: $result"
        }
        after 510
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ToggleKlystronMagnets \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_TurnOff: $result"
        }
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryKlyMagnetsOn \
                      -deviceList $device \
                      -returnPVList 1} result]} {
            APSMpReturn error "LMOCS_TurnOff: $result"
        }
        if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable cawait \
                      -interval=1 \
                      -waitFor=$result,equalto=0 \
                      -timeLimit=10} result]} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_TurnOff: Unable to turn off focus magnets in sector $sector: $result"] == 1} {
                APSMpReturn error "LMOCS_TurnOff: Unable to turn off focus magnets in sector $sector: $result"
            }
        }
    }
    APSMpReturn ok
}

proc LMOCS_ShutdownTillReadyToPulseOff {args} {
    APSMpStep init
    if {![llength [info commands blt::bgexec]]} {
        package require BLT
        global blt_library
        lappend auto_path $blt_library
    }
    set rampPFN 1
    global execMode
    if {$execMode == "Manual"} {
        set prefix "Press Continue to "
    } else {
        set prefix ""
    }

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

    set sector ""
    APSStrictParseArguments {sector rampPFN}

    switch -exact -- $sector {
        L1 {set device 1} 
        L3 {set device 3} 
        L4 {set device 4} 
        L6 {set device 6} 
        default {APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: invalid sector $sector"}
    }

    set style new

    APSMpStep "${prefix}Suspend power control script for $sector" -desc "Suspend power control script"
    if {[catch {APSLSuspendResumeRFPowerControllaws -klystronList $device -mode suspend} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while suspending $sector power controls: $result"] == 1} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
    }	
    if {$sector == "L1"} {
        APSMpStep "${prefix}Check $sector Attenuation is above 4.55" -desc "Check that attenuation is above 4.55"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ReadRFAttenuatorPosition \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
        if {$result < 4.55} {
            APSWaitWithUpdate -waitSeconds 3
            APSMpStep "${prefix}Increase $sector attenuation to 4.55" -desc "Increase attenuation if needed"
            if {[catch {APSLINAC_IncreaseAttnCtrl -deviceList $device -minAttenuation 4.55} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while increasing $sector attenuation to 4.55: $result"] == 1} {
                    APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
                }
            }
        } 
    } elseif {$sector == "L2"} {
        APSMpStep "${prefix}Check $sector Attenuation is above 3.16" -desc "Check that attenuation is above 3.16"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ReadRFAttenuatorPosition \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
        if {$result < 3.16} {
            APSWaitWithUpdate -waitSeconds 3
            APSMpStep "${prefix}Increase $sector attenuation to 3.16" -desc "Increase attenuation if needed"
            if {[catch {APSLINAC_IncreaseAttnCtrl -deviceList $device -minAttenuation 3.16} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while increasing $sector attenuation to 3.16: $result"] == 1} {
                    APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
                }
            }
        } 
    } elseif {$sector == "L3"} {
        APSMpStep "${prefix}Check $sector Attenuation is above 3.0" -desc "Check that attenuation is above 3.0"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ReadRFAttenuatorPosition \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
        if {$result < 3.0} {
            APSWaitWithUpdate -waitSeconds 3
            APSMpStep "${prefix}Increase $sector attenuation to 3.0" -desc "Increase attenuation if needed"
            if {[catch {APSLINAC_IncreaseAttnCtrl -deviceList $device -minAttenuation 3.0} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while increasing $sector attenuation to 3.0: $result"] == 1} {
                    APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
                }
            }
        } 
    } elseif {$sector == "L4"} {
        APSMpStep "${prefix}Check $sector Attenuation is above 4.0" -desc "Check that attenuation is above 4.0"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ReadRFAttenuatorPosition \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
        if {$result < 4.0} {
            APSWaitWithUpdate -waitSeconds 3
            APSMpStep "${prefix}Increase $sector attenuation to 4.0" -desc "Increase attenuation if needed"
            if {[catch {APSLINAC_IncreaseAttnCtrl -deviceList $device -minAttenuation 4.0} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while increasing $sector attenuation to 4.0: $result"] == 1} {
                    APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
                }
            }
        } 
    } else {
        APSMpStep "${prefix}Check $sector Attenuation is above 2.8" -desc "Check that attenuation is above 2.8"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ReadRFAttenuatorPosition \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
        if {$result < 2.8} {
            APSWaitWithUpdate -waitSeconds 3
            APSMpStep "${prefix}Increase $sector attenuation to 2.8" -desc "Increase attenuation if needed"
            if {[catch {APSLINAC_IncreaseAttnCtrl -deviceList $device -minAttenuation 2.8} result]} {
                if {[APSPEMTKDialog .warningDialog -text "Error while increasing $sector attenuation to 2.8: $result"] == 1} {
                    APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
                }
            }
        } 
    }

    

    APSMpStep "${prefix}Turn off LLRF in $sector" -desc "Turn off LLRF"
    if {[catch {APSLINAC_LLRFOnOff \
                  -button Off \
                  -deviceList $device} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while turning off LLRF in $sector : $result"] == 1} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
    }

    APSMpStep "${prefix}Check PFN voltage" -desc "Check PFN voltage"
    if {[catch {APSDevSend -group LinacKlystron -operation ReadPFNVoltage -deviceList $device} result]} {
        APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
    }
    if {$result > 1} {
        APSMpStep "Decreasing PFN to 0" -desc "Decrease PFN to 0 if needed"
        if [catch {APSDevSend -group LinacKlystron -deviceList $device \
                     -operation SetPFNVoltage -valueList 0} result] {
            return -code error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
    }
    if {[catch {APScavget -list=L${device}:MO:PFNvAI -pend=5 -printErrors 1} RFVoltage]} {
        APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $RFVoltage"
    }
    set tries 0
    while {$RFVoltage > .5} {
        incr tries
        if {$tries > 15} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: L${device}:MO:PFNvAI is not going to zero"
        }
        APSWaitWithUpdate -waitSeconds 3
        if {[catch {APScavget -list=L${device}:MO:PFNvAI -pend=5 -printErrors 1} RFVoltage]} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $RFVoltage"
        }
    }
    

    APSMpStep "${prefix}Check if PS Enabled in $sector" -desc "Check if PS is enabled for new style modulators"
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation QueryPSEnableOn \
                  -deviceList $device} result]} {
        APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
    }
    if {$result} {
        APSMpStep "${prefix}Disable PS in $sector" -desc "Disable PS if needed"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ResetPowerSupplyEnable \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
        after 510
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation TogglePowerSupplyEnable \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryPSEnableOn \
                      -deviceList $device \
                      -returnPVList 1} result]} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
        if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable cawait \
                      -interval=1 \
                      -waitFor=$result,equalto=0 \
                      -timeLimit=10} result]} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_ShutdownTillReadyToPulseOff: Unable to disable PS in sector $sector: $result"] == 1} {
                APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: Unable to disable PS in sector $sector: $result"
            }
        }
    }
    
    APSMpStep "${prefix}Check if ready to pulse in $sector" -desc "Check if Ready to Pulse"
    if {[catch {APSDevSend \
                  -group LinacKlystron \
                  -operation QueryReadyToPulseOn \
                  -deviceList $device} result]} {
        APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
    }
    if {$result} {
        APSMpStep "${prefix}Set Ready to Pulse Off in $sector" -desc "Set Ready to Pulse off if needed"
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ResetReadyToPulse \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
        after 510
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation ToggleReadyToPulse \
                      -deviceList $device} result]} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
        if {[catch {APSDevSend \
                      -group LinacKlystron \
                      -operation QueryReadyToPulseOn \
                      -deviceList $device \
                      -returnPVList 1} result]} {
            APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: $result"
        }
        if {[catch {blt::bgexec apsLMOCSTurnOnAbortVariable cawait \
                      -interval=1 \
                      -waitFor=$result,equalto=0 \
                      -timeLimit=10} result]} {
            if {[APSPEMTKDialog .warningDialog -text "LMOCS_ShutdownTillReadyToPulseOff: Unable to turn Ready to Pulse off: $result"] == 1} {
                APSMpReturn error "LMOCS_ShutdownTillReadyToPulseOff: Unable to turn Ready to Pulse off: $result"
            }
        }
    }
    APSMpReturn ok
}





proc LMOCS_ResetAutoPhaseControl {args} {
    set SCRFile ""
    set sectors ""
    set L1 0
    set L2 0
    set L3 0
    set L4 0
    set L5 0
    APSStrictParseArguments {SCRFile L1 L2 L3 L4 L5}
    foreach sector "L1 L2 L3 L4 L5" sec "1 2 3 4 5" {
        if {[set $sector]} {
            append sectors $sec
        }
    }
    if {[llength $sectors] == 0} {
        return
    }
    
    if {[catch {exec sddsselect $SCRFile /home/helios/oagData/pem/linac/SCRPhaseFilterFile -match=ControlName -pipe=out | sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
        return -code error "LMOCS_ResetAutoPhaseControl: Invalid SCR file"
    }
    if {[catch {APSPCGUN_ReadRFSwitch1} rfSwitch]} {
        return -code error "LMOCS_ResetAutoPhaseControl: $rfSwitch"
    }
    if {"GUN" != $rfSwitch} {
        set sectors 1245
    }

    set option1 ""
    set option2 ""
    set option3 ""
    set option4 ""
    if {[catch {
        foreach {controlName valueString} $results {
            if {[regexp -- L\[${sectors}\]:AUTO:PH:modeMO $controlName]} {
                #		set L[string index $controlName 1]Mode Disabled
                lappend option1 ${controlName}=Disabled
                lappend option4 ${controlName}=$valueString
            } elseif {[regexp -- L\[${sectors}\]:PP:phaseAdjAO $controlName]} {
                #		set L[string index $controlName 1]Phase $valueString
                lappend option2 ${controlName}=$valueString
            } elseif {[regexp -- L\[${sectors}\]:AUTO:PH:SetpointAO $controlName]} {
                #		set L[string index $controlName 1]Setpoint $valueString
                lappend option3 ${controlName}=$valueString
            }
        }
        eval exec cavput -list=[join $option1 ,] -pend=20
        APSWaitWithUpdate -waitSeconds 1
        eval exec cavput -list=[join $option2 ,] -pend=20
        eval exec cavput -list=[join $option3 ,] -pend=20
        if {"GUN" == $rfSwitch} {
            APSWaitWithUpdate -waitSeconds 1
            eval exec cavput -list=[join $option4 ,] -pend=20
        }
    } results]} {
        return -code error "LMOCS_ResetAutoPhaseControl: $results"
    }
}

proc LMOCS_PowerControlLawSetup {args} {
    set deviceList L1
    set mode high
    APSStrictParseArguments {deviceList mode}
    set L1gain .4
    set L2gain .5
    set L3gain .4
    set L4gain .4
    set L5gain .4
    set L1aver 1
    set L2aver 1
    set L3aver 1
    set L4aver 1
    set L5aver 1
    set L1intr 1
    set L2intr 1
    set L3intr 1
    set L4intr 1
    set L5intr 1

    set L1gain .35
    set L1intr 5
    set L2gain .19
    set L2intr 10
    set L3gain .19
    set L3intr 10
    set L4gain .19
    set L4intr 10
    set L5gain .25
    set L5intr 10
    
    if {$mode == "low"} {
        set L1gain .19
        set L2gain .39
        set L3gain .19
        set L4gain .3
        set L5gain .3
        set L2aver 5
        set L2intr 5

        set L1gain .35
        set L1intr 5
        set L2gain .19
        set L2intr 10
        set L3gain .19
        set L3intr 10
        set L4gain .19
        set L4intr 10
        set L5gain .25
        set L5intr 10
    }
    APSMpStep "Set modulators $deviceList to $mode mode" -desc "Setup modulator modes"
    foreach device $deviceList {
        if {[catch {exec cavput -list=L:${device}Stabilizer:SDDS.GAIN=[set ${device}gain],L:${device}Stabilizer:SDDS.AVER=[set ${device}aver],L:${device}Stabilizer:SDDS.INTR=[set ${device}intr] } result]} {
            return -code error "LMOCS_PowerControlLawSetup: $result"
        }
    }
}

proc CheckModulatorInterlocks {args} {
    set sectors "L1 L2 L3 L4 L5"
    foreach sector $sectors {
        set $sector 1
    }
    APSStrictParseArguments {L1 L2 L3 L4 L5}
    global execMode
    
    if {[catch {APScavget -list=L3:IC1:K1dwnModeM,L3:IC1:K2dwnModeM,L3:IC1:K3dwnModeM -num} modes]} {
        return -code error "CheckModulatorInterlocks: $modes"
    }
    set K1Down [lindex $modes 0]
    set K2Down [lindex $modes 1]
    set K3Down [lindex $modes 2]
    
    if {$L1} {
        if {[catch {APScavget -list=L1:IC1:VacPermitM,L1:IC1:SF6:ZAB:PermitM,L1:IC1:WS1:PermitM -num} results]} {
            return -code error "CheckModulatorInterlocks: $results"
        }
        if {[lindex $results 0] != 1} {
            return -code error "CheckModulatorInterlocks: L1 vacuum interlock problem detected."
        }
        if {[lindex $results 1] != 1} {
            return -code error "CheckModulatorInterlocks: L1 SF6 interlock problem detected."
        }
        if {[lindex $results 2] != 1} {
            return -code error "CheckModulatorInterlocks: L1 water interlock problem detected."
        }        
    }
    if {$L2} {
        if {[catch {APScavget -list=L2:IC1:VacPermitM,L2:IC1:SLED:PermitM,L2:IC1:SF6:ZC:PermitM,L2:IC1:WS1:PermitM -num} results]} {
            return -code error "CheckModulatorInterlocks: $results"
        }
        if {[lindex $results 0] != 1} {
            return -code error "CheckModulatorInterlocks: L2 vacuum interlock problem detected."
        }
        if {[lindex $results 1] != 1} {
            return -code error "CheckModulatorInterlocks: L2 SLED needle interlock problem detected."
        }
        if {[lindex $results 2] != 1} {
            return -code error "CheckModulatorInterlocks: L2 SF6 interlock problem detected."
        }
        if {[lindex $results 3] != 1} {
            return -code error "CheckModulatorInterlocks: L2 water interlock problem detected."
        }        
    }
    if {$L3} {
        if {[catch {APScavget -list=L3:IC1:VacPermitM,L3:IC1:SLED:PermitM,L3:IC1:SF6:PermitM,L3:IC1:H2O:PermitM -num} results]} {
            return -code error "CheckModulatorInterlocks: $results"
        }
        if {[lindex $results 0] != 1} {
            return -code error "CheckModulatorInterlocks: L3 vacuum interlock problem detected."
        }
        if {$K2Down} {
            if {[lindex $results 1] != 1} {
                return -code error "CheckModulatorInterlocks: L3 SLED needle interlock problem detected."
            }
        }
        if {[lindex $results 2] != 1} {
            return -code error "CheckModulatorInterlocks: L3 SF6 interlock problem detected."
        }
        if {[lindex $results 3] != 1} {
            return -code error "CheckModulatorInterlocks: L3 water interlock problem detected."
        }        
    }
    if {$L4} {
        if {[catch {APScavget -list=L4:IC1:VacPermitM,L4:IC1:SLED:PermitM,L4:IC1:H2O:PermitM -num} results]} {
            return -code error "CheckModulatorInterlocks: $results"
        }
        if {[lindex $results 0] != 1} {
            return -code error "CheckModulatorInterlocks: L4 vacuum interlock problem detected."
        }
        if {[lindex $results 1] != 1} {
            return -code error "CheckModulatorInterlocks: L4 SLED needle interlock problem detected."
        }
        if {[lindex $results 2] != 1} {
            return -code error "CheckModulatorInterlocks: L4 water interlock problem detected."
        }        
    }
    if {$L5} {
        if {[catch {APScavget -list=L5:IC1:VacPermitM,L5:IC1:SLED:PermitM,L5:IC1:H2O:PermitM -num} results]} {
            return -code error "CheckModulatorInterlocks: $results"
        }
        if {[lindex $results 0] != 1} {
            return -code error "CheckModulatorInterlocks: L5 vacuum interlock problem detected."
        }
        if {[lindex $results 1] != 1} {
            return -code error "CheckModulatorInterlocks: L5 SLED needle interlock problem detected."
        }
        if {[lindex $results 2] != 1} {
            return -code error "CheckModulatorInterlocks: L5 water interlock problem detected."
        }        
    }
    return
}

