proc APSMpSRFStartUpInfo {args} {
    return "Bring the selected SR RF systems from no power to full power."
}

proc APSMpSRFStartUpInitDialog {frame} {
    global APSMpSRFStartUp

    pack [frame ${frame}.f2]
    APSCheckButtonFrame .cf0 -parent $frame.f2 -label "Systems: " \
      -buttonList {RF1 RF2 RF3 RF4} \
      -variableList {APSMpSRFStartUp(SRF1) APSMpSRFStartUp(SRF2) APSMpSRFStartUp(SRF3) APSMpSRFStartUp(SRF4)} \
      -packOption "-side left" \
      -contextHelp "Select which RF systems to modify."
    if {$APSMpSRFStartUp(SRF1) == 0} {
        $frame.f2.cf0.frame.button1 configure -state disable
    }
    if {$APSMpSRFStartUp(SRF2) == 0} {
        $frame.f2.cf0.frame.button2 configure -state disable
    }
    if {$APSMpSRFStartUp(SRF3) == 0} {
        $frame.f2.cf0.frame.button3 configure -state disable
    }
    if {$APSMpSRFStartUp(SRF4) == 0} {
        $frame.f2.cf0.frame.button4 configure -state disable
    }
}


proc APSMpSRFStartUp {args} {
    set SRF1 0
    set SRF2 0
    set SRF3 0
    set SRF4 0

    #CHECK WAVEGUIDE SWITCH MODE
    if {[catch {APScavget -list=S6:WGS:modeSelect -pend=20 -printErrors} waveGuideSwitchMode]} {
        APSMpReturn error "APSMpSRFStartUp: $waveGuideSwitchMode"
    }
    if {($waveGuideSwitchMode != "Mode7") && \
          ($waveGuideSwitchMode != "Mode8") && \
          ($waveGuideSwitchMode != "Mode9") && \
          ($waveGuideSwitchMode != "Mode10") && \
          ($waveGuideSwitchMode != "Mode11") && \
          ($waveGuideSwitchMode != "Mode12")} {
        APSMpReturn error "APSMpSRFStartUp: This procedure cannot be run in this waveguide switch mode. $waveGuideSwitchMode"
    }
    if {($waveGuideSwitchMode == "Mode7")} {
        set SRF2 1
        set SRF4 1
    } elseif {($waveGuideSwitchMode == "Mode8")} {
        set SRF1 1
        set SRF2 1
    } elseif {($waveGuideSwitchMode == "Mode9")} {
        set SRF1 1
        set SRF2 1
    } elseif {($waveGuideSwitchMode == "Mode10")} {
        set SRF3 1
        set SRF4 1
    } elseif {($waveGuideSwitchMode == "Mode11")} {
        set SRF2 1
        set SRF4 1
    } elseif {($waveGuideSwitchMode == "Mode12")} {
        set SRF1 1
        set SRF3 1
    }

    #CHECK ACIS INTERLOCK STATUS
    if {[catch {APScavget -list=ACIS:FA_UP_BEAM_INH,ACIS:FBL_UP_BEAM_INH,ACIS:FA_BP_MODE,ACIS:FB_BP_MD -num -pend=20 -printErrors} acisState]} {
        APSMpReturn error "APSMpSRFStartUp: $acisState"
    }
    if {([lindex $acisState 0] == 1) || ([lindex $acisState 1] == 1)} {
        if {[APSPEMTKDialog .warningDialog \
               -text "SRF is in an acis inhibit state."] == 1} {
            APSMpReturn error "APSMpSRFStartUp: SR RF is in an acis inhibit state."
        }
    } elseif {([lindex $acisState 2] == 0) || ([lindex $acisState 3] == 0)} {
        if {[APSPEMTKDialog .warningDialog \
               -text "SRF is in an acis trip state."] == 1} {
            APSMpReturn error "APSMpSRFStartUp: SR RF is in an acis trip state."
        }
    }
    APSMpStep init -promptDialog APSMpSRFStartUpInitDialog \
      -vars {SRF1 SRF2 SRF3 SRF4}

    set paramString ""
    foreach param {SRF1 SRF2 SRF3 SRF4} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction \
             -procedure APSMpSRFStartUp \
             -action initialize \
             -state ok \
             -parameters $paramString}

    for {set i 1} {$i <= 4} {incr i} {
        if {[set SRF$i]} {
            APSMpStep "SRF${i}: Bring Up To Full Power" -proc APSMpSRFBringUpToFullPower
            set id$i [APSMpParallel -mode "Automatic" \
                        -procedure "APSMpSRFBringUpToFullPower \
                                     -rf $i"]
        }
    }

    for {set i 1} {$i <= 4} {incr i} {
        if {[set SRF$i]} {
            if {[catch {APSMpJoin [set id$i]} results]} {
                if {[APSPEMTKDialog .warningDialog -text "Problem occured\nAPSMpSRFStartUp: $results"] == 1} {
                    APSMpReturn error "APSMpSRFStartUp: $results"
                }
            }
        }
    }

    APSMpReturn ok
}

proc APSMpSRFStandbyInfo {args} {
    return "Bring the selected SR RF systems from no power to diode mode."
}

proc APSMpSRFStandbyInitDialog {frame} {
    global APSMpSRFStandby

    pack [frame ${frame}.f1]
    APSCheckButtonFrame .cf0 -parent $frame.f1 -label "Systems: " \
      -buttonList {RF1 RF2 RF3 RF4} \
      -variableList {APSMpSRFStandby(SRF1) APSMpSRFStandby(SRF2) APSMpSRFStandby(SRF3) APSMpSRFStandby(SRF4)} \
      -packOption "-side left" \
      -contextHelp "Select which RF systems to modify."

    if {$APSMpSRFStandby(SRF1) == 0} {
        $frame.f1.cf0.frame.button1 configure -state disable
    }
    if {$APSMpSRFStandby(SRF2) == 0} {
        $frame.f1.cf0.frame.button2 configure -state disable
    }
    if {$APSMpSRFStandby(SRF3) == 0} {
        $frame.f1.cf0.frame.button3 configure -state disable
    }
    if {$APSMpSRFStandby(SRF4) == 0} {
        $frame.f1.cf0.frame.button4 configure -state disable
    }

}

proc APSMpSRFStandby {args} {
    set SRF1 0
    set SRF2 0
    set SRF3 0
    set SRF4 0
    APSStrictParseArguments {SRF1 SRF2 SRF3 SRF4}

    #CHECK WAVEGUIDE SWITCH MODE
    if {[catch {APScavget -list=S6:WGS:modeSelect -pend=20 -printErrors} waveGuideSwitchMode]} {
        APSMpReturn error "APSMpSRFStandby: $waveGuideSwitchMode"
    }
    if {($waveGuideSwitchMode != "Mode7") && \
          ($waveGuideSwitchMode != "Mode8") && \
          ($waveGuideSwitchMode != "Mode9") && \
          ($waveGuideSwitchMode != "Mode10") && \
          ($waveGuideSwitchMode != "Mode11") && \
          ($waveGuideSwitchMode != "Mode12")} {
        APSMpReturn error "APSMpSRFStandby: This procedure cannot be run in this waveguide switch mode. $waveGuideSwitchMode"
    }
    if {($waveGuideSwitchMode == "Mode7")} {
        set SRF1 1
        set SRF3 1
    } elseif {($waveGuideSwitchMode == "Mode8")} {
        set SRF3 1
        set SRF4 1
    } elseif {($waveGuideSwitchMode == "Mode9")} {
        set SRF3 1
        set SRF4 1
    } elseif {($waveGuideSwitchMode == "Mode10")} {
        set SRF1 1
        set SRF2 1
    } elseif {($waveGuideSwitchMode == "Mode11")} {
        set SRF1 1
        set SRF3 1
    } elseif {($waveGuideSwitchMode == "Mode12")} {
        set SRF2 1
        set SRF4 1
    }

    #CHECK ACIS INTERLOCK STATUS
    if {[catch {APScavget -list=ACIS:FA_UP_BEAM_INH,ACIS:FBL_UP_BEAM_INH,ACIS:FA_BP_MODE,ACIS:FB_BP_MD -num -pend=20 -printErrors} acisState]} {
        APSMpReturn error "APSMpSRFStandby: $acisState"
    }
    if {([lindex $acisState 0] == 1) || ([lindex $acisState 1] == 1)} {
        if {[APSPEMTKDialog .warningDialog \
               -text "Booster is in an acis inhibit state."] == 1} {
            APSMpReturn error "APSMpSRFStandby: Booster is in an acis inhibit state."
        }
    } elseif {([lindex $acisState 2] == 0) || ([lindex $acisState 3] == 0)} {
        if {[APSPEMTKDialog .warningDialog \
               -text "Booster is in an acis trip state."] == 1} {
            APSMpReturn error "APSMpSRFStandby: Booster is in an acis trip state."
        }
    }

    APSMpStep init -promptDialog APSMpSRFStandbyInitDialog \
      -vars {SRF1 SRF2 SRF3 SRF4}

    set paramString ""
    foreach param {SRF1 SRF2 SRF3 SRF4} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction \
             -procedure APSMpSRFStandby \
             -action initialize \
             -state ok \
             -parameters $paramString}

    for {set i 1} {$i <= 4} {incr i} {
        if {[set SRF$i]} {
            APSMpStep "SRF${i}: Bring Up To Standby (if off)" -proc APSMpSRFBringUpToStandby
            set id$i [APSMpParallel -mode "Automatic" \
                        -procedure "APSMpSRFBringUpToStandby \
                                     -rf $i"]
        }
    }

    for {set i 1} {$i <= 4} {incr i} {
        if {[set SRF$i]} {
            if {[catch {APSMpJoin [set id$i]} results]} {
                if {[APSPEMTKDialog .warningDialog -text "Problem occured\nAPSMpSRFStandby: $results"] == 1} {
                    APSMpReturn error "APSMpSRFStandby: $results"
                }
            }
        }
    }

    for {set i 1} {$i <= 4} {incr i} {
        if {[set SRF$i]} {
            APSMpStep "SRF${i}: Take To Standby From Full Power (if powered)" -proc APSMpSRFStandbyFromFullPower
            set id$i [APSMpParallel -mode "Automatic" \
                        -procedure "APSMpSRFStandbyFromFullPower \
                                     -rf $i"]
        }
    }

    for {set i 1} {$i <= 4} {incr i} {
        if {[set SRF$i]} {
            if {[catch {APSMpJoin [set id$i]} results]} {
                if {[APSPEMTKDialog .warningDialog -text "Problem occured\nAPSMpSRFStandby: $results"] == 1} {
                    APSMpReturn error "APSMpSRFStandby: $results"
                }
            }
        }
    }

    APSMpReturn ok
}

proc APSMpSRFShutDownInfo {args} {
    return "Bring the selected SR RF systems down to no power."
}

proc APSMpSRFShutDownDialog {frame} {
    APSCheckButtonFrame .cf0 -parent $frame -label "Systems: " \
      -buttonList {RF1 RF2 RF3 RF4} \
      -variableList {APSMpSRFShutDown(SRF1) APSMpSRFShutDown(SRF2) APSMpSRFShutDown(SRF3) APSMpSRFShutDown(SRF4)} \
      -contextHelp "Select which RF systems to modify."
    return
}

proc APSMpSRFShutDown {args} {
    set SRF1 0
    set SRF2 0
    set SRF3 0
    set SRF4 0
    APSStrictParseArguments {SRF1 SRF2 SRF3 SRF4}
    APSMpStep init -promptDialog APSMpSRFShutDownDialog -vars {SRF1 SRF2 SRF3 SRF4}

    for {set i 1} {$i <= 4} {incr i} {
        if {[set SRF$i]} {
            APSMpStep "SRF${i}: Go To Standby From Full Power (if needed)" -proc APSMpSRFStandbyFromFullPower
            set id$i [APSMpParallel -mode "Automatic" \
                        -procedure "APSMpSRFStandbyFromFullPower -rf $i"]
        }
    }

    for {set i 1} {$i <= 4} {incr i} {
        if {[set SRF$i]} {
            if {[catch {APSMpJoin [set id$i]} results]} {
                if {[APSPEMTKDialog .warningDialog -text "Problem occured\nAPSMpSRFShutDown: $results"] == 1} {
                    APSMpReturn error "APSMpSRFShutDown: $results"
                }
            }
        }
    }

    for {set i 1} {$i <= 4} {incr i} {
        if {[set SRF$i]} {
            APSMpStep "SRF${i}: Shutdown From Standby" -proc APSMpSRFShutdownFromStandby
            set id$i [APSMpParallel -mode "Automatic" \
                        -procedure "APSMpSRFShutdownFromStandby -rf $i"]
        }
    }

    for {set i 1} {$i <= 4} {incr i} {
        if {[set SRF$i]} {
            if {[catch {APSMpJoin [set id$i]} results]} {
                if {[APSPEMTKDialog .warningDialog -text "Problem occured\nAPSMpSRFShutDown: $results"] == 1} {
                    APSMpReturn error "APSMpSRFShutDown: $results"
                }
            }
        }
    }

    APSMpReturn ok
}

proc APSMpSRFBringUpToFullPower {args} {
    set rf 1
    APSStrictParseArguments {rf}

    APSMpStep "SRF${rf}: Check Whether System Is Already On" -proc "APSMpSRFSystemIsOn"
    if [catch {APSMpSRFSystemIsOn -rf $rf} state1] {
        APSMpReturn error "APSMpSRFBringUpToFullPower: Problem determining whether system is on already."
    }
    if $state1 {
        APSMpReturn ok "SRF$rf already on."
    }

    APSMpStep "SRF${rf}: Perform Manual Preparations (operator)" -proc "APSMpSRFManualPrepCheck"
    while {1} {
	if [catch {APSMpSRFManualPrepCheck -rf $rf}] {
	    if {[tk_dialog2 .warningDialog "Warning Message" \
                   "Problem with manual preparation portion of turn on\nPlease fix then click continue" \
                   warning -1 "Continue" "Abort"] == 1} {
		APSMpReturn error "APSMpSRFBringUpToFullPower: Problem with manual preparation portion of turn on. Aborted by user."
	    }
	    continue
	}
	break
    }

    if [catch {APScavget -list=SRF:P${rf}:beamCurrent -numerical -printErrors} beamCurrent] {
	APSMpReturn error "APSMpSRFBringUpToFullPower: Problem reading PVs: $beamCurrent"
    }
    if {$beamCurrent > 1} {
    	APSMpReturn error "APSMpSRFBringUpToFullPower: RF $rf beam current greater than 1A. PEM expects system to be completely off."
    }

    APSMpStep "SRF${rf}: Turn Off Rf Drive"
    if [catch {APScavput -list=S${rf}:K:rfDriveOff_C=1} result] {
	APSMpReturn error "APSMpSRFBringUpToFullPower: Problem turning off srf $rf rf drive: $result"
    }

    APSMpStep "SRF${rf}: Reset HV PS" -proc "APSMpSRFHVPSReset"
    while {1} {
	if [catch {APSMpSRFHVPSReset -rf $rf}] {
	    if {[tk_dialog2 .warningDialog "Warning Message" \
                   "Problem reseting SRF$rf HVPS\nPlease fix then click continue" \
                   warning -1 "Continue" "Abort"] == 1} {
		APSMpReturn error "APSMpSRFBringUpToFullPower: Problem reseting SRF$rf HVPS. Aborted by user."
	    }
	    continue
	}
	break
    }

    APSMpStep "SRF${rf}: Turn On Beam" -proc "APSMpSRFTurnOnBeam"
    while {1} {
	if [catch {APSMpSRFTurnOnBeam -rf $rf}] {
	    if {[tk_dialog2 .warningDialog "Warning Message" \
                   "Problem turning on SRF$rf klystron beam\nPlease fix then click continue" \
                   warning -1 "Continue" "Abort"] == 1} {
		APSMpReturn error "APSMpSRFBringUpToFullPower: Problem turning on SRF$rf klystron beam. Aborted by user."
	    }
	    continue
	}
	break
    }

    if {($rf == 2)} {
        APSMpStep "SRF${rf}: Raise Beam Voltage To 50kV" -proc "APSMpSRFRaiseBeamVoltage"
        if [catch {APSMpSRFRaiseBeamVoltage -target 50e3 -bePrecise 0 -rf $rf}] {
            APSMpReturn error "APSMpSRFBringUpToFullPower: Problem raising SRF$rf beam voltage to 50kV."
        }
        APSMpStep "SRF${rf}: Set Mod Anode To 26kV"
        if {[catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=26000} result]} {
            APSMpReturn error "Problem seting SRF$rf mod anode to 26000 Volts: $result"
        }
    } else {
        APSMpStep "SRF${rf}: Raise Beam Voltage To 70kV" -proc "APSMpSRFRaiseBeamVoltage"
        if [catch {APSMpSRFRaiseBeamVoltage -target 70e3 -bePrecise 0 -rf $rf}] {
            APSMpReturn error "APSMpSRFBringUpToFullPower: Problem raising SRF$rf beam voltage to 70kV."
        }
        APSMpStep "SRF${rf}: Set Mod Anode To 23kV"
        if {[catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=23000} result]} {
            APSMpReturn error "Problem seting SRF$rf mod anode to 23000 Volts: $result"
        }
    }
    after 1000
    APSMpStep "SRF${rf}: Turn On Mod Anode" -proc "APSMpSRFTurnOnModAnode"
    if [catch {APSMpSRFTurnOnModAnode -rf $rf -zeroValue 0}] {
        APSMpReturn error "APSMpSRFBringUpToFullPower: Problem turning on SRF$rf mod anode."
    }
    APSMpStep "SRF${rf}: Raise Beam Current To 5A" -proc "APSMpSRFRaiseBeamCurrent"
    if [catch {APSMpSRFRaiseBeamCurrent -rf $rf -target 5}] {
        APSMpReturn error "APSMpSRFBringUpToFullPower: Problem raising SRF$rf beam current to 5A."
    }
    
    APSMpStep "SRF${rf}: Raise Beam Voltage To 80kV" -proc "APSMpSRFRaiseBeamVoltage"
    if [catch {APSMpSRFRaiseBeamVoltage -target 80e3 -bePrecise 0 -rf $rf}] {
        APSMpReturn error "APSMpSRFBringUpToFullPower: Problem raising SRF$rf beam voltage to 80kV."
    }
    
    APSWaitWithUpdate -waitSeconds 5
    if {($rf == 1) || ($rf == 2) || ($rf == 4)} {
        APSMpStep "SRF${rf}: Raise Beam Voltage To 88kV" -proc "APSMpSRFRaiseBeamVoltage"
        if [catch {APSMpSRFRaiseBeamVoltage -rf $rf -target 88e3 -bePrecise 1}] {
            APSMpReturn error "APSMpSRFBringUpToFullPower: Problem raising SRF$rf beam voltage to 88kV. (expected current 5Amps)"
        }
        APSWaitWithUpdate -waitSeconds 5
    }

    APSMpStep "SRF${rf}: Turn On RF Drive" -proc "APSMpSRFTurnOnRF"
    if [catch {APSMpSRFTurnOnRF -rf $rf} result] {
        APSMpReturn error "APSMpSRFBringUpToFullPower: Problem turning on SRF$rf RF--check power monitor and interlocks: $result"
    }
    if {($rf == 2)} {
        APSMpStep "SRF${rf}: Raise Beam Current To 8.3A" -proc "APSMpSRFRaiseBeamCurrent"
        if [catch {APSMpSRFRaiseBeamCurrent -rf $rf -target 8.3}] {
            APSMpReturn error "APSMpSRFBringUpToFullPower: Problem raising SRF$rf beam current to 8.3A."
        }
    }

    APSMpStep "SRF${rf}: Reset Collector Interlock" -proc APSMpSRFResetCollectorInterlock
    if {[catch {APSMpSRFResetCollectorInterlock -rf $rf -timeLimit 60} result]} {
        APSMpReturn error "APSMpSRFBringUpToFullPower: $result"
    }
    APSMpStep "SRF${rf}: Waiting 30 seconds after resetting collector interlock"
    APSWaitWithUpdate -waitSeconds 30

    APSMpStep "SRF${rf}: Raise or Lower Average Cavity Power to 25KW" -proc "APSMpSRFRaiseOrLowerAverageCavityPower"
    if {[catch {APSMpSRFRaiseOrLowerAverageCavityPower -rf $rf -target 25} result]} {
        APSMpReturn error "APSMpSRFBringUpToFullPower: Problem raising SRF$rf average cavity power to 25KW. $result"
    }

    APSMpStep "SRF${rf}: Check Gap Voltage AGC loop setpoint"
    while {1} {
        if {($rf == 1) || ($rf == 4)} {
            if {[catch {APScavget -list=BRF:S:FB2:pidSpCh1AO} result]} {
                APSMpReturn error "APSMpSRFBringUpToFullPower: Problem reading SRF$rf AGC Loop setpoint: $result"
            }
        } else {
            if {[catch {APScavget -list=BRF:S:FB2:pidSpCh0AO} result]} {
                APSMpReturn error "APSMpSRFBringUpToFullPower: Problem reading SRF$rf AGC Loop setpoint: $result"
            }
        }
        if {($result < .8) || ($result > 1.0)} {
            if {[tk_dialog2 .warningDialog "Warning Message" \
                   "The gap voltage AGC loop setpoint for SRF $rf is not between .8 and 1.0\nPlease fix then click continue" \
                   warning -1 "Continue" "Abort"] == 1} {
                APSMpReturn error "APSMpSRFBringUpToFullPower: The gap voltage AGC loop setpoing was out of range. Aborted by user."
            }
            continue
        }
        break
    }

    APSMpStep "SRF${rf}: Turn on Gap Voltage AGC FB Control"
    if {($rf == 1) || ($rf == 4)} {
        if {[catch {APScavput -list=SRF:AGC:OpsManualCtl1BO=1} result]} {
            APSMpReturn error "APSMpSRFBringUpToFullPower: Problem with SRF$rf AGC FB Control: $result"
        }
    } else {
        if {[catch {APScavput -list=SRF:AGC:OpsManualCtl2BO=1} result]} {
            APSMpReturn error "APSMpSRFBringUpToFullPower: Problem with SRF$rf AGC FB Control: $result"
        }
    }
    if {($rf == 1) || ($rf == 4)} {
        if {[catch {APScavput -list=SRF:AGC:FB_SoftEngage1BO=1} result]} {
            APSMpReturn error "APSMpSRFBringUpToFullPower: Problem with SRF$rf AGC FB Control: $result"
        }
    } else {
        if {[catch {APScavput -list=SRF:AGC:FB_SoftEngage2BO=1} result]} {
            APSMpReturn error "APSMpSRFBringUpToFullPower: Problem with SRF$rf AGC FB Control: $result"
        }
    }

    APSMpStep "SRF${rf}: Check Gap Voltage AGC Loop Closed"
    if {($rf == 1) || ($rf == 4)} {
        if {[catch {APScavget -list=S1:K:FB_CavTuneSumCC -printErrors} cavTune]} {
            APSMpReturn error "APSMpSRFBringUpToFullPower: $cavTune"
        }
    } else {
        if {[catch {APScavget -list=S2:K:FB_CavTuneSumCC -printErrors} cavTune]} {
            APSMpReturn error "APSMpSRFBringUpToFullPower: $cavTune"
        }
    }
    if {$cavTune != 1} {
        if {[tk_dialog2 .warningDialog "Warning Message" \
               "AGC for SRF$rf is not tuned. \nPlease fix then click continue" \
               warning -1 "Continue" "Abort"] == 1} {
            APSMpReturn error "APSMpSRFBringUpToFullPower: AGC for SRF$rf is not tuned. Aborted by user."
        }
    }
    APSWaitWithUpdate -waitSeconds 10
    if {($rf == 1) || ($rf == 4)} {
        if {[catch {APScavget -list=SR:C:S38_40TotalGapCC -printErrors} gapVoltage]} {
            APSMpReturn error "APSMpSRFBringUpToFullPower: $gapVoltage"
        }
    } else {
        if {[catch {APScavget -list=SR:C:S36_37TotalGapCC -printErrors} gapVoltage]} {
            APSMpReturn error "APSMpSRFBringUpToFullPower: $gapVoltage"
        }
    }
    if {$gapVoltage < 4400} {
        if {[tk_dialog2 .warningDialog "Warning Message" \
               "AGC Gap Voltage for SRF$rf is lower than 4400KV. \nPlease fix then click continue" \
               warning -1 "Continue" "Abort"] == 1} {
            APSMpReturn error "APSMpSRFBringUpToFullPower: AGC Gap Voltage for SRF$rf is lower than 4400KV. Aborted by user."
        }
    }
    
    if {($rf == 2) || ($rf == 3)} {
        if {[catch {APScavget -list=SRF:AGC:FBout_sys2AI -printErrors} feedbackOutput]} {
            APSMpReturn error "APSMpSRFBringUpToFullPower: $feedbackOutput"
        }
        while {$feedbackOutput > 2.0} {
            APSMpStep "SRF${rf}: Lowering Mod Anode to get Feedback Output < 2.0"
            
            if [catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=125 -delta} result] {
                APSMpReturn error "Problem setting RF $rf mod anode voltage: $result"
            }
            after 4000
            if {[catch {APScavget -list=SRF:AGC:FBout_sys2AI -printErrors} feedbackOutput]} {
                APSMpReturn error "APSMpSRFBringUpToFullPower: $feedbackOutput"
            }
        }
    }
    if {($rf == 1) || ($rf == 4)} {
        if {[catch {APScavget -list=SRF:AGC:FBout_sys1AI -printErrors} feedbackOutput]} {
            APSMpReturn error "APSMpSRFBringUpToFullPower: $feedbackOutput"
        }
        while {$feedbackOutput > 2.0} {
            APSMpStep "SRF${rf}: Lowering Mod Anode to get Feedback Output < 2.0"
            
            if [catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=125 -delta} result] {
                APSMpReturn error "Problem setting RF $rf mod anode voltage: $result"
            }
            after 4000
            if {[catch {APScavget -list=SRF:AGC:FBout_sys1AI -printErrors} feedbackOutput]} {
                APSMpReturn error "APSMpSRFBringUpToFullPower: $feedbackOutput"
            }
        }
    }
    
    

    APSMpReturn ok
}

proc APSMpSRFSystemIsOn {args} {
    set level 180
    set rf 1
    APSStrictParseArguments {level rf}

    # check if system is on at operating levels
    if [catch {APScavget -numerical \
                 -list=S${rf}:K:RfIntrTallyOK,SRF:P${rf}:faultInterlock,SRF:K${rf}:ED1:Ch1KWatt -printErrors} results] {
        APSMpReturn error $results
    }
    if {[lindex $results 0]==1 && [lindex $results 1]==1 && \
          [lindex $results 2]>$level} {
        APSMpReturn ok 1
    }
    APSMpReturn ok 0
}

proc APSMpSRFManualPrepCheck {args} {
    set rf 1
    APSStrictParseArguments {rf}
    # check state of klystron magnets, ion pump, and heater
    global status
    set problems 0
    if [catch {APScavget -list=SRF:P${rf}:mag1Supply -list=Current,OnOff,Ready -numerical -printErrors} result] {
        return -code error "Problem getting status of RF $rf magnet 1 supply: $result"
    }
    if [string compare [join $result] "0 1 1"]!=0 {
        set status "RF $rf Magnet 1 supply not ready."
        incr problems
    }
    if [catch {APScavget -list=SRF:P${rf}:mag2Supply -list=Current,OnOff,Ready -numerical -printErrors} result] {
        return -code error "Problem getting status of RF $rf magnet 1 supply: $result" 
    }
    if [string compare [join $result] "0 1 1"]!=0 {
        set status "RF $rf Magnet 2 supply not ready."
        incr problems
    }
    if [catch {APScavget -list=SRF:P${rf}:ionPump -list=OnOff,Ready -numerical -printErrors} result] {
        return -code error "Problem getting status of RF $rf ion pump: $result"
    }
    if [string compare [join $result] "1 1"]!=0 {
        set status "RF $rf Ion pump not ready."
        incr problems
    }
    if [catch {APScavget -list=SRF:P${rf}:heater -list=OnOffStatus,SupplyReady -numerical -printErrors} result] {
        return -code error "Problem getting status of RF $rf heater: $result"
    }
    if [string compare [join $result] "1 1"]!=0 {
        set status "RF $rf Heater not ready."
        incr problems
    }
    if [catch {APScavget -list=SRF:P${rf}:disconnectSwClose -printErrors} result] {
        return -code error "Problem getting status of RF $rf disconnect switch: $result"
    }
    if [string compare $result CLOSED]!=0 {
        set status "RF $rf Disconnect switch not closed."
        incr problems
    }
    return -code ok [expr !$problems]
}

proc APSMpSRFLowerBeamCurrent {args} {
    set target 0
    set rf 1
    APSStrictParseArguments {target rf}
    
    # if SRF:P1:beamCurrent>target
    #   lower mod anode voltage in 1000V steps to get target.
    #   don't exceed mod anode limit 
    set steps 0
    set increment -1000
    while 1 {
        if [catch {APSSRFCheckCathodeSupply -rf $rf}] {
            APSMpReturn error "RF $rf Cathode supply not on."
        }
        if [catch {APSSRFCheckModAnodeSupply -rf $rf}] {
            APSMpReturn error "RF $rf Mod anode supply not on."
        }
        if [catch {APScavget -list=SRF:P${rf}:beamCurrent -printErrors} current] {
            APSMpReturn error "Problem getting RF $rf beam current: $result"
        }
        if {$steps == 0} {
            if {$current < [expr {$target + .08}]} {
                break
            }
        } else {
            if {$current < $target} {
                break
            }
        }
        # go slow near the end
        if [expr ($current-$target)<0.25] {
            set increment -125
        } elseif [expr ($current-$target)<0.5] {
            set increment -250
        }
        if [catch {APSSRFCheckCathodeSupply -rf $rf}] {
            APSMpReturn error "RF $rf Cathode supply not on."
        }
        if [catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=$increment -delta} result] {
            APSMpReturn error "Problem setting RF $rf mod anode voltage: $result"
        }
        incr steps
        after 4000
        update
    }
    APSMpReturn ok
}

proc APSSRFCheckCathodeSupply {args} {
    set rf 1
    APSStrictParseArguments {rf}
    if {[catch {APScavget -list=SRF:P${rf}:cathodeSupplyOnOff -numerical -printErrors} result] || \
          [string compare $result 0]==0} {
        catch {APScavput -list=SRF:P${rf}:=0 -list=beamVoltageAdj,modAnodeVoltageAdj}
        return -code error 
    }
    return -code ok
}

proc APSSRFCheckModAnodeSupply {args} {
    set rf 1
    APSStrictParseArguments {rf}
    if {[catch {APScavget -list=SRF:P${rf}:modAnodeOnOff -numerical -printErrors} result] || \
          [string compare $result 0]==0} {
        catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=0}
        return -code error 
    }
    return -code ok
}

proc APSMpSRFHVPSReset {args} {
    set rf 1
    APSStrictParseArguments {rf}
    # if not SRF:P5:highVoltageReady=READY
    #    press SRF:P5:resetCtl to reset
    # if not SRF:P5:faultInterlock=READY
    #    check items under interlocks/status
    if [catch {APScavget -list=SRF:P${rf}:highVoltageReady -printErrors} result] {
        APSMpReturn error "Problem getting SRF$rf HVPS status: $result"
    } 
    if [string compare $result READY]==0 {
        APSMpReturn ok
    }
    if [catch {APScavput -list=S${rf}:K:RfAcisRst=1 -num} result] {
        APSMpReturn error "Problem reseting SRF$rf HVPS: $result"
    }
    after 2000
    if [catch {APScavput -list=SRF:P${rf}:resetCtl=RESET} result] {
        APSMpReturn error "Problem reseting SRF$rf HVPS: $result"
    }
    for {set try 0} {$try<3} {incr try}  {
        after 2000
        if [catch {APScavget -list=SRF:P${rf}:highVoltageReady -printErrors} result] {
            APSMpReturn error "Problem getting SRF$rf HVPS status: $result"
        } 
        if [string compare $result READY]==0 {
            APSMpReturn ok
        }
    }
    APSMpReturn error "SRF$rf HVPS did not reset"
}

proc APSMpSRFTurnOnBeam {args} {
    set rf 1
    APSStrictParseArguments {rf}
    # if SRF:P5:beamVoltageAdj < 1e3
    #   send 0 to SRF:P5:beamVoltageAdj
    #   press SRF:P5:cathodeSupplySw.PROC
    #   check SRF:P5:cathodeSupplyOnOff=ON,

    APSWaitWithUpdate -waitSeconds 10

    for {set try 0} {$try<3} {incr try} {
        if [catch {APScavget -list=SRF:P${rf}:cathodeSupplyOnOff -numerical -printErrors} result] {
            APSMpReturn error "Problem getting SRF$rf status data: $result"
        }
        if [string compare $result 1]!=0 {
            if [catch {APScavput -list=SRF:P${rf}:beamVoltageAdj=0,SRF:P${rf}:cathodeSupplySw.PROC=1} result] {
                APSMpReturn error "Problem turning on SRF$rf cathode supply: $result"
            }
            after 2000
        } else {
            break
        }
    }
    if $try==3 {
        set choice \
          [APSMultipleChoice [APSUniqueName .] -modal 1 \
             -question "Problem getting SRF$rf cathode supply to turn on.  You may need to do this locally.  If you are able to do this, then hit Proceed, otherwise hit Abort." \
             -labelList {Proceed Abort} -returnList {Proceed Abort} \
             -contextHelp "Dialog for choosing what action to take when automatic procudure is unable to turn on the cathode power supply."]
        switch $choice {
            Abort {
                APSMpReturn error "Unable to turn on SRF$rf cathode supply."
            }
            Proceed {
                if [catch {APScavget -list=SRF:P${rf}:cathodeSupplyOnOff -numerical -printErrors} result] {
                    APSMpReturn error "Problem getting SRF$rf status data: $result"
                }
                if [string compare $result 1]!=0 {
                    APSMpReturn error "SRF$rf Cathode supply not on---can't proceed."
                }
            }
        }
    }
    APSMpReturn ok
}

proc APSMpSRFRaiseBeamVoltage {args} {
    set rf 1
    set target 0
    set expectedCurrent 0
    set currentTolerance 0
    set bePrecise 1
    APSStrictParseArguments {target expectedCurrent bePrecise currentTolerance rf}
    # check for SRF:P5:beamVoltage>target
    # if not:
    #   send target value to SRF:P5:beamVoltageAdj
    #   wait 10s
    #   check SRF:P5:beamVoltage
    if [catch {APScavget -list=SRF:P${rf}:beamVoltage -printErrors} beamVoltage] {
        APSMpReturn error "Problem getting value of SRF$rf beam voltage reference."
    }
    if {$beamVoltage>=$target} {
        APSMpReturn ok "SRF$rf Beam voltage at $beamVoltage---not changed."
    }

    if [catch {APScavget -list=SRF:P${rf}:cathodeVReference -printErrors} vReference] {
        APSMpReturn error "Problem getting value of SRF$rf beam voltage reference"
    }
    for {set vSet [expr $vReference+1e3]} {$vSet<$target} {set vSet [expr $vSet+1e3]} {
        if [catch {APSSRFCheckCathodeSupply -rf $rf}] {
            APSMpReturn error "SRF$rf Cathode supply not on."
        }
        if [catch {APScavput -list=SRF:P${rf}:beamVoltageAdj=$vSet} result] {
            APSMpReturn error "Problem sending value for SRF$rf beam voltage."
        }
        after 500
        update
    }

    if $bePrecise {
        if [catch {APSMpSRFAdjustBeamVoltage -rf $rf -target $target \
                     -expectedCurrent $expectedCurrent \
                     -currentTolerance $currentTolerance} result] {
            APSMpReturn error "Problem adjusting SRF$rf beam voltage: $result"
        }
    }
    APSMpReturn ok
}

proc APSMpSRFLowerBeamVoltage {args} {
    set rf 1
    set target 0
    set expectedCurrent 0
    set currentTolerance 0
    APSStrictParseArguments {target expectedCurrent currentTolerance rf}
    # check for SRF:P5:beamVoltage>target
    # if not:
    #   send target value to SRF:P5:beamVoltageAdj
    #   wait 10s
    #   check SRF:P5:beamVoltage
    if [catch {APScavget -list=SRF:P${rf}:beamVoltage -printErrors} beamVoltage] {
        APSMpReturn error "Problem getting value of SRF$rf beam voltage reference."
    }
    if {$beamVoltage<=$target} {
        APSMpReturn ok "SRF$rf Beam voltage at $beamVoltage---not changed."
    }

    if [catch {APScavget -list=SRF:P${rf}:cathodeVReference -printErrors} vReference] {
        APSMpReturn error "Problem getting value of SRF$rf beam voltage reference"
    }
    for {set vSet [expr $vReference-1e3]} {$vSet>$target} {set vSet [expr $vSet-1e3]} {
        if [catch {APSSRFCheckCathodeSupply -rf $rf}] {
            APSMpReturn error "SRF$rf Cathode supply not on."
        }
        if [catch {APScavput -list=SRF:P${rf}:beamVoltageAdj=$vSet} result] {
            APSMpReturn error "Problem sending value for SRF$rf beam voltage."
        }
        after 500
        update
    }

    APSMpReturn ok
}

proc APSMpSRFAdjustBeamVoltage {args} {
    set rf 1
    set target 0
    set expectedCurrent 0
    set currentTolerance 0
    set maxTries 10
    APSStrictParseArguments {target expectedCurrent currentTolerance maxTries rf}

    # zero in on exact value by iterating on the difference
    for {set try 0} {$try<$maxTries} {incr try} {
        if [catch {APSSRFCheckCathodeSupply -rf $rf}] {
            APSMpReturn error "SRF$rf Cathode supply not on."
        }
        if [catch {APScavget -list=SRF:P${rf}:beamVoltage -printErrors} beamVoltage] {
            APSMpReturn error "Problem getting value of SRF$rf beam voltage."
        }
        set adjustment [expr $target-$beamVoltage]
        set sleepFor 5000
        if $adjustment<0 {
            set sign -1
        } else {
            set sign 1
        }
        if [expr abs($adjustment)<20] {
            APSMpReturn ok
        }
        if [expr abs($adjustment)>2e3] {
            set adjustment [expr $sign*1e3]
            set sleepFor 2000
        } elseif [expr abs($adjustment)>1e3] {
            set adjustment [expr $sign*1e3]
        }
        if [catch {APScavput -list=SRF:P${rf}:beamVoltageAdj=$adjustment -delta} result] {
            APSMpReturn error "Problem sending value for SRF$rf beam voltage."
        }
        after $sleepFor
        update
    }
    if [expr abs($adjustment)>40] {
        APSMpReturn error "Didn't get within expected tolerance on SRF$rf beam voltage."
    }

    # check the beam current
    if $expectedCurrent>0 {
        after 4000
        if [catch {APScavget -list=SRF:P${rf}:beamCurrent -printErrors} current] {
            APSMpReturn error "Problem getting value of SRF$rf beam current"
        }
        set delta [expr abs($current-$expectedCurrent)]
        if {$delta>$currentTolerance} {
            APSMpReturn error "Problem setting SRF$rf beam voltage---system not responding within tolerance of $currentTolerance A.  Expected $expectedCurrent, got $current."
        }
    }
    APSMpReturn ok
}

proc APSMpSRFTakeOutOfDiodeMode {args} {
    set rf 1
    APSStrictParseArguments {rf}
    # check if system is on at operating levels
    if [catch {APScavget -numerical \
                 -list=S${rf}:K:RfIntrTallyOK,SRF:P${rf}:faultInterlock,SRF:K${rf}:ED1:Ch1KWatt,SRF:P${rf}:anodeVoltage -printErrors} results] {
        APSMpReturn error $results
    }
    if {[lindex $results 0]==1 && [lindex $results 1]==1 && \
          [lindex $results 2]>50} {
        # more than 50 kW RF power---not diode mode
        APSMpReturn ok
    }
    if [expr [lindex $results 3]>20e3] {
        # mod anode too high
        APSMpReturn ok
    }
    if [catch {APSMpSRFLowerModAnode -target 10e3 -rf $rf} result] {
        APSMpReturn error "Problem lowering SRF$rf mod anode voltage: $result"
    }
    APSMpReturn ok 
}

proc APSMpSRFLowerModAnode {args} {
    set rf 1
    set target 0
    APSStrictParseArguments {target rf}
    while 1 {
        if [catch {APScavget -list=SRF:P${rf}:anodeVoltage -printErrors} voltage] {
            APSMpReturn error "Problem reading SRF$rf mod anode voltage: $voltage"
        }
        set diff [expr $voltage-$target]
        if $diff>0 {
            if $diff>1000 {
                if [catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=-1000 -delta} result] {
                    APSMpReturn error "Problem changing SRF$rf mod anode voltage: $result"
                }
            } else {
                if [catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=$target} result] {
                    APSMpReturn error "Problem changing SRF$rf mod anode voltage: $result"
                }
                APSMpReturn ok
            }
        } else {
            APSMpReturn ok
        }
        after 1000
        update
    }
}

proc APSMpSRFTurnOnModAnode {args} {
    set rf 1
    set zeroValue 1
    APSStrictParseArguments {rf zeroValue}
    # check SRF:P5:modAnodeReady=READY, SRF:P5:modAnodeOnOff=OFF
    # if ok:
    #   send 0 to SRF:P5:modAnodeVoltageAdj
    #   press SRF:P5:modAnodeSw.PROC
    #   check SRF:P5:modAnodeOnOff=ON
    if [catch {APScavget -list=SRF:P${rf}: -list=modAnodeReady,modAnodeOnOff -printErrors} result] {
        APSMpReturn error "Problem getting status for SRF$rf mod anode: $result"
    }
    if [string compare [lindex $result 0] READY] {
        APSMpReturn error "SRF$rf Mod anode is not ready to be turned on.  Check interlocks."
    }
    if [string compare [lindex $result 1] OFF] {
        APSMpReturn ok "SRF$rf Mod anode already on."
    }
    if {$zeroValue} {
        if {[catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=0; after 1000} result]} {
            APSMpReturn error "Problem turning on SRF$rf mod anode: $result"
        }
    }
    if {[catch {APScavput -list=SRF:P${rf}:modAnodeSw.PROC=1; after 1000} result]} {
        APSMpReturn error "Problem turning on SRF$rf mod anode: $result"
    }
    for {set try 0} {$try<6} {incr try} {
        after 1500 
        if [catch {APScavget -list=SRF:P${rf}:modAnodeOnOff -printErrors} result] {
            APSMpReturn error "Problem getting status for SRF$rf mod anode: $result"
        }
        if [string compare $result ON]==0 {
            APSMpReturn ok
        }
    }
    APSMpReturn error "SRF$rf Mod anode did not turn on (state is $result)."
}

proc APSMpSRFRaiseModAnode {args} {
    set rf 1
    set target 0
    APSStrictParseArguments {target rf}

    # if SRF:P5:anodeVoltage<target
    #   send target to SRF:P5:modAnodeVoltageAdj 
    if [catch {APScavget -list=SRF:P{$rf}:anodeVoltage -printErrors} voltage] {
        APSMpReturn error "Problem getting SRF$rf mod anode voltage: $voltage"
    }
    if $voltage>=$target {
        APSMpReturn ok "SRF$rf Mod anode voltage already at $voltage---not changed."
    }
    if [catch {APSSRFCheckCathodeSupply -rf $rf}] {
        APSMpReturn error "SRF$rf Cathode supply not on."
    }
    if [catch {APSSRFCheckModAnodeSupply -rf $rf}] {
        APSMpReturn error "SRF$rf Mod anode supply not on."
    }
    if [catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=$target} result] {
        APSMpReturn error "Problem changing SRF$rf mod anode voltage: $result"
    }
}

proc APSMpSRFRaiseBeamCurrent {args} {
    set rf 1
    set target 0
    APSStrictParseArguments {target rf}
    
    # if SRF:P5:beamCurrent<target
    #   raise mod anode voltage in 1000V steps to get target.
    #   if asked, wait for SRF:K5:CollectorSupT_AI to stabilize at 30.5-30.7degC
    #   don't exceed mod anode limit 
    set steps 0
    set increment 1000
    while 1 {
        if [catch {APSSRFCheckCathodeSupply -rf $rf}] {
            APSMpReturn error "SRF$rf Cathode supply not on."
        }
        if [catch {APSSRFCheckModAnodeSupply -rf $rf}] {
            APSMpReturn error "SRF$rf Mod anode supply not on."
        }
        if [catch {APScavget -list=SRF:P${rf}:beamCurrent -printErrors} current] {
            APSMpReturn error "Problem getting SRF$rf beam current: $result"
        }
        if $current>$target {
            break
        }
        # go slow near the end
        if [expr ($target-$current)<0.25] {
            set increment 125
        } elseif [expr ($target-$current)<0.5] {
            set increment 250
        }
        if [catch {APSSRFCheckCathodeSupply -rf $rf}] {
            APSMpReturn error "SRF$rf Cathode supply not on."
        }
        if [catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=$increment -delta} result] {
            APSMpReturn error "Problem setting SRF$rf mod anode voltage: $result"
        }
        incr steps
        after 4000
        update
    }
    APSMpReturn ok
}

proc APSMpSRFFullPowerFromStandby {args} {
    global status

    set finalCurrent 11.5
    set rf 1
    APSStrictParseArguments {rf}

    if [catch {APScavget -list=SRF:P${rf}:beamVoltageAdj,SRF:P${rf}:modAnodeVoltageAdj,SRF:P${rf}:beamCurrent,SRF:P${rf}:cathodeSupplyOnOff,SRF:P${rf}:highVoltageReady,SRF:P${rf}:modAnodeOnOff,SRF:P${rf}:modAnodeReady -numerical -printErrors} results] {
        APSMpReturn error "Problem reading PVs: $results"
    }
    #ARE THESE LEVELS VALID
    if {$rf == 1} {
        set beamVoltageAdjMin 65000
        set modAnodeVoltageAdjMin 18000
        set beamCurrentMin 4.5
    } elseif {$rf == 2} {
        set beamVoltageAdjMin 65000
        set modAnodeVoltageAdjMin 18000
        set beamCurrentMin 4.5
    } elseif {$rf == 3} {
        set beamVoltageAdjMin 65000
        set modAnodeVoltageAdjMin 18000
        set beamCurrentMin 4.5
    } elseif {$rf == 4} {
        set beamVoltageAdjMin 65000
        set modAnodeVoltageAdjMin 18000
        set beamCurrentMin 4.5
    }

    if {([lindex $results 0] < $beamVoltageAdjMin) || ([lindex $results 1] < $modAnodeVoltageAdjMin) || ([lindex $results 2] < $beamCurrentMin) || ([lindex $results 3] != 1) || ([lindex $results 4] != 1) || ([lindex $results 5] != 1) || ([lindex $results 6] != 1)} {
        APSMpReturn ok "SRF$rf is not in a valid standby mode"
    }

    APSMpStep "SRF${rf}: Raise Beam Current To 9.0A" -proc "APSMpSRFRaiseBeamCurrent"
    if [catch {APSMpSRFRaiseBeamCurrent -rf $rf -target 9.0}] {
        APSMpReturn error "Problem raising SRF$rf beam current to 9.0A."
    }

    APSMpStep "SRF${rf}: Turn On RF Drive" -proc "APSMpSRFTurnOnRF"
    if [catch {APSMpSRFTurnOnRF -rf $rf} result] {
        APSMpReturn error "Problem turning on SRF$rf RF--check power monitor and interlocks: $result"
    }

    APSMpStep "SRF${rf}: Wait For Tuners To Move"
    APSWaitWithUpdate -waitSeconds 20 -updateInterval 1

    APSMpStep "SRF${rf}: Raise Beam Current To 10A" -proc "APSMpSRFRaiseBeamCurrent"
    if [catch {APSMpSRFRaiseBeamCurrent -rf $rf -target 10}] {
        APSMpReturn error "Problem raising SRF$rf beam current to 10A."
    }

    APSMpStep "SRF${rf}: Wait For Stabilization"
    APSWaitWithUpdate -waitSeconds 10

    APSMpStep "SRF${rf}: Raise Power To Final Level ($finalCurrent Amps)" -proc "APSMpSRFRaisePower"
    if [catch {APSMpSRFRaisePower -rf $rf -finalCurrent $finalCurrent -collectorLimit 1375 -modAnodeLimit 40e3} result] {
        APSMpReturn error "Problem raising SRF$rf power level: $result"
    }

    APSMpReturn ok
}

proc APSMpSRFTurnOnRF {args} {
    set rf 1
    APSStrictParseArguments {rf}
    lappend testPVList S${rf}:K:PmRfFltSum S${rf}:K:rfDriveStatM S${rf}:K:RfIntrTallyOK
    lappend desiredTestValList 0 1 1
    lappend resetPVList S${rf}:K:PmMasterRst S${rf}:K:rfDriveOn_C S${rf}:K:rfInterlockReset
    lappend resetValList 1 ON RESET
    lappend descripList "power monitor" "rf drive" "rf interlock" 
    # if B:K:pwrMonDirBit1=0 (power monitor)
    #    send B:K:PmMasterRst=1
    # if B:K:rfDriveInhibit=OFF:
    #    send B:K:rfDriveInhibit=ON
    # if B:K:RfInterlockBI=FAULT
    #    send B:K:RfInterlockBO=RESET
    # stop and start the rf ramps
    # check for rf power

    global status
    if [catch {APSSRFCheckCathodeSupply -rf $rf}] {
        APSMpReturn error "SRF$rf Cathode supply not on."
    }
    if [catch {APSSRFCheckModAnodeSupply -rf $rf}] {
        APSMpReturn error "SRF$rf Mod anode supply not on."
    }
    set index 0
    foreach testPV $testPVList {
        set resetPV [lindex $resetPVList $index]
        set resetVal [lindex $resetValList $index]
        for {set try 0} {$try<3} {incr try} {
            if [catch {APScavget -list=$testPV -numerical -printErrors} result] {
                APSMpReturn error "Problem reading PV $testPV: $result"
            }
            if [string compare $result [lindex $desiredTestValList $index]]==0 \
              break
            set status "Reseting SRF$rf [lindex $descripList $index] (now $result)"
            bell
            if [catch {APScavput -list=$resetPV=$resetVal} results] {
                APSMpReturn error "Problem setting PV $resetPV ([lindex $descripList $index]): $results"
            }
            after 2000
        }
        if [string compare $result [lindex $desiredTestValList $index]] {
            APSMpReturn error "SRF$rf Failed to reset [lindex $descripList $index]"
        }
        incr index
    }
    after 2000
    if {$rf == 2} {
        APSMpStep "SRF${rf}: Raise Beam Current To 8.3A" -proc "APSMpSRFRaiseBeamCurrent"
        if [catch {APSMpSRFRaiseBeamCurrent -rf $rf -target 8.3}] {
            APSMpReturn error "APSMpSRFBringUpToFullPower: Problem raising SRF$rf beam current to 8.3A."
        }
    }

    if [catch {APSSRFCheckAveragePower -rf $rf -require 5.5} result] {
        APSMpReturn error "$result"
    }

    APSMpReturn ok
}

proc APSSRFCheckForwardPower {args} {
    set require 0
    set safeLevel 34000.0
    set rf 1
    APSStrictParseArguments {require safeLevel rf}
    
    set try 1
    while {1} {
        if [catch {APScavget -list=SRF:K${rf}:ED1:Ch1KWatt -printErrors} fwdPwr] {
            APSMpReturn error "Problem reading SRF$rf forward power: $fwdPwr"
        }
        if {$fwdPwr<$require} {
            if {$try > 3} {
                set answer [tk_dialog2 .warningDialog "Warning Message" \
                              "SRF$rf Forward power of $fwdPwr less than required $require" \
                              warning -1 "Continue" "Check Again" "Abort"]
                if {$answer == 2} {
                    if {$safeLevel>0} {
                        catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=$safeLevel}
                    }
                    APSMpReturn error "SRF$rf Forward power of $fwdPwr less than required $require"
                }
                if {$answer == 0} {
                    APSMpReturn ok
                }
                set try 0
            }
            after 1000
            incr try
        } else {
            APSMpReturn ok
        }
    }
    APSMpReturn ok
}


proc APSMpSRFRaisePower {args} {
    set forwardTarget 0
    set finalCurrent 0
    set collectorLimit 0
    set modAnodeLimit 0
    set rf 1
    APSStrictParseArguments {forwardTarget finalCurrent collectorLimit modAnodeLimit rf}

    # while forwardTarget > SRF:K5:ED1:Ch1KWatt &&
    #       collectorLimit > SRF:K5:PCollectorCC &&
    #       modAnodeLimit > SRF:P5:anodeVoltage-1e3
    #   raise mod anode by 1000
    set increment 500
    while 1 {
        if {[catch {APSSRFCheckCathodeSupply -rf $rf}]} {
            APSMpReturn error "SRF$rf Cathode supply not on."
        }
        if {[catch {APSSRFCheckModAnodeSupply -rf $rf}]} {
            APSMpReturn error "SRF$rf Mod anode supply not on."
        }
        if {[catch {APScavget -list=SRF:K${rf}:ED1:Ch1KWatt,SRF:K${rf}:CollectorCalAI,SRF:P${rf}:anodeVoltage,SRF:P${rf}:beamCurrent -printErrors} results]} {
            APSMpReturn error "Problem reading PVs: $result"
        }
        set fwdPwr [lindex $results 0]
        set finalCur [lindex $results 3]
        if {$finalCur > $finalCurrent} {
            APSMpReturn ok
        }
        if {$fwdPwr < 180} {
            catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=34e3} 
            APSMpReturn error "SRF$rf Less that 180kW forward power---can't proceed"
        }
        # slow down near end to avoid overshooting
        if {[expr $finalCurrent - $finalCur] < .4} {
            set increment 50
        } elseif {[expr $finalCurrent - $finalCur] < 1} {
            set increment 250
        }
        set colPwr [lindex $results 1]
        set anode  [expr [lindex $results 2]+$increment]
        if {$colPwr > $collectorLimit} {
            catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=34e3}
            APSMpReturn error "SRF$rf Collector power was $colPwr, which is in excess of limit of $collectorLimit"
        }
        if {$anode > $modAnodeLimit} {
            APSMpReturn error "Can't raise SRF$rf forward power---would exceed mod anode limit of $modAnodeLimit"
        }
        if {[catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=$increment -delta} result]} {
            APSMpReturn error "Problem setting SRF$rf mod anode voltage: $result"
        }
        APSWaitWithUpdate -waitSeconds 5 -updateInterval 1
    }
}

proc APSMpSRFShutdownFromStandby {args} {
    set rf 1
    APSStrictParseArguments {rf}
    if [catch {APScavget -list=S${rf}:K:rfDriveStatM,SRF:P${rf}:beamCurrent,SRF:P${rf}:modAnodeOnOff -numerical -printErrors} results] {
        APSMpReturn error "Problem reading PVs: $results"
    }
    if {[lindex $results 0] != 0} {
        APSMpReturn error "SRF$rf RF Drive is still on"
    }	
    if {[lindex $results 1] > 6} {
        APSMpReturn error "SRF$rf Beam current is not in standby mode"
    }

    #    APSMpStep "SRF${rf}: Lower Mod Anode To 0" -proc "APSMpSRFLowerModAnode"
    #    APSMpSRFLowerModAnode -rf $rf -target 0 
    
    if [catch {APScavget -list=SRF:P${rf}:modAnodeOnOff -numerical -printErrors} result] {
        APSMpReturn error "Problem reading SRF:P${rf}:modAnodeOnOff: $result"
    }
    if {$result != 0} { 
        APSMpStep TurnOffModAnode
        if {[catch {APScavput -list=SRF:P${rf}:modAnodeSw.PROC=1} result]} {
            APSMpReturn error "Problem turning on SRF$rf mod anode: $result"
        }
        after 1000
    }
    APSMpStep "SRF${rf}: Set Mod Anode To 0"
    if {[catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=0} result]} {
        APSMpReturn error "Problem seting SRF$rf mod anode to 0 Volts: $result"
    }
    after 1000

    APSMpStep "SRF${rf}: Lower Beam Voltage To 30KV" -proc "APSMpSRFLowerBeamVoltage"
    APSMpSRFLowerBeamVoltage -rf $rf -target 30e3 

    APSMpStep "SRF${rf}: Lower Beam Voltage To 0KV" -proc "APSMpSRFLowerBeamVoltage"
    APSMpSRFLowerBeamVoltage -rf $rf -target 0 -tolerance 4500

    APSMpStep "SRF${rf}: Turn Off Cathode Supply (if needed)"
    if [catch {APScavget -list=SRF:P${rf}:cathodeSupplyOnOff -numerical -printErrors} result] {
        APSMpReturn error "Problem reading SRF:P${rf}:cathodeSupplyOnOff: $result"
    }
    if {$result != 0} {
        if [catch {APScavput -list=SRF:P${rf}:cathodeSupplySw.PROC=1} result] {
            APSMpReturn error "Problem turning off SRF$rf beam: $result"
        }
    }

    APSMpStep "SRF${rf}: Lower Beam Voltage to 0"
    APSMpSRFLowerBeamVoltage -rf $rf -target 0 -tolerance 500
    APSMpReturn ok
}

proc APSMpSRFLowerBeamVoltage {args} {
    set target 0
    set tolerance 3000
    set rf 1
    APSStrictParseArguments {target tolerance rf}
    # check for SRF:P5:beamVoltage<target
    # if not:
    #   send target value to SRF:P5:beamVoltageAdj
    if [catch {APScavget -list=SRF:P${rf}:beamVoltage -printErrors} beamVoltage] {
        APSMpReturn error "Problem getting value of SRF$rf beam voltage"
    }
    if {$beamVoltage<$target} {
        APSMpReturn ok "SRF$rf Beam voltage at $beamVoltage---not changed."
    }
    if [catch {APScavput -list=SRF:P${rf}:beamVoltageAdj=$target} result] {
        APSMpReturn error "Problem sending value for SRF$rf beam voltage."
    }

    global status
    set status "Waiting for SRF$rf voltage to fall...[clock format [clock seconds] -format %H:%M:%S]"
    set index 0
    while 1 {
        if [catch {APScavget -list=SRF:P${rf}:beamVoltage -printErrors} result] {
            APSMpReturn error $result
        }
        set diff [expr ($result-$target)]
        if $diff<$tolerance {
            APSMpReturn ok 
        }
        APSWaitWithUpdate -waitSeconds 5 -updateInterval 1
        update
        set status "Waiting for SRF$rf voltage to fall...[clock format [clock seconds] -format %H:%M:%S]"
        incr index
    }
    APSMpReturn ok
}


proc APSMpSRFResetCollectorInterlock {args} {
    set rf 1
    set timeLimit 60
    APSStrictParseArguments {rf timeLimit}
    if {[catch {APScavput -list=S${rf}:K:colDissInterlockReset=1} result]} {
        APSMpReturn error "APSMpSRFResetCollectorInterlock: cavput error $result"
    }
    set initTime [clock seconds]
    while {1} {
        if {[catch {APScavget -list=S${rf}:K:colDissInterlockStat -num -printErrors} result]} {
            APSMpReturn error "APSMpSRFResetCollectorInterlock: cavget error $result"
        }
        set pass 1
        foreach r $result {
            if {$r != 0} {
                set pass 0
                break
            }
        }
        if {$pass} {
            catch {APScavput -list=S${rf}:K:colDissInterlockReset=0}
            break
        }
        if {[expr [clock seconds] - $initTime] >= $timeLimit} {
            catch {APScavput -list=S${rf}:K:colDissInterlockReset=0}
            APSMpReturn error "APSMpSRFResetCollectorInterlock: Timed out doing a collector power reset"
        }
        APSWaitWithUpdate -waitSeconds 2
    }
    APSMpReturn ok
}

proc APSSRFCheckAveragePower {args} {
    set require 0
    set rf 1
    APSStrictParseArguments {require rf}
    
    set try 1
    if {($rf == 1) || ($rf == 4)} {
        while {1} {
            if [catch {APScavget -list=SRF:S38:AveragePowerM -printErrors} avgPwr] {
                APSMpReturn error "Problem reading SRF1 average power: $avgPwr"
            }
            if {$avgPwr<$require} {
                if {$try > 3} {
                    set answer [tk_dialog2 .warningDialog "Warning Message" \
                                  "SRF1 Average power of $avgPwr less than required $require" \
                                  warning -1 "Continue" "Check Again" "Abort"]
                    if {$answer == 2} {
                        APSMpReturn error "SRF1 Average power of $avgPwr less than required $require"
                    }
                    if {$answer == 0} {
                        APSMpReturn ok
                    }
                    set try 0
                }
                after 1000
                incr try
            } else {
                break
            }
        }
        while {1} {
            if [catch {APScavget -list=SRF:S40:AveragePowerM -printErrors} avgPwr] {
                APSMpReturn error "Problem reading SRF4 average power: $avgPwr"
            }
            if {$avgPwr<$require} {
                if {$try > 3} {
                    set answer [tk_dialog2 .warningDialog "Warning Message" \
                                  "SRF4 Average power of $avgPwr less than required $require" \
                                  warning -1 "Continue" "Check Again" "Abort"]
                    if {$answer == 2} {
                        APSMpReturn error "SRF4 Average power of $avgPwr less than required $require"
                    }
                    if {$answer == 0} {
                        APSMpReturn ok
                    }
                    set try 0
                }
                after 1000
                incr try
            } else {
                break
            }
        }
    } elseif {($rf == 2) || ($rf == 3)} {
        while {1} {
            if [catch {APScavget -list=SRF:S36:AveragePowerM -printErrors} avgPwr] {
                APSMpReturn error "Problem reading SRF2 average power: $avgPwr"
            }

            if {$avgPwr<$require} {
                if {$try > 3} {
                    set answer [tk_dialog2 .warningDialog "Warning Message" \
                                  "SRF2 Average power of $avgPwr less than required $require" \
                                  warning -1 "Continue" "Check Again" "Abort"]
                    if {$answer == 2} {
                        APSMpReturn error "SRF2 Average power of $avgPwr less than required $require"
                    }
                    if {$answer == 0} {
                        APSMpReturn ok
                    }
                    set try 0
                }
                after 1000
                incr try
            } else {
                break
            }
        }
        while {1} {
            if [catch {APScavget -list=SRF:S37:AveragePowerM -printErrors} avgPwr] {
                APSMpReturn error "Problem reading SRF3 average power: $avgPwr"
            }
            if {$avgPwr<$require} {
                if {$try > 3} {
                    set answer [tk_dialog2 .warningDialog "Warning Message" \
                                  "SRF3 Average power of $avgPwr less than required $require" \
                                  warning -1 "Continue" "Check Again" "Abort"]
                    if {$answer == 2} {
                        APSMpReturn error "SRF3 Average power of $avgPwr less than required $require"
                    }
                    if {$answer == 0} {
                        APSMpReturn ok
                    }
                    set try 0
                }
                after 1000
                incr try
            } else {
                break
            }
        }
    }
    APSMpReturn ok
}

proc APSMpSRFRaiseOrLowerAverageCavityPower {args} {
    set rf 1
    set target 0
    APSStrictParseArguments {target rf}
    
    if {$rf == 1} {
        set sector 40
    } elseif {$rf == 2} {
        set sector 36
    } elseif {$rf == 3} {
        set sector 37
    } elseif {$rf == 4} {
        set sector 38
    }


    if [catch {APScavget -list=SRF:S${sector}:AveragePowerM -printErrors} avgPower] {
        APSMpReturn error "Problem getting SRF$rf average power: $avgPower"
    }
    if $avgPower>$target {
        set raise 0
        set increment -1000
    } else {
        set raise 1
        set increment 1000
    }

    # if SRF:S38:AveragePowerM<target
    #   raise mod anode voltage in 1000V steps to get target.
    #   if asked, wait for SRF:K5:CollectorSupT_AI to stabilize at 30.5-30.7degC
    #   don't exceed mod anode limit 
    set steps 0
    while 1 {
        if [catch {APSSRFCheckCathodeSupply -rf $rf}] {
            APSMpReturn error "SRF$rf Cathode supply not on."
        }
        if [catch {APSSRFCheckModAnodeSupply -rf $rf}] {
            APSMpReturn error "SRF$rf Mod anode supply not on."
        }
        if [catch {APScavget -list=SRF:S${sector}:AveragePowerM -printErrors} avgPower] {
            APSMpReturn error "Problem getting SRF$rf average power: $avgPower"
        }
        if {$raise} {
            if $avgPower>$target {
                break
            }
            # go slow near the end
            if {[expr ($target - $avgPower)] < 0.25} {
                set increment 125
            } elseif {[expr ($target - $avgPower)] < 0.5} {
                set increment 250
            }
        } else {
            if $avgPower<$target {
                break
            }
            # go slow near the end
            if {[expr ($avgPower - $target)] < 0.25} {
                set increment -125
            } elseif {[expr ($avgPower - $target)] < 0.5} {
                set increment -250
            }
        }
        if [catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=$increment -delta} result] {
            APSMpReturn error "Problem setting SRF$rf mod anode voltage: $result"
        }
        incr steps
        after 4000
        update
    }
    APSMpReturn ok
}


proc APSMpSRFCheckPhaseDetectorOutputVoltages {args} {
    set rf 1
    set max .5
    APSStrictParseArguments {rf max}
    if {$rf == 1} {
        set PVs SRF:S40:PD1:Ch0 SRF:S40:PD1:Ch1 SRF:S40:PD2:Ch0 SRF:S40:PD2:Ch1
    } elseif {$rf == 2} {
        set PVs SRF:S36:PD1:Ch0 SRF:S36:PD1:Ch1 SRF:S36:PD2:Ch0 SRF:S36:PD2:Ch1
    } elseif {$rf == 3} {
        set PVs SRF:S37:PD1:Ch0 SRF:S37:PD1:Ch1 SRF:S37:PD2:Ch0 SRF:S37:PD2:Ch1
    } elseif {$rf == 4} {
        set PVs SRF:S38:PD1:Ch0 SRF:S38:PD1:Ch1 SRF:S38:PD2:Ch0 SRF:S38:PD2:Ch1
    }
    if {[catch {APScavget -list=[join $PVs ,] -num -printErrors} results]} {
        APSMpReturn error "APSMpSRFCheckPhaseDetectorOutputVoltages: $results"
    }
    foreach r $results pv $PVs {
        if {$r > $max} {
            APSMpReturn error "APSMpSRFCheckPhaseDetectorOutputVoltages: $pv greater than .5V"
        }
    }
    APSMpReturn ok
}


proc APSMpSRFBringUpToStandby {args} {
    set rf 1
    APSStrictParseArguments {rf}

    APSMpStep "SRF${rf}: Check Whether System Is Already On" -proc "APSMpSRFSystemIsOn"
    if [catch {APSMpSRFSystemIsOn -rf $rf} state1] {
        APSMpReturn error "APSMpSRFBringUpToStandby: Problem determining whether system is on already."
    }
    if $state1 {
        APSMpReturn ok "SRF$rf already on."
    }

    APSMpStep "SRF${rf}: Check For Standby Mode" 
    if [catch {exec cavget -list=SRF:P${rf}:beamVoltageAdj,SRF:P${rf}:modAnodeVoltageAdj,SRF:P${rf}:beamCurrent,SRF:P${rf}:cathodeSupplyOnOff,SRF:P${rf}:highVoltageReady,SRF:P${rf}:modAnodeOnOff,SRF:P${rf}:modAnodeReady -numerical} results] {
        APSMpReturn error "APSMpSRFBringUpToStandby: Problem reading PVs: $results"
    }
    #ARE THESE LEVELS VALID
    if {$rf == 1} {
        set beamVoltageAdjMin 65000
        set modAnodeVoltageAdjMin 18000
        set beamCurrentMin 4.5
    } elseif {$rf == 2} {
        set beamVoltageAdjMin 65000
        set modAnodeVoltageAdjMin 18000
        set beamCurrentMin 4.5
    } elseif {$rf == 3} {
        set beamVoltageAdjMin 65000
        set modAnodeVoltageAdjMin 18000
        set beamCurrentMin 4.5
    } elseif {$rf == 4} {
        set beamVoltageAdjMin 65000
        set modAnodeVoltageAdjMin 18000
        set beamCurrentMin 4.5
    }

    if {([lindex $results 0] > $beamVoltageAdjMin) && ([lindex $results 1] > $modAnodeVoltageAdjMin) && ([lindex $results 2] > $beamCurrentMin) && ([lindex $results 3] == 1) && ([lindex $results 4] == 1) && ([lindex $results 5] == 1) && ([lindex $results 6] == 1)} {
        APSMpReturn ok "SRF$rf is already in standby mode or full power mode"
    }
    if {([lindex $results 0] > $beamVoltageAdjMin) && ([lindex $results 1] > $modAnodeVoltageAdjMin) && ([lindex $results 2] > $beamCurrentMin) && ([lindex $results 3] == 1) && ([lindex $results 5] == 1)} {
        APSMpReturn ok "SRF$rf READY indicator is red"
    }
    set beamCurrent [lindex $results 2]

    APSMpStep "SRF${rf}: Perform Manual Preparations (operator)" -proc "APSMpSRFManualPrepCheck"
    while {1} {
        if [catch {APSMpSRFManualPrepCheck -rf $rf}] {
            if {[tk_dialog2 .warningDialog "Warning Message" \
                   "Problem with manual preparation portion of turn on\nPlease fix then click continue" \
                   warning -1 "Continue" "Abort"] == 1} {
                APSMpReturn error "APSMpSRFBringUpToStandby: Problem with manual preparation portion of turn on. Aborted by user."
            }
            continue
        }
        break
    }

    if {$beamCurrent > 1} {
        APSMpReturn error "APSMpSRFBringUpToStandby: RF $rf beam current greater than 1A. PEM expects system to be completely off."
    }

    APSMpStep "SRF${rf}: Turn Off Rf Drive"
    if [catch {exec cavput -list=S${rf}:K:rfDriveOff_C=1} result] {
        APSMpReturn error "APSMpSRFBringUpToStandby: Problem turning off srf $rf rf drive: $result"
    }

    APSMpStep "SRF${rf}: Reset HV PS" -proc "APSMpSRFHVPSReset"
    while {1} {
        if [catch {APSMpSRFHVPSReset -rf $rf}] {
            if {[tk_dialog2 .warningDialog "Warning Message" \
                   "Problem reseting SRF$rf HVPS\nPlease fix then click continue" \
                   warning -1 "Continue" "Abort"] == 1} {
                APSMpReturn error "APSMpSRFBringUpToStandby: Problem reseting SRF$rf HVPS. Aborted by user."
            }
            continue
        }
        break
    }

    APSMpStep "SRF${rf}: Turn On Beam" -proc "APSMpSRFTurnOnBeam"
    while {1} {
        if [catch {APSMpSRFTurnOnBeam -rf $rf}] {
            if {[tk_dialog2 .warningDialog "Warning Message" \
                   "Problem turning on SRF$rf klystron beam\nPlease fix then click continue" \
                   warning -1 "Continue" "Abort"] == 1} {
                APSMpReturn error "APSMpSRFBringUpToStandby: Problem turning on SRF$rf klystron beam. Aborted by user."
            }
            continue
        }
        break
    }

    if {($rf == 2)} {
        APSMpStep "SRF${rf}: Raise Beam Voltage To 50kV" -proc "APSMpSRFRaiseBeamVoltage"
        if [catch {APSMpSRFRaiseBeamVoltage -target 50e3 -bePrecise 0 -rf $rf}] {
            APSMpReturn error "APSMpSRFBringUpToStandby: Problem raising SRF$rf beam voltage to 50kV."
        }

        APSMpStep "SRF${rf}: Set Mod Anode To 26kV"
        if {[catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=26000} result]} {
            APSMpReturn error "Problem seting SRF$rf mod anode to 26000 Volts: $result"
        }
        after 1000
        
        APSMpStep "SRF${rf}: Turn On Mod Anode" -proc "APSMpSRFTurnOnModAnode"
        if [catch {APSMpSRFTurnOnModAnode -rf $rf -zeroValue 0}] {
            APSMpReturn error "APSMpSRFBringUpToStandby: Problem turning on SRF$rf mod anode."
        }

        APSMpStep "SRF${rf}: Raise Beam Current To 5A" -proc "APSMpSRFRaiseBeamCurrent"
        if [catch {APSMpSRFRaiseBeamCurrent -rf $rf -target 5}] {
            APSMpReturn error "APSMpSRFBringUpToStandby: Problem raising SRF$rf beam current to 5A."
        }

        APSMpStep "SRF${rf}: Raise Beam Voltage To 70kV" -proc "APSMpSRFRaiseBeamVoltage"
        if [catch {APSMpSRFRaiseBeamVoltage -target 70e3 -bePrecise 0 -rf $rf}] {
            APSMpReturn error "APSMpSRFBringUpToStandby: Problem raising SRF$rf beam voltage to 70kV."
        }
    } else {
        APSMpStep "SRF${rf}: Raise Beam Voltage To 70kV" -proc "APSMpSRFRaiseBeamVoltage"
        if [catch {APSMpSRFRaiseBeamVoltage -target 70e3 -bePrecise 0 -rf $rf}] {
            APSMpReturn error "APSMpSRFBringUpToStandby: Problem raising SRF$rf beam voltage to 70kV."
        }

        APSMpStep "SRF${rf}: Set Mod Anode To 23kV"
        if {[catch {APScavput -list=SRF:P${rf}:modAnodeVoltageAdj=23000} result]} {
            APSMpReturn error "Problem seting SRF$rf mod anode to 23000 Volts: $result"
        }
        after 1000
        
        APSMpStep "SRF${rf}: Turn On Mod Anode" -proc "APSMpSRFTurnOnModAnode"
        if [catch {APSMpSRFTurnOnModAnode -rf $rf -zeroValue 0}] {
            APSMpReturn error "APSMpSRFBringUpToStandby: Problem turning on SRF$rf mod anode."
        }

        APSMpStep "SRF${rf}: Raise Beam Current To 5A" -proc "APSMpSRFRaiseBeamCurrent"
        if [catch {APSMpSRFRaiseBeamCurrent -rf $rf -target 5}] {
            APSMpReturn error "APSMpSRFBringUpToStandby: Problem raising SRF$rf beam current to 5A."
        }
    }

    APSMpReturn ok
}

proc APSMpSRFStandbyFromFullPower {args} {
    set rf 1
    APSStrictParseArguments {rf}


    set turnOffGapVoltage 0

    if {[catch {APScavget -list=S6:WGS:modeSelect -pend=20 -printErrors} waveGuideSwitchMode]} {
        APSMpReturn error "APSMpSRFStandbyFromFullPower: $waveGuideSwitchMode"
    }
    if {($waveGuideSwitchMode != "Mode7") && \
          ($waveGuideSwitchMode != "Mode8") && \
          ($waveGuideSwitchMode != "Mode9") && \
          ($waveGuideSwitchMode != "Mode10") && \
          ($waveGuideSwitchMode != "Mode11") && \
          ($waveGuideSwitchMode != "Mode12")} {
        APSMpReturn error "APSMpSRFStandbyFromFullPower: This procedure cannot be run in this waveguide switch mode. $waveGuideSwitchMode"
    }
    if {($waveGuideSwitchMode == "Mode7")} {
        if {($rf == 2) || ($rf == 4)} {
            set turnOffGapVoltage 1
        }
    } elseif {($waveGuideSwitchMode == "Mode8")} {
        if {($rf == 1) || ($rf == 2)} {
            set turnOffGapVoltage 1
        }
    } elseif {($waveGuideSwitchMode == "Mode9")} {
        if {($rf == 1) || ($rf == 2)} {
            set turnOffGapVoltage 1
        }
    } elseif {($waveGuideSwitchMode == "Mode10")} {
        if {($rf == 3) || ($rf == 4)} {
            set turnOffGapVoltage 1
        }
    } elseif {($waveGuideSwitchMode == "Mode11")} {
        if {($rf == 2) || ($rf == 4)} {
            set turnOffGapVoltage 1
        }
    } elseif {($waveGuideSwitchMode == "Mode12")} {
        if {($rf == 1) || ($rf == 3)} {
            set turnOffGapVoltage 1
        }
    }
    if {$turnOffGapVoltage} {
        APSMpStep "SRF${rf}: Turn off Gap Voltage AGC FB Control"
        if {($rf == 1) || ($rf == 4)} {
            if {[catch {APScavput -list=SRF:AGC:OpsManualCtl1BO=0} result]} {
                APSMpReturn error "APSMpSRFStandbyFromFullPower: Problem with SRF$rf AGC FB Control: $result"
            }
        } else {
            if {[catch {APScavput -list=SRF:AGC:OpsManualCtl2BO=0} result]} {
                APSMpReturn error "APSMpSRFStandbyFromFullPower: Problem with SRF$rf AGC FB Control: $result"
            }
        }
        APSWaitWithUpdate -waitSeconds 5
    }
    APSMpStep "SRF${rf}: Lower Beam Current To 5A" -proc "APSMpSRFLowerBeamCurrent"
    if [catch {APSMpSRFLowerBeamCurrent -target 5 -rf $rf}] {
        APSMpReturn error "APSMpSRFStandbyFromFullPower: Problem lowering beam current to 5A."
    }
    APSMpStep "SRF${rf}: Turn Off Rf Drive"
    if [catch {exec cavput -list=S${rf}:K:rfDriveOff_C=1} result] {
        APSMpReturn error "APSMpSRFStandbyFromFullPower: Problem turning off srf $rf rf drive: $result"
    }

    APSMpStep "SRF${rf}: Lower Beam Voltage To 70kV" -proc "APSMpSRFRaiseBeamVoltage"
    if [catch {APSMpSRFLowerBeamVoltage -target 70e3 -rf $rf}] {
        APSMpReturn error "APSMpSRFStandbyFromFullPower: Problem lowering SRF$rf beam voltage to 70kV."
    }
    APSMpReturn ok
}

proc APSMpUpdateRFControllawTestLimitsInfo {} {
    return "Updates the rf controllaw test limits for RF frequency PV based on current RF frequency. File /home/helios/oagData/sr/rfOrbitControllaw/lattices/default/h.default/tests will be updated."
}

proc APSMpUpdateRFControllawTestLimitsDialog {frame} {
    global  APSMpUpdateRFControllawTestLimits
    pack [frame $frame.f1]
    set  APSMpUpdateRFControllawTestLimits(rfFreqDelta) 100
    APSLabeledEntry .rf -parent $frame.f1 -label "RF frequency delta test limit (Hz) :" -textVariable APSMpUpdateRFControllawTestLimits(rfFreqDelta) \
      -contextHelp "The rf frequency delta test limit (+-) for rf controllaw, the rf frequency test limit will be current RF frequency +/- this delta limit."
    checkbutton $frame.f1.cb -text "Transfer msAve BPM RF Errors to RF Setpoints" -variable APSMpUpdateRFControllawTestLimits(transferBPMrfErrors)
    pack $frame.f1.cb -anchor nw
    return
}

proc APSMpUpdateRFControllawTestLimits {args} {
    set rfFreqDelta ""
    set transferBPMrfErrors 0
    APSStrictParseArguments {rfFreqDelta transferBPMrfErrors}

    APSMpStep init \
      -promptDialog APSMpUpdateRFControllawTestLimitsDialog \
      -vars "rfFreqDelta transferBPMrfErrors" -proc "APSMpUpdateRFControllawTestLimits"

    if {$transferBPMrfErrors} {
        if {[catch {APSMpTransferBpmRFErrorsToRFSetpoint} results]} {
            APSMpReturn error "APSMpUpdateRFControllawTestLimits: $results"
        }
    }

    APSMpStep "Update rf frequency test limit..."
    
    if [catch {exec cavget -list=A014-IETS:BTC:SRSetFreqM -float=%21.1f -pend=15} freqNow] {
        APSMpReturn error "APSMpUpdateRFControllawTestLimits: error getting frequency from source: $freqNow"
    }
    set min [expr $freqNow - $rfFreqDelta]
    set max [expr $freqNow + $rfFreqDelta]
    APSMpStep "The new test limit will be $min to $max "
    set testFile /home/helios/oagData/sr/rfOrbitControllaw/lattices/default/h.default/tests
    if [catch {exec sddsprocess $testFile $testFile.1 \
                 "-redefine=col,MinimumValue,ControlName \"A014-IETS:BTC:SRSetFreqM\" strmatch ? $min : MinimumValue $ " \
                 "-redefine=col,MaximumValue,ControlName \"A014-IETS:BTC:SRSetFreqM\" strmatch ? $max : MaximumValue $ " } result] {
        APSMpReturn "APSMpUpdateRFControllawTestLimits: error updating RF frequency test limits: $result"
    }
    exec mv $testFile.1 $testFile
    
    APSMpStep "RF frequency test limit was updated."
    APSMpReturn ok
}
