

proc APSMpBRFStartUpInfo {} {
    return "For more detailed information please refer to OPSDoc_Boo_PEM007 under required reading.

This machine procedure is used to start the booster rf system and bring it to full power.   The procedure first checks if the rf system is already on or in standby mode (also known as \"diode\" mode) and will bring the system up from both these \"partially on\" modes.  The procedure will reset and load the Arbitrary Function Generator (AFG) ramps and bring up the high voltage and beam current at a rate determined by the klystron body temperature radio button selection.  Normally this button should be set to the default \"Very Careful\".  Selection of \"Very Careful\" will not allow the beam current to be raised until the klystron body temperature is very close to its stabilized value.  The procedure will wait a long time in this case until the temperature is very close to its specified level.  Selecting \"Careful\" allows the beam current to be raised when the body temperature is within a few percent of its stabilized value.  If \"None\" is selected the procedure does not perform this check and the procedure does not wait at all for the temperature to stabilize.  

At a beam current of 9 Amperes, the procedure turns on the rf drive and waits for the tuner feedback to correct the tuners to their operational phase setpoint.  When the loops are locked the feedback error signal will be zero.  The procedure also checks the cavity sum signal ramp waveform and makes sure it has the proper shape as it proceeds to bring the system to full power.   The operator is required to select an SCR file and to select a power increase mode defined by the klystron body temperature radio button. The procedure will leave the klystron ramping at full power at based on the settings in the SCR. Usually this is around 71 kV and 11.8 Amperes.
"
}

proc APSMpBRFStartUp {args} {
    set restoreFile /home/helios/oagData/SCR/snapshots/BRF/BRF-Preferred.gz
    set tempCheck 2
    set doRestore 1
    set finalPower 270
    APSStrictParseArguments {restoreFile tempCheck doRestore finalPower}

    global execMode

    if {$execMode != "Automatic"} {
        if {[catch {APScavget -list=BOO-ACIS:MCR:ExtInhibitLedM,BOO-ACIS:Status:AaTripM,BOO-ACIS:Status:CaTripM -num -printErrors -pend=10} acisState]} {
            APSMpReturn error "APSMpBRFStartUp: $acisState"
        }
        if {[lindex $acisState 0] != 0} {
            if {[APSPEMTKDialog .warningDialog -text "Booster is in an acis inhibit state."] == 1} {
                APSMpReturn error "APSMpBRFStartUp: Booster is in an acis inhibit state."
            }
        }
        if {([lindex $acisState 1] != 0) || ([lindex $acisState 2] != 0)} {
            if {[APSPEMTKDialog .warningDialog -text "Booster is in an acis trip state."] == 1} {
                APSMpReturn error "APSMpBRFStartUp: Booster is in an acis trip state."
            }
        }
    }

    APSMpStep init -promptDialog APSMpBRFStartUpInitDialog \
      -vars {tempCheck doRestore finalPower}

    global APSMpBoosterControlPS
    if {![file exists $APSMpBoosterControlPS(Filename)]} {
        set APSMpBoosterControlPS(Filename) $restoreFile
    }
    set restoreFile $APSMpBoosterControlPS(Filename)
    if {![file exists $restoreFile]} {
        set restoreFile /home/helios/oagData/SCR/snapshots/BRF/BRF-Preferred.gz
    }
    set paramString ""
    foreach param {tempCheck doRestore finalPower restoreFile} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction \
             -procedure APSMpBRFStartUp \
             -action initialize \
             -state ok \
             -parameters $paramString}

    if [catch {exec sddsselect $restoreFile /home/helios/oagData/pem/booster/SCRFilterFileBRF -match=ControlName -pipe=out | sdds2stream -column=ControlName,ValueString -pipe=in} results] {
        APSMpReturn error "APSMpBRFStartUp: Invalid SCR file"
    }
    set cav1phase ""
    set cav2phase ""
    set cav3phase ""
    set cav4phase ""
    set cav1setpoint ""
    set cav2setpoint ""
    set cav3setpoint ""
    set cav4setpoint ""
    set finalCurrent 11.0
    set finalVoltage 69000
    set waveformFile bto4th
    #set waveformFile bt4th
    #set waveformFile operations
    foreach {controlName valueString} $results {
        if {"BRF:INJ:PS1:Ch0" == $controlName} {
            set cav1phase $valueString
        } elseif {"BRF:INJ:PS1:Ch1" == $controlName} {
            set cav2phase $valueString
        } elseif {"BRF:EXT:PS1:Ch0" == $controlName} {
            set cav3phase $valueString
        } elseif {"BRF:EXT:PS1:Ch1" == $controlName} {
            set cav4phase $valueString
        } elseif {"BRF:INJ:C1:TunerSetPtAO" == $controlName} {
            set cav1setpoint $valueString
        } elseif {"BRF:INJ:C2:TunerSetPtAO" == $controlName} {
            set cav2setpoint $valueString
        } elseif {"BRF:EXT:C3:TunerSetPtAO" == $controlName} {
            set cav3setpoint $valueString
        } elseif {"BRF:EXT:C4:TunerSetPtAO" == $controlName} {
            set cav4setpoint $valueString
        } elseif {"BRF:P5:beamCurrent" == $controlName} {
            set finalCurrent $valueString
        } elseif {"BRF:P5:beamVoltage" == $controlName} {
            set finalVoltage $valueString
        } elseif {"BRF:K5:AFG:file" == $controlName} {
            set waveformFile $valueString
        }
    }


    APSMpStep "BRF: Bring Up To Standby" -proc APSMpBRFBringUpToStandby
    if [catch {APSMpBRFBringUpToStandby \
                 -restoreFile $restoreFile \
                 -tempCheck $tempCheck \
                 -doRestore $doRestore -noPrompt 1 \
                 -finalVoltage $finalVoltage \
                 -waveformFile $waveformFile} results] {
        APSMpReturn error "APSMpBRFStartUp: $results"
    }

    APSMpStep "BRF: Bring To Full Power From Standby" -proc APSMpBRFFullPowerFromStandby
    if [catch {APSMpBRFFullPowerFromStandby \
                 -tempCheck $tempCheck \
                 -finalPower $finalPower -noPrompt 1 \
                 -cav1phase $cav1phase -cav2phase $cav2phase \
                 -cav3phase $cav3phase -cav4phase $cav4phase \
                 -cav1setpoint $cav1setpoint \
                 -cav2setpoint $cav2setpoint \
                 -cav3setpoint $cav3setpoint \
                 -cav4setpoint $cav4setpoint \
                 -finalCurrent $finalCurrent} results] {
        APSMpReturn error "APSMpBRFStartUp: $results"
    }
    APSMpReturn ok
}

proc APSMpBRFStartUpInitDialog {frame} {
    global APSMpBRFStartUp

    APSAddSCRDialog .scr \
      -arrayName APSMpBoosterControlPS \
      -daysPast 7 \
      -system BRF \
      -parent $frame

    pack [frame ${frame}.f1]
    APSLabeledEntry .le1 -parent $frame.f1 -label "Final power (kW): " \
      -textVariable APSMpBRFStartUp(finalPower) -width 40 \
      -contextHelp "Enter the final RF power desired in kW."

    pack [frame ${frame}.f2]
    APSRadioButtonFrame .rf0 -parent $frame.f2 -label "Do restore: " \
      -buttonList {Yes No} -valueList {1 0} -packOption "-side left" \
      -variable APSMpBRFStartUp(doRestore) \
      -contextHelp "Select whether to do restore a file at all."

    APSRadioButtonFrame .rf1 -parent $frame.f2 -label "Temperature check: " \
      -buttonList {"None" "Careful" "Very Careful"} -packOption "-side left" \
      -valueList {0 1 2} \
      -variable APSMpBRFStartUp(tempCheck) \
      -contextHelp "Select the type of klystron body temperature checking to do when raising the beam power.  For cold startup, use Very Careful, which waits for warmup and cooloff.  Careful mode just waits for the temperature to crest and begin to fall.  None mode doesn't wait at all, and isn't really recommended."

}

proc APSMpBRFStandbyInfo {} {
    return "For more detailed information please refer to OPSDoc_Boo_PEM007 under required reading.

This machine procedure starts up the booster rf system and brings it into a standby mode.  If the system is at full power it will bring it down into a standby mode.  Standby mode is defined as a high voltage value of 71 kV and 5 Amperes beam current.
"
}

proc APSMpBRFStandby {args} {
    set restoreFile /home/helios/oagData/SCR/snapshots/BRF/BRF-Preferred.gz
    set tempCheck 2
    set doRestore 1
    APSStrictParseArguments {restoreFile tempCheck doRestore}

    global execMode

    if {$execMode != "Automatic"} {
        if {[catch {APScavget -list=BOO-ACIS:MCR:ExtInhibitLedM,BOO-ACIS:Status:AaTripM,BOO-ACIS:Status:CaTripM -num -printErrors -pend=10} acisState]} {
            APSMpReturn error "APSMpBRFStandby: $acisState"
        }
        if {[lindex $acisState 0] != 0} {
            if {[APSPEMTKDialog .warningDialog -text "Booster is in an acis inhibit state."] == 1} {
                APSMpReturn error "APSMpBRFStandby: Booster is in an acis inhibit state."
            }
        }
        if {([lindex $acisState 1] != 0) || ([lindex $acisState 2] != 0)} {
            if {[APSPEMTKDialog .warningDialog -text "Booster is in an acis trip state."] == 1} {
                APSMpReturn error "APSMpBRFStandby: Booster is in an acis trip state."
            }
        }
    }

    if [catch {exec cavget -list=BRF:P5:beamVoltageAdj,BRF:P5:modAnodeVoltageAdj,BRF:P5:beamCurrent,BRF:P5:cathodeSupplyOnOff,BRF:P5:highVoltageReady,BRF:P5:modAnodeOnOff,BRF:P5:modAnodeReady -numerical} results] {
        APSMpReturn error "Problem reading PVs: $results"
    }
    if {([lindex $results 0] > 65000) && ([lindex $results 1] > 16500) && ([lindex $results 2] > 4.5) && ([lindex $results 3] == 1) && ([lindex $results 4] == 1) && ([lindex $results 5] == 1) && ([lindex $results 6] == 1)} {
        APSMpStep init -promptDialog APSMpBRFStandbyInitDialogNoSCR \
          -vars {tempCheck doRestore}
    } else {
        APSMpStep init -promptDialog APSMpBRFStandbyInitDialog \
          -vars {tempCheck doRestore}
        global APSMpBoosterControlPS
        set restoreFile $APSMpBoosterControlPS(Filename)
        if {![file exists $restoreFile]} {
            set restoreFile /home/helios/oagData/SCR/snapshots/BRF/BRF-Preferred.gz
        }
    }

    set paramString ""
    foreach param {tempCheck doRestore restoreFile} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction \
             -procedure APSMpBRFStandby \
             -action initialize \
             -state ok \
             -parameters $paramString}


    if [catch {exec sddsselect $restoreFile /home/helios/oagData/pem/booster/SCRFilterFileBRF -match=ControlName -pipe=out | sdds2stream -column=ControlName,ValueString -pipe=in} results] {
        APSMpReturn error "APSMpBRFStandby: Invalid SCR file"
    }
    set finalVoltage 71000
    set waveformFile bto4th
    #set waveformFile bt4th
    #set waveformFile operations
    foreach {controlName valueString} $results {
        if {"BRF:P5:beamVoltage" == $controlName} {
            set finalVoltage $valueString
        } elseif {"BRF:K5:AFG:file" == $controlName} {
            set waveformFile $valueString
        }
    }

    APSMpStep "BRF: Bring Up To Standby (if off)" -proc APSMpBRFBringUpToStandby
    if [catch {APSMpBRFBringUpToStandby \
                 -restoreFile $restoreFile \
                 -tempCheck $tempCheck \
                 -doRestore $doRestore -noPrompt 1 \
                 -finalVoltage $finalVoltage \
                 -waveformFile $waveformFile} results] {
        APSMpReturn error "APSMpBRFStandby: $results"
    }

    APSMpStep "BRF: Take To Standby From Full Power (if powered)" -proc APSMpBRFStandbyFromFullPower
    if [catch {APSMpBRFStandbyFromFullPower} results] {
        APSMpReturn error "APSMpBRFStandby: $results"
    }
    APSMpReturn ok
}

proc APSMpBRFStandbyInitDialog {frame} {
    global APSMpBRFStandby

    APSAddSCRDialog .scr \
      -arrayName APSMpBoosterControlPS \
      -daysPast 7 \
      -system BRF \
      -parent $frame

    pack [frame ${frame}.f1]
    APSRadioButtonFrame .rf0 -parent $frame.f1 -label "Do restore: " \
      -buttonList {Yes No} -valueList {1 0} -packOption "-side left" \
      -variable APSMpBRFStandby(doRestore) \
      -contextHelp "Select whether to do restore a file at all."

    APSRadioButtonFrame .rf1 -parent $frame.f1 -label "Temperature check: " \
      -buttonList {"None" "Careful" "Very Careful"} -packOption "-side left" \
      -valueList {0 1 2} \
      -variable APSMpBRFStandby(tempCheck) \
      -contextHelp "Select the type of klystron body temperature checking to do when raising the beam power.  For cold startup, use Very Careful, which waits for warmup and cooloff.  Careful mode just waits for the temperature to crest and begin to fall.  None mode doesn't wait at all, and isn't really recommended."

}
proc APSMpBRFStandbyInitDialogNoSCR {frame} {
    APSSetVarAndUpdate status "Click OK bring down to Standby"
    pack [message $frame.msg -aspect 300 -justify left \
            -text "Click OK bring down to Standby"]
    return
}

proc APSMpBRFBringUpToStandbyInfo {} {
    return "This procedure starts up the booster rf system and brings it into a standyby state."
}

proc APSMpBRFBringUpToStandby {args} {
    set restoreFile /home/helios/oagData/SCR/snapshots/BRF/BRF-Preferred.gz
    set tempCheck 2
    set doRestore 1
    set noPrompt 0
    set finalVoltage 71000
    set waveformFile bto4th
    #set waveformFile bt4th
    #set waveformFile operations
    APSStrictParseArguments {restoreFile tempCheck doRestore noPrompt finalVoltage waveformFile}
    if {$noPrompt == 0} {
        APSMpStep init -promptDialog APSMpBRFBringUpToStandbyInitDialog \
          -vars {tempCheck doRestore}

        global APSMpBoosterControlPS
        set restoreFile $APSMpBoosterControlPS(Filename)
        if {![file exists $restoreFile]} {
            set restoreFile /home/helios/oagData/SCR/snapshots/BRF/BRF-Preferred.gz
        }

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

    APSMpStep "BRF: Check For Standby Mode" 
    if [catch {exec cavget -list=BRF:P5:beamVoltageAdj,BRF:P5:modAnodeVoltageAdj,BRF:P5:beamCurrent,BRF:P5:cathodeSupplyOnOff,BRF:P5:highVoltageReady,BRF:P5:modAnodeOnOff,BRF:P5:modAnodeReady -numerical} results] {
        APSMpReturn error "Problem reading PVs: $results"
    }
    if {([lindex $results 0] > 65000) && ([lindex $results 1] > 16500) && ([lindex $results 2] > 4.5) && ([lindex $results 3] == 1) && ([lindex $results 4] == 1) && ([lindex $results 5] == 1) && ([lindex $results 6] == 1)} {
        APSMpReturn ok "Booster rf is already in standby mode or full power mode"
    }
    if {([lindex $results 0] > 65000) && ([lindex $results 1] > 16500) && ([lindex $results 2] > 4.5) && ([lindex $results 3] == 1) && ([lindex $results 5] == 1)} {
        APSMpReturn ok "Booster rf READY indicator is red"
    }
    set beamCurrent [lindex $results 2]

    APSMpStep "BRF: Reset AFG Ramps"
    if [catch {exec caput -t BRF:K5:AFG:softreset 1} result] {
        APSMpReturn error "Problem stopping AFG ramps: $result"
    }

    APSMpStep "BRF: Restore SCR File Data"
    if {[string length $restoreFile] && $doRestore} {
        APSMpStep RestoreControlData
        if ![file exists $restoreFile] {
            APSMpReturn error "File $restoreFile does not exist."
        }
        set tmpFile /tmp/[APSTmpString]
        if {[catch {exec sddsselect $restoreFile -match=ControlName \
                      /home/helios/oagData/pem/booster/BoosterRF-Restorable.req \
                      -pipe=out \
                      | sddsprocess -pipe=in $tmpFile \
                      -match=col,ControlName=,! \
                      -match=col,ValueString=,! } result] || \
              [catch {exec sddscasr -restore $tmpFile} result]} {
            APSMpReturn error $result
        }
    }

    APSMpStep "BRF: Start AFG Ramps"
    if [catch {exec cavput "-list=BRF:K5:AFG:file=${waveformFile}"} result] {
        APSMpReturn error "Problem setting AFG waveform file: $result"
    }
    after 3000
    if [catch {exec cavput "-list=BRF:K5:AFG:ram=3"} result] {
        APSMpReturn error "Problem setting AFG ramps: $result"
    }
    after 5000
    if [catch {exec cavget -list=BRF:K5:AFG:ram -num} result] {
        APSMpReturn error "Problem setting AFG ramps: $result"
    } else {
        if {$result != 3} {
            if [catch {exec cavput "-list=BRF:K5:AFG:ram=3"} result] {
                APSMpReturn error "Problem setting AFG ramps: $result"
            }
            after 5000
        }

    }
    if [catch {exec cavput "-list=BRF:K5:AFG:ram=0"} result] {
        APSMpReturn error "Problem setting AFG ramps: $result"
    }
    after 5000
    if [catch {exec cavget -list=BRF:K5:AFG:ram -num} result] {
        APSMpReturn error "Problem setting AFG ramps: $result"
    } else {
        if {$result != 0} {
            if [catch {exec cavput "-list=BRF:K5:AFG:ram=0"} result] {
                APSMpReturn error "Problem setting AFG ramps: $result"
            }
            after 5000
        }
    }
    if [catch {exec cavput "-list=BRF:K5:AFG:store=1"} result] {
        APSMpReturn error "Problem setting AFG ramps: $result"
    }
    after 5000
    if [catch {exec cavput "-list=BRF:K5:AFG:rambank=3"} result] {
        APSMpReturn error "Problem setting AFG ramps: $result"
    }
    after 5000
    if [catch {exec cavget -list=BRF:K5:AFG:rambank -num} result] {
        APSMpReturn error "Problem setting AFG ramps: $result"
    } else {
        if {$result != 3} {
            if [catch {exec cavput "-list=BRF:K5:AFG:rambank=3"} result] {
                APSMpReturn error "Problem setting AFG ramps: $result"
            }
            after 5000
        }
    }
    if [catch {exec cavput "-list=BRF:K5:AFG:rambank=0"} result] {
        APSMpReturn error "Problem setting AFG ramps: $result"
    }
    after 5000
    if [catch {exec cavget -list=BRF:K5:AFG:rambank -num} result] {
        APSMpReturn error "Problem setting AFG ramps: $result"
    } else {
        if {$result != 0} {
            if [catch {exec cavput "-list=BRF:K5:AFG:rambank=0"} result] {
                APSMpReturn error "Problem setting AFG ramps: $result"
            }
            after 5000
        }
    }
    if [catch {exec caput -t BRF:K5:AFG:start 1} result] {
        APSMpReturn error "Problem starting AFG ramps: $result"
    }
    after 5000
    if {[catch {exec sddswget -PVnames=BRF:K5:WaveformCh0 -pipe=out | sddsbreak -pipe -gapin=Waveform,amount=.1 | sddsconvert -pipe -topage=1 | sddsprocess -pipe -process=Waveform,spread,Spread | sdds2stream -pipe=in -para=Spread} result]} {
        APSMpReturn error "Problem reading the BRF:K5:WaveformCh0 waveform: $result"
    }
    if {$result < .1} {
        if {[tk_dialog2 .warningDialog "Warning Message" \
               "AFG ramp not loaded properly.\nPlease fix then click continue" \
               warning -1 "Continue" "Abort"] == 1} {
            APSMpReturn error "AFG ramp not loaded properly. Aborted by user."
        }
    }

    APSMpStep "BRF: Perform Manual Preparations (operator)" -proc "APSMpBRFManualPrep"
    while {1} {
        if [catch {APSMpBRFManualPrep}] {
            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 "Problem with manual preparation portion of turn on. Aborted by user."
            }
            continue
        }
        break
    }

    if {$beamCurrent > 8} {
        APSMpStep "BRF: Lower Beam Current 8A (if higher)" -proc "APSMpBRFLowerBeamCurrent"
        if [catch {APSMpBRFLowerBeamCurrent -target 8}] {
            APSMpReturn error "Problem lowering beam current to 8A."
        }
    }

    APSMpStep "BRF: Turn Off Rf Drive"
    if [catch {exec cavput -list=B:K:RfDriveOffBO=1} result] {
        APSMpReturn error "Problem turning off rf: $result"
    }

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

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

    APSMpStep "BRF: Raise Beam Voltage To 30kV" -proc "APSMpBRFRaiseBeamVoltage"
    if [catch {APSMpBRFRaiseBeamVoltage -target 30e3 -bePrecise 0}] {
        APSMpReturn error "Problem raising beam voltage to 30kV."
    }

    APSMpStep "BRF: Take Out Of Diode Mode" -proc "APSMpBRFTakeOutOfDiodeMode"
    if [catch {APSMpBRFTakeOutOfDiodeMode}] {
        APSMpReturn error "Problem coming out of diode mode."
    }

    APSMpStep "BRF: Raise Beam Voltage To 50kV" -proc "APSMpBRFRaiseBeamVoltage"
    if [catch {APSMpBRFRaiseBeamVoltage -target 50e3 -bePrecise 0}] {
        APSMpReturn error "Problem raising beam voltage to 50kV."
    }

    APSMpStep "BRF: Turn On Mod Anode" -proc "APSMpBRFTurnOnModAnode"
    if [catch {APSMpBRFTurnOnModAnode}] {
        APSMpReturn error "Problem turning on mod anode."
    }
    
    APSMpStep "BRF: Raise Mod Anode To 18kV" -proc "APSMpBRFRaiseModAnode"
    if [catch {APSMpBRFRaiseModAnode -target 18e3}] {
        APSMpReturn error "Problem raising mod anode to 18kV."
    }
    
    APSMpStep "BRF: Raise Beam Voltage To $finalVoltage volts" -proc "APSMpBRFRaiseBeamVoltage"
    if [catch {APSMpBRFRaiseBeamVoltage -target $finalVoltage -bePrecise 1 -expectedCurrent "4.6 5.6" -currentTolerance 0.2}] {
        APSMpReturn error "Problem raising beam voltage to $finalVoltage volts (expect 4.6A or 5.6A beam current)."
    }

    set startTime [clock seconds]
    APSMpStep "BRF: Raise Beam Current To 7A" -proc "APSMpBRFRaiseBeamCurrent"
    if [catch {APSMpBRFRaiseBeamCurrent -target 7 -tempCheck $tempCheck -forceTempCheck 1}] {
        APSMpReturn error "Problem raising beam current to 7A."
    }

    APSMpStep "BRF: Check RF Ramp Signal" -proc "APSMpBRFCheckRFRampSignal"
    if [catch {APSMpBRFCheckRFRampSignal} results] {
        APSMpReturn error "APSMpBRFBringUpToStandby: $results"
    }

    set endTime [clock seconds]
    if {[expr $endTime - $startTime] < 5} {
        set pauseTime 0
    } else {
        set pauseTime [expr $startTime - $endTime + 180]
    }
    if {$pauseTime > 0} {
        APSMpStep "BRF: Wait For System To Stabilize"
        APSWaitWithUpdate -waitSeconds $pauseTime
    }

    APSMpReturn ok

}

proc APSMpBRFBringUpToStandbyInitDialog {frame} {
    global APSMpBRFBringUpToStandby

    APSAddSCRDialog .scr \
      -arrayName APSMpBoosterControlPS \
      -daysPast 7 \
      -system BRF \
      -parent $frame

    pack [frame ${frame}.f1]
    APSRadioButtonFrame .rf0 -parent $frame.f1 -label "Do restore: " \
      -buttonList {Yes No} -valueList {1 0} -packOption "-side left" \
      -variable APSMpBRFBringUpToStandby(doRestore) \
      -contextHelp "Select whether to do restore a file at all."

    APSRadioButtonFrame .rf1 -parent $frame.f1 -label "Temperature check: " \
      -buttonList {"None" "Careful" "Very Careful"} -packOption "-side left" \
      -valueList {0 1 2} \
      -variable APSMpBRFBringUpToStandby(tempCheck) \
      -contextHelp "Select the type of klystron body temperature checking to do when raising the beam power.  For cold startup, use Very Careful, which waits for warmup and cooloff.  Careful mode just waits for the temperature to crest and begin to fall.  None mode doesn't wait at all, and isn't really recommended."

}

proc APSMpBRFFullPowerFromStandbyInfo {} {
    return "This procedure take the booster rf and brings it from standby to full power."
}

proc APSMpBRFFullPowerFromStandby {args} {
    global status

    set tempCheck 2
    set finalPower 270
    set finalCurrent 11.0
    set noPrompt 0
    set cav1phase ""
    set cav2phase ""
    set cav3phase ""
    set cav4phase ""
    set cav1setpoint ""
    set cav2setpoint ""
    set cav3setpoint ""
    set cav4setpoint ""
    APSStrictParseArguments {tempCheck finalPower noPrompt cav1phase cav2phase cav3phase cav4phase cav1setpoint cav2setpoint cav3setpoint cav4setpoint finalCurrent}
    if {$noPrompt == 0} {
        APSMpStep init -promptDialog APSMpBRFFullPowerFromStandbyInitDialog \
          -vars {tempCheck finalPower}
    }

    if [catch {exec cavget -list=BRF:P5:beamVoltageAdj,BRF:P5:modAnodeVoltageAdj,BRF:P5:beamCurrent,BRF:P5:cathodeSupplyOnOff,BRF:P5:highVoltageReady,BRF:P5:modAnodeOnOff,BRF:P5:modAnodeReady -numerical} results] {
        APSMpReturn error "Problem reading PVs: $results"
    }
    if {([lindex $results 0] < 65000) || ([lindex $results 1] < 16500) || ([lindex $results 2] < 4.5) || ([lindex $results 3] != 1) || ([lindex $results 4] != 1) || ([lindex $results 5] != 1) || ([lindex $results 6] != 1)} {
        APSMpReturn ok "Booster rf is not in a valid standby mode"
    }

    APSMpStep "BRF: Check RF Ramp Signal" -proc "APSMpBRFCheckRFRampSignal"
    if [catch {APSMpBRFCheckRFRampSignal} results] {
        APSMpReturn error "APSMpBRFFullPowerFromStandby: $results"
    }

    APSMpStep "BRF: Raise Beam Current To 7.0A" -proc "APSMpBRFRaiseBeamCurrent"
    if [catch {APSMpBRFRaiseBeamCurrent -target 7.0}] {
        APSMpReturn error "Problem raising beam current to 7.0A."
    }

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

    APSMpStep "BRF: Wait For Tuners To Move"
    APSWaitWithUpdate -waitSeconds 20 -updateInterval 1

    #    APSMpStep GetTunersLocked
    if {([llength $cav1phase]) && ([llength $cav2phase]) && ([llength $cav3phase]) && ([llength $cav4phase])} {
        if {[catch {APScavput -list=BRF:INJ:PS1:Ch0=$cav1phase,BRF:INJ:PS1:Ch1=$cav2phase,BRF:EXT:PS1:Ch0=$cav3phase,BRF:EXT:PS1:Ch1=$cav4phase} result]} {
            APSMpReturn error "Problem restoring cavity phase setpoints: $result"
            puts "cavput -list=BRF:INJ:PS1:Ch0=$cav1phase,BRF:INJ:PS1:Ch1=$cav2phase,BRF:EXT:PS1:Ch0=$cav3phase,BRF:EXT:PS1:Ch1=$cav4phase"
        }
    }

    if {([llength $cav1setpoint]) && ([llength $cav2setpoint]) && ([llength $cav3setpoint]) && ([llength $cav4setpoint])} {
        if {[catch {APScavput -list=BRF:INJ:C1:TunerSetPtAO=$cav1setpoint,BRF:INJ:C2:TunerSetPtAO=$cav2setpoint,BRF:EXT:C3:TunerSetPtAO=$cav3setpoint,BRF:EXT:C4:TunerSetPtAO=$cav4setpoint} result]} {
            APSMpReturn error "Problem restoring cavity phase setpoints: $result"
        }
    }
    if 0 {
        foreach cavity {1 2 3 4} {
            APSMpStep GetTunersLockedCav$cavity -desc "BRF: Get Tuners Locked For Each Cavity" -proc "APSMpBRFGetTunerLocked"
            if [catch {APSMpBRFGetTunerLocked -cavity $cavity} result] {
                set choice \
                  [APSMultipleChoice [APSUniqueName .] -modal 1 \
                     -question "Problem getting tuner to lock on cavity $cavity ($result).  You should try to do this manually, then indicate the desired course of action by pressing the appropriate button below." \
                     -labelList {Proceed Abort} -returnList {Proceed Abort} \
                     -contextHelp "Dialog for choosing what action to take when automatic procudure is unable to get a tuner to lock."]
                switch $choice {
                    Abort {
                        if [catch {exec cavput -list=B:K:RfDriveOffBO=1} result] {
                            APSMpReturn error "Problem turning off rf after tuner lock abort: $result"
                        }
                        APSMpReturn error "Startup aborted due to tuner lock problem.  RF is off."
                    }
                    Proceed {
                        set status "Proceeding with startup in spite of tuning problem with cavity $cavity."
                    }
                }
            }
        }
    }
    #removed temp check here
    APSMpStep "BRF: Check Reflected Power"
    if {[catch {exec cavget -list=BRF:INJ:ED1:Ch1KWatt,BRF:INJ:ED2:Ch1KWatt,BRF:EXT:ED1:Ch1KWatt,BRF:EXT:ED2:Ch1KWatt -list=.HIHI -pend=5} hihiList]} {
        APSMpReturn error "$hihiList"
    }
    if {[catch {exec cavget -list=BRF:INJ:ED1:Ch1KWatt,BRF:INJ:ED2:Ch1KWatt,BRF:EXT:ED1:Ch1KWatt,BRF:EXT:ED2:Ch1KWatt -repeat=num=10,pause=1,average} result]} {
        APSMpReturn error "$result"
    }
    foreach value $result hihi $hihiList pv "BRF:INJ:ED1:Ch1KWatt BRF:INJ:ED2:Ch1KWatt BRF:EXT:ED1:Ch1KWatt BRF:EXT:ED2:Ch1KWatt" {
        if {$value >= $hihi} {
            set answer [tk_dialog2 .warningDialog "Warning Message" "Reflected power PV $pv is greater than $hihi KWatts" warning -1 "Continue" "Abort"]
            if {$answer != 0} {
                APSMpReturn error "Reflected power PV $pv is greater than 10KWatts"
            }
        }
    }

    APSMpStep "BRF: Raise Beam Current To 10A" -proc "APSMpBRFRaiseBeamCurrent"
    if [catch {APSMpBRFRaiseBeamCurrent -target 10 -reflectedPowerCheck 1}] {
        APSMpReturn error "Problem raising beam current to 10A."
    }

    APSMpStep "BRF: Wait For Stabilization"
    APSWaitWithUpdate -waitSeconds 10

    #    APSMpStep "BRF: Check Kalmus Amp Output Signal" -proc "APSMpBRFCheckKalmusAmpOutputSignal"
    #    if [catch {APSMpBRFCheckKalmusAmpOutputSignal -targetArea 45.9 -maxDiff 2.0} results] {
    #	APSMpReturn error "APSMpBRFFullPowerFromStandby: $results"
    #    }

    #133.0
    APSMpStep "BRF: Check Cavity Sum Signal" -proc "APSMpBRFCheckCavitySumSignal"
    if [catch {APSMpBRFCheckCavitySumSignal -targetArea 53.0 -maxDiff 25} results] {
        APSMpReturn error "APSMpBRFFullPowerFromStandby: $results"
    }

    APSMpStep "BRF: Raise Power To Final Level ($finalCurrent Amps)" -proc "APSMpBRFRaisePower"
    if [catch {APSMpBRFRaisePower -finalCurrent $finalCurrent -collectorLimit 900 -modAnodeLimit 34e3} result] {
        APSMpReturn error "Problem raising power level to target of ${finalPower}A cathode current: $result"
    }

    APSMpStep "BRF: Check Reflected Power"
    if {[catch {exec cavget -list=BRF:INJ:ED1:Ch1KWatt,BRF:INJ:ED2:Ch1KWatt,BRF:EXT:ED1:Ch1KWatt,BRF:EXT:ED2:Ch1KWatt -repeat=num=10,pause=1,average} result]} {
        APSMpReturn error "$result"
    }
    foreach value $result hihi $hihiList pv "BRF:INJ:ED1:Ch1KWatt BRF:INJ:ED2:Ch1KWatt BRF:EXT:ED1:Ch1KWatt BRF:EXT:ED2:Ch1KWatt" {
        if {$value >= $hihi} {
            set answer [tk_dialog2 .warningDialog "Warning Message" "Reflected power PV $pv is greater than $hihi KWatts" warning -1 "Continue" "Abort"]
            if {$answer != 0} {
                APSMpReturn error "Reflected power PV $pv is greater than 10KWatts"
            }
        }
    }

    #135.0
    APSMpStep "BRF: Check Cavity Sum Signal" -proc "APSMpBRFCheckCavitySumSignal"
    if [catch {APSMpBRFCheckCavitySumSignal -targetArea 55.0 -maxDiff 25 -fullPower 1} results] {
        APSMpReturn error "APSMpBRFFullPowerFromStandby: $results"
    }

    APSMpStep "BRF: Check Injection Power" -proc "APSMpBRFCheckInjectionPower"
    if [catch {APSMpBRFCheckInjectionPower -target 0.0} result] {
        APSMpReturn error "APSMpBRFFullPowerFromStandby: $results"
    }

    #    APSMpStep MinimizeReflectedPower
    #    foreach cavity {1 2 3 4} {
    #        if [catch {APSMpBRFMinimizeReflectedPower -cavity $cavity}] {
    #            set status "Warning: problem minimizing reflected power for cavity $cavity."
    #        }
    #    }

    APSMpReturn ok
}

proc APSMpBRFFullPowerFromStandbyInitDialog {frame} {
    global APSMpBRFFullPowerFromStandby

    APSLabeledEntry .le1 -parent $frame -label "Final power (kW): " \
      -textVariable APSMpBRFFullPowerFromStandby(finalPower) -width 40 \
      -contextHelp "Enter the final RF power desired in kW."

    APSRadioButtonFrame .rf1 -parent $frame -label "Temperature check: " \
      -buttonList {"None" "Careful" "Very Careful"} \
      -valueList {0 1 2} \
      -variable APSMpBRFFullPowerFromStandby(tempCheck) \
      -contextHelp "Select the type of klystron body temperature checking to do when raising the beam power.  For cold startup, use Very Careful, which waits for warmup and cooloff.  Careful mode just waits for the temperature to crest and begin to fall.  None mode doesn't wait at all, and isn't really recommended."

}

proc APSMpBRFStandbyFromFullPower {} {
    APSMpStep "BRF: Lower Beam Current To 8A" -proc "APSMpBRFLowerBeamCurrent"
    if [catch {APSMpBRFLowerBeamCurrent -target 8}] {
        APSMpReturn error "Problem lowering beam current to 8A."
    }

    APSMpStep "BRF: Turn Off Rf Drive"
    if [catch {exec cavput -list=B:K:RfDriveOffBO=1} result] {
        APSMpReturn error "Problem turning off rf: $result"
    }

    APSMpStep "BRF: Lower Beam Current To 5A" -proc "APSMpBRFLowerBeamCurrent"
    if [catch {APSMpBRFLowerBeamCurrent -target 5}] {
        APSMpReturn error "Problem lowering beam current to 5A."
    }
    APSMpReturn ok
}

proc APSMpBRFStandbyFromFullPowerInfo {} {
    return "This procedure brings the booster RF system into a standby mode from a full power mode."
}

proc APSMpBRFShutdownFromStandby {} {
    if [catch {exec cavget -list=B:K:RfDriveBI,BRF:P5:beamCurrent,BRF:P5:modAnodeOnOff -numerical} results] {
        APSMpReturn error "Problem reading PVs: $results"
    }
    if {[lindex $results 0] != 0} {
        APSMpReturn error "RF Drive is still on"
    }	
    if {[lindex $results 1] > 6} {
        APSMpReturn error "Beam current is not in standby mode"
    }

    APSMpStep "BRF: Lower Mod Anode To 0" -proc "APSMpBRFLowerModAnode"
    if [catch {APSMpBRFLowerModAnode -target 0} result] {
        APSMpReturn error "Problem lowering mod anode voltage: $result"
    }
    
    if {[catch {exec cavput -list=BRF:P5:modAnodeVoltageAdj=0} result]} {
        APSMpReturn error "Problem seting mod anode to 0 Volts: $result"
    }
    after 1000
    if [catch {exec cavget -list=BRF:P5:modAnodeOnOff -numerical} result] {
        APSMpReturn error "Problem reading BRF:P5:modAnodeOnOff: $result"
    }
    if {$result != 0} { 
        APSMpStep TurnOffModAnode
        if {[catch {exec cavput -list=BRF:P5:modAnodeSw.PROC=1} result]} {
            APSMpReturn error "Problem turning on mod anode: $result"
        }
        after 1000
    }

    APSMpStep "BRF: Lower Beam Voltage To 30KV" -proc "APSMpBRFLowerBeamVoltage"
    APSMpBRFLowerBeamVoltage -target 30e3 

    APSMpStep "BRF: Lower Beam Voltage To 0KV" -proc "APSMpBRFLowerBeamVoltage"
    APSMpBRFLowerBeamVoltage -target 0 -tolerance 4500

    APSMpStep "BRF: Turn Off Cathode Supply (if needed)"
    if [catch {exec cavget -list=BRF:P5:cathodeSupplyOnOff -numerical} result] {
        APSMpReturn error "Problem reading BRF:P5:cathodeSupplyOnOff: $result"
    }
    if {$result != 0} {
        if [catch {exec cavput -list=BRF:P5:cathodeSupplySw.PROC=1} result] {
            APSMpReturn error "Problem turning off beam: $result"
        }
    }

    APSMpStep "BRF: Lower Beam Voltage to 0"
    APSMpBRFLowerBeamVoltage -target 0 -tolerance 100
    APSMpReturn ok
}

proc APSMpBRFShutdownFromStandbyInfo {} {
    return "This procedure brings the booster RF system into a HV Shutdown with only the filaments on."
}

proc APSMpBRFShutDown {} {
    APSMpStep init -promptDialog APSMpBRFShutDownDialog
    APSMpStep "BRF: Go To Standby From Full Power (if needed)" -proc APSMpBRFStandbyFromFullPower
    if [catch {APSMpBRFStandbyFromFullPower} results] {
        APSMpReturn error "APSMpBRFShutDown: $results"
    }

    APSMpStep "BRF: Shutdown From Standby" -proc APSMpBRFShutdownFromStandby
    if [catch {APSMpBRFShutdownFromStandby} results] {
        APSMpReturn error "APSMpBRFShutDown: $results"
    }
    APSMpReturn ok
}

proc APSMpBRFShutDownDialog {frame} {
    APSSetVarAndUpdate status "Click OK to shut down the Booster RF"
    pack [message $frame.msg -aspect 300 -justify left \
            -text "Click OK to shut down the Booster RF"]
    return
}

proc APSMpBRFShutDownInfo {} {
    return "For more detailed information please refer to OPSDoc_Boo_PEM007 under required reading.

This machine procedure shuts down the booster rf system if it is on at full power or standby.  It lowers the beam current to 0 Amperes then lowers the the high voltage to 0 kV.  It leaves the cathode supply voltage off.
"
}

proc APSMpBRFTouchUpInfo {} {
    return "Touches up the rf system to the nominal running values of 71kV and 11.8Amps"
}

proc APSMpBRFTouchUp {} {
    APSMpStep "BRF: Verify System Is On" -proc "APSMpBRFSystemIsOn"
    if [catch {APSMpBRFSystemIsOn -level 125} state1] {
        APSMpReturn error "Problem determining whether system is on already."
    }
    if !$state1 {
        APSMpReturn error "Booster RF must be running at 125kW or more to do this."
    }

    APSMpStep "BRF: Adjust Beam Voltage To 71kV" -proc "APSMpBRFAdjustBeamVoltage"
    if [catch {APSMpBRFAdjustBeamVoltage -target 71e3 -maxTries 20} result] {
        APSMpReturn error "Problem adjusting beam voltage to 71kV: $result."
    }
    
    APSMpStep "BRF: Raise Power To Full Level (11.8 Amps)" -proc "APSMpBRFRaisePower"
    if [catch {APSMpBRFRaisePower -finalCurrent 11.8 -collectorLimit 900 -modAnodeLimit 36e3} result] {
        APSMpReturn error "Problem raising power level to target of 270kW forward power: $result"
    }
    APSMpReturn ok
}

proc APSMpBRFCheckRFRampSignal {args} {
    APSMpReturn ok
    set a0(min) 0.0260
    #    set a0(max) 0.0336271212582
    set a0(max) 0.05
    set a4(min) -1.15172020401e-10
    #  set a4(max) -5.78102958504e-11 
    set a4(max) -3.78102958504e-11
    set a0(value) 0
    set a4(value) 0
    set try 1
    while {$try < 4} {
        set fileName /tmp/[APSTmpString]
        if {[catch {exec sddswmonitor $fileName -pvNames=BRF:K5:WaveformCh0 -steps=1 -erase} results]} {
            APSMpReturn error "Problem reading the RF Ramp Signal : $results"
        }
        if {[catch {exec sddsbreak $fileName -pipe=out -gapin=BRF:K5:WaveformCh0,amount=.1 | sddsconvert -pipe -topage=1 | sddspfit -pipe=in $fileName -columns=Index,BRF:K5:WaveformCh0 -terms=5 -verbose} results]} {
            file delete $fileName $fileName~
            APSMpReturn error "Problem reading the RF Ramp Signal : $results"
        }
        file delete $fileName $fileName~
        set lines [split $results \n]
        foreach line $lines {
            set l0 [lindex $line 0]
            set l2 [lindex $line 2]
            if {([string compare $l0 "a\[0\]"] == 0)} {
                set a0(value) $l2
            }
            if {([string compare $l0 "a\[4\]"] == 0)} {
                set a4(value) $l2
            }
        }
        if {($a0(value) < $a0(min))} {
            set description "Offset too low in BRF:K5:WaveformCh0\n"
        }
        if {($a0(value) > $a0(max))} {
            set description "Offset too high in BRF:K5:WaveformCh0\n"
        }
        if {($a4(value) < $a4(min))} {
            set description "Curve in BRF:K5:WaveformCh0 is too shallow\n"
        }
        if {($a4(value) > $a4(max))} {
            set description "Curve in BRF:K5:WaveformCh0 is too deep\n"
        }
        if {($a0(value) < $a0(min)) || ($a0(value) > $a0(max)) ||
            ($a4(value) < $a4(min)) || ($a4(value) > $a4(max))} {
            if {$try == 3} {
                set answer [tk_dialog2 .warningDialog "Warning Message" "Invalid RF Ramp Signal detected\n$description" warning -1 "Continue" "Re-examine" "Abort"]
                if {$answer == 2} {
                    APSMpReturn error "Invalid RF Ramp Signal detected"
                } elseif {$answer == 0} {
                    APSMpReturn ok
                } else {
                    set try 1
                    continue
                }
            }            
        } else {
            APSMpReturn ok
        }
        incr try
    }
    APSMpReturn error "Invalid RF Ramp Signal detected"
}

proc APSMpBRFCheckKalmusAmpOutputSignal {args} {
    set targetArea 0
    set maxDiff .4
    APSStrictParseArguments {targetArea maxDiff}
    set minTargetArea [expr $targetArea - 4.0]
    set maxTargetArea [expr $targetArea + 4.0]
    set try 1
    while {$try < 4} {
        set fileName /tmp/[APSTmpString]
        if [catch {exec sddswmonitor $fileName -pvNames=BRF:K5:WaveformCh2 -steps=1 -erase} results] {
            APSMpReturn error "Problem reading the Kalmus Amp Output Signal : $results"
        }
        if [catch {exec sddsprocess $fileName -pipe=out -process=BRF:K5:WaveformCh2,sum,area | sdds2stream -pipe=in -parameter=area} area] {
            file delete $fileName
            APSMpReturn error "Problem reading the Kalmus Amp Output Signal : $area"
        }
        if {($area < $minTargetArea) || ($area > $maxTargetArea)} {
            if {$try == 3} {
                file delete $fileName
                set answer [tk_dialog2 .warningDialog "Warning Message" "Invalid Kalmus Amp Output Signal detected\nMinimum Area [format %.2f $minTargetArea]\nMaximum Area [format %.2f $maxTargetArea]\nActuall Area [format %.2f $area]" warning -1 "Continue" "Re-examine" "Abort"]
                if {$answer == 2} {
                    APSMpReturn error "Invalid Kalmus Amp Output Signal detected"
                } elseif {$answer == 0} {
                    APSMpReturn ok
                } else {
                    set try 1
                    continue
                }
            }
        } else {
            #This check will not work until I get a new KalmusSignal snapshot because the PV length has changed
            if {0} {
                if [catch {exec sddsconvert $fileName -pipe=out -rename=column,BRF:K5:WaveformCh2=waveform | sddsxref -pipe /home/helios/OAG/oagData/booster/ramps/snapshots/KalmusSignal -take=BRF:K5:WaveformCh2 | sddsprocess -pipe "-define=column,delta,waveform BRF:K5:WaveformCh2 - abs" -process=delta,sum,diff | sdds2stream -pipe=in -parameter=diff} diff] {
                    file delete $fileName
                    APSMpReturn error "Problem reading the Kalmus Amp Output Signal : $diff"
                }
            } else {
                set diff 0
            }
            if {($diff > $maxDiff)} {
                if {$try == 3} {
                    file delete $fileName
                    set answer [tk_dialog2 .warningDialog "Warning Message" "Invalid Kalmus Amp Output Signal detected\nPoint by point comparison results in a difference that is [format %.2f [expr {$diff / $maxDiff * 100}]]% of the allowed difference" warning -1 "Continue" "Re-examine" "Abort"]
                    if {$answer == 2} {
                        APSMpReturn error "Invalid Kalmus Amp Output Signal detected"
                    } elseif {$answer == 0} {
                        APSMpReturn ok
                    } else {
                        set try 1
                        continue
                    }
                }
            } else {
                file delete $fileName
                APSMpReturn ok
            }
        }
        file delete $fileName
        incr try
    }
    file delete $fileName
    APSMpReturn error "Invalid Kalmus Amp Output Signal detected"
}

proc APSMpBRFCheckCavitySumSignal {args} {
    set targetArea 0
    set maxDiff .4
    set fullPower 0
    APSStrictParseArguments {targetArea maxDiff fullPower}
    set minTargetArea [expr $targetArea - 15.0]
    set maxTargetArea [expr $targetArea + 30.0]
    set try 1

    while {$try < 4} {
        set fileName /tmp/[APSTmpString]
        if [catch {exec sddswmonitor $fileName -pvNames=BRF:K5:WaveformCh1 -steps=1 -erase} results] {
            APSMpReturn error "Problem reading the Cavity Sum Signal(1) : $results"
        }
        if [catch {exec sddsprocess $fileName -pipe=out -process=BRF:K5:WaveformCh1,sum,area | sdds2stream -pipe=in -parameter=area} area] {
            file delete $fileName
            APSMpReturn error "Problem reading the Cavity Sum Signal(2) : $area"
        }

        if {($area < $minTargetArea) || ($area > $maxTargetArea)} {
            if {$try == 3} {
                file delete $fileName
                set answer [tk_dialog2 .warningDialog "Warning Message" "Invalid Cavity Sum Signal detected\nMinimum Area [format %.2f $minTargetArea]\nMaximum Area [format %.2f $maxTargetArea]\nActuall Area [format %.2f $area]" warning -1 "Continue" "Re-examine" "Abort"]
                if {$answer == 2} {
                    APSMpReturn error "Invalid Cavity Sum Signal detected"
                } elseif {$answer == 0} {
                    APSMpReturn ok
                } else {
                    set try 1
                    continue
                }
            }
        } else {
            #The point by point check will not work until I get new CavitySumSignal snapshots because the PV now has 300 data points
            if {0} {
                if {$fullPower} {
                    set f /home/helios/OAG/oagData/booster/ramps/snapshots/CavitySumSignalFullPower
                } else {
                    set f /home/helios/OAG/oagData/booster/ramps/snapshots/CavitySumSignal
                }
                if [catch {exec sddsconvert $fileName -pipe=out -rename=column,BRF:K5:WaveformCh1=waveform | sddsxref -pipe $f -take=BRF:K5:WaveformCh1 | sddsprocess -pipe "-define=column,delta,waveform BRF:K5:WaveformCh1 - abs" -process=delta,sum,diff | sdds2stream -pipe=in -parameter=diff} diff] {
                    file delete $fileName
                    APSMpReturn error "Problem reading the Cavity Sum Signal(3) : $diff"
                }
            } else {
                set diff 0
            }

            if {($diff > $maxDiff)} {
                if {$try == 3} {
                    file delete $fileName
                    set answer [tk_dialog2 .warningDialog "Warning Message" "Invalid Cavity Sum Signal detected\nPoint by point comparison results in a difference that is [format %.2f [expr {$diff / $maxDiff * 100}]]% of the allowed difference" warning -1 "Continue" "Re-examine" "Abort"]
                    if {$answer == 2} {
                        APSMpReturn error "Invalid Cavity Sum Signal detected"
                    } elseif {$answer == 0} {
                        APSMpReturn ok
                    } else {
                        set try 1
                        continue
                    }
                }
            } else {
                file delete $fileName
                APSMpReturn ok
            }
        }
        file delete $fileName
        incr try
    }
    file delete $fileName
    APSMpReturn error "Invalid Cavity Sum Signal detected"
}

proc APSMpBRFCheckInjectionPower {args} {
    set target 0
    APSStrictParseArguments {target}
    set minTarget [expr $target - 15.0]
    set maxTarget [expr $target + 15.0]
    if [catch {exec cavput -list=BRF:KLY:TIM:boosterRFDly1.DLY=1} results] {
        APSMpReturn error "Problem setting the Booster RF Ramp delay2 to 1: $results"
    }
    after 3000
    if [catch {exec cavget -list=BRF:K5:ED1:Ch1KWatt} watts] {
        catch {exec cavput -list=BRF:KLY:TIM:boosterRFDly1.DLY=249969}
        APSMpReturn error "Problem reading the forward power: $watts"
    }
    if {($watts < $minTarget) || ($watts > $maxTarget)} {
        catch {exec cavput -list=BRF:KLY:TIM:boosterRFDly1.DLY=249969}
        tk_dialog2 .warningDialog "Warning Message" \
          "Injection power is not between ${minTarget}kW and ${maxTarget}kW\nPlease check by hand and continue" \
          warning -1 "Continue"
    }
    catch {exec cavput -list=BRF:KLY:TIM:boosterRFDly1.DLY=249969}

    APSMpReturn ok
}

proc APSMpBRFSystemIsOn {args} {
    set level 300
    APSStrictParseArguments {level}

    # check if system is on at operating levels
    if [catch {exec cavget -numerical \
                 -list=B:K:RfInterlockBI,BRF:P5:faultInterlock,BRF:K5:ED1:Ch1KWatt} results] {
        APSMpReturn error $results
    }
    if {[lindex $results 0]==1 && [lindex $results 1]==1 && \
          [lindex $results 2]>$level} {
        APSMpReturn ok 1
    }
    APSMpReturn ok 0
}

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

proc APSMpBRFManualPrep {} {
    # check and request turn on off klystron magnets, ion pump, and heater
    # wait about 15 minutes if systems were not on
    # check BRF:P5:heaterWarmingUp for value READY
    global status

    if [catch {APSMpBRFManualPrepCheck} result] {
        APSMpReturn error $result
    }
    if [string compare $result 1] {
        switch [APSMultipleChoice [APSUniqueName .] -modal 1 \
                  -question "Operator actions: Turn on ion pump power supply, magnet 1 and 2 power supplies, and the heater.  Close the disconnect switch.\nWhen you have done this, hit Proceed.  Otherwise, hit Abort." \
                  -labelList {Proceed Abort} -returnList {Proceed Abort} \
                  -name "Do this, human." \
                  -contextHelp "Dialog to prompt manual turn-on of BRF system components."] { 
                      Abort {
                          APSMpReturn error "Manual preparation aborted."
                      }
                      Proceed {
                          set status "Proceeding..."
                      }
                  }
        
        if [catch {APSMpBRFManualPrepCheck} result] {
            APSMpReturn error $result
        }
        if [string compare $result 1] {
            APSMpReturn error "Manual preparation not done properly."
        }
    }

    set status "Waiting for heater warm up...[clock format [clock seconds] -format %H:%M:%S]"
    set index 0
    while 1 {
        if [catch {exec cavget -list=BRF:P5:heaterWarmingUp} result] {
            APSMpReturn error $result
        }
        if [string compare $result "READY"]==0 {
            APSMpReturn ok "Heater warmed up."
        }
        after 5000
        if [expr $index%6]==0 {
            set status "Waiting for heater warm up...[clock format [clock seconds] -format %H:%M:%S]"
        }
        incr index
        update
    }
}

proc APSMpBRFHVPSReset {} {
    # if not BRF:P5:highVoltageReady=READY
    #    press BRF:P5:resetCtl to reset
    # if not BRF:P5:faultInterlock=READY
    #    check items under interlocks/status
    if [catch {exec cavget -list=BRF:P5:highVoltageReady} result] {
        APSMpReturn error "Problem getting HVPS status: $result"
    } 
    if [string compare $result READY]==0 {
        APSMpReturn ok
    }
    if [catch {exec cavput -list=B:K:RfAcisResetBO=1 -num} result] {
        APSMpReturn error "Problem reseting HVPS: $result"
    }
    after 2000
    if [catch {exec cavput -list=BRF:P5:resetCtl=RESET} result] {
        APSMpReturn error "Problem reseting HVPS: $result"
    }
    for {set try 0} {$try<3} {incr try}  {
        after 2000
        if [catch {exec cavget -list=BRF:P5:highVoltageReady} result] {
            APSMpReturn error "Problem getting HVPS status: $result"
        } 
        if [string compare $result READY]==0 {
            APSMpReturn ok
        }
    }
    APSMpReturn error "HVPS did not reset"
}


proc APSMpBRFACISReset {} {
    if [catch {exec cavput -list=B:K:owA3C5S7=close} result] {
        APSMpReturn error "Problem reseting ACIS: $result"
    }
    after 2000
    if [catch {exec cavget -list=B:K:RfAcis_HvpsBI,B:K:RfAcis_RfDriveBI -numerical} result] {
        APSMpReturn error "Problem getting ACIS status: $result"
    } 
    if [string compare [join $result] "1 1"]==0 {
        APSMpReturn ok
    }
    APSMpReturn error "ACIS did not reset"
}

proc APSMpBRFTurnOnBeam {} {
    # if BRF:P5:beamVoltageAdj < 1e3
    #   send 0 to BRF:P5:beamVoltageAdj
    #   press BRF:P5:cathodeSupplySw.PROC
    #   check BRF:P5:cathodeSupplyOnOff=ON,

    APSWaitWithUpdate -waitSeconds 10

    for {set try 0} {$try<3} {incr try} {
        if [catch {exec cavget -list=BRF:P5:cathodeSupplyOnOff -numerical} result] {
            APSMpReturn error "Problem getting status data: $result"
        }
        if [string compare $result 1]!=0 {
            if [catch {exec cavput -list=BRF:P5:beamVoltageAdj=0,BRF:P5:cathodeSupplySw.PROC=1} result] {
                APSMpReturn error "Problem turning on cathode supply: $result"
            }
            after 2000
        } else {
            break
        }
    }
    if $try==3 {
        set choice \
          [APSMultipleChoice [APSUniqueName .] -modal 1 \
             -question "Problem getting 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 cathode supply."
            }
            Proceed {
                if [catch {exec cavget -list=BRF:P5:cathodeSupplyOnOff -numerical} result] {
                    APSMpReturn error "Problem getting status data: $result"
                }
                if [string compare $result 1]!=0 {
                    APSMpReturn error "Cathode supply not on---can't proceed."
                }
            }
        }
    }
    APSMpReturn ok
}

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

    if [catch {exec cavget -list=BRF:P5:cathodeVReference} vReference] {
        APSMpReturn error "Problem getting value of beam voltage reference"
    }
    for {set vSet [expr $vReference+1e3]} {$vSet<$target} {set vSet [expr $vSet+1e3]} {
        if [catch {APSBRFCheckCathodeSupply}] {
            APSMpReturn error "Cathode supply not on."
        }
        if [catch {exec cavput -list=BRF:P5:beamVoltageAdj=$vSet} result] {
            APSMpReturn error "Problem sending value for beam voltage."
        }
        after 500
        update
    }

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

proc APSMpBRFAdjustBeamVoltage {args} {
    set target 0
    set expectedCurrent 0
    set currentTolerance 0
    set maxTries 10
    APSStrictParseArguments {target expectedCurrent currentTolerance maxTries }

    # zero in on exact value by iterating on the difference
    for {set try 0} {$try<$maxTries} {incr try} {
        if [catch {APSBRFCheckCathodeSupply}] {
            APSMpReturn error "Cathode supply not on."
        }
        if [catch {exec cavget -list=BRF:P5:beamVoltage} beamVoltage] {
            APSMpReturn error "Problem getting value of 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 {exec cavput -list=BRF:P5:beamVoltageAdj=$adjustment -delta} result] {
            APSMpReturn error "Problem sending value for beam voltage."
        }
        after $sleepFor
        update
    }
    if [expr abs($adjustment)>40] {
        APSMpReturn error "Didn't get within expected tolerance on beam voltage."
    }

    # check the beam current
    set ec1 [lindex $expectedCurrent 0]
    if {[llength $expectedCurrent] == 2} {
        set ec2 [lindex $expectedCurrent 1]
    } else {
        set ec2 0
    }
    if {$ec1 > 0} {
        after 4000
        if [catch {exec cavget -list=BRF:P5:beamCurrent} current] {
            APSMpReturn error "Problem getting value of beam current"
        }
        set delta1 [expr abs($current - $ec1)]
        if {$ec2 > 0} {
            set delta2 [expr abs($current - $ec2)]
        } else {
            set delta2 0
        }
        if {($delta1 > $currentTolerance) && ($delta2 > $currentTolerance)} {
            APSMpReturn error "Problem setting beam voltage---system current not responding within tolerance of ${currentTolerance}A.  Expected [join $expectedCurrent { or }] Amps, reading ${current}A."
        }
    }

    APSMpReturn ok
}

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

proc APSMpBRFRaiseModAnode {args} {
    set target 0
    APSStrictParseArguments {target}

    # if BRF:P5:anodeVoltage<target
    #   send target to BRF:P5:modAnodeVoltageAdj 
    if [catch {exec cavget -list=BRF:P5:anodeVoltage} voltage] {
        APSMpReturn error "Problem getting mod anode voltage: $voltage"
    }
    if $voltage>=$target {
        APSMpReturn ok "Mod anode voltage already at $voltage---not changed."
    }
    if [catch {APSBRFCheckCathodeSupply}] {
        APSMpReturn error "Cathode supply  not on."
    }
    if [catch {APSBRFCheckModAnodeSupply}] {
        APSMpReturn error "Mod anode supply not on."
    }
    if [catch {exec cavput -list=BRF:P5:modAnodeVoltageAdj=$target} result] {
        APSMpReturn error "Problem changing mod anode voltage: $result"
    }
}

proc APSMpBRFRaiseBeamCurrent {args} {
    set target 0
    set tempCheck 0
    set forceTempCheck 0
    set reflectedPowerCheck 0
    APSStrictParseArguments {target tempCheck forceTempCheck reflectedPowerCheck}
    
    # if BRF:P5:beamCurrent<target
    #   raise mod anode voltage in 1000V steps to get target.
    #   if asked, wait for BRF:K5:CollectorSupT_AI to stabilize at 30.5-30.7degC
    #   don't exceed mod anode limit 
    if {$tempCheck  && \
          [catch {exec cavget -list=BRF:K5:CollectorSupT_AI} origTemp]} {
        APSMpReturn error "Problem getting klystron body temperature"
    }
    set steps 0
    set increment 1000
    while 1 {
        if [catch {APSBRFCheckCathodeSupply}] {
            APSMpReturn error "Cathode supply  not on."
        }
        if [catch {APSBRFCheckModAnodeSupply}] {
            APSMpReturn error "Mod anode supply not on."
        }
        if [catch {exec cavget -list=BRF:P5:beamCurrent} current] {
            APSMpReturn error "Problem getting beam current: $result"
        }
        if $current>$target {
            break
        }
        if !$steps {
            # don't do temp check if we are originally close to target current
            set absDiff [expr abs($target-$current)]
            if $absDiff<0.5 {
                if {$forceTempCheck == 0} {
                    set tempCheck 0
                }
            }
        }
        # 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 {APSBRFCheckCathodeSupply}] {
            APSMpReturn error "Cathode supply not on."
        }
        if [catch {exec cavput -list=BRF:P5:modAnodeVoltageAdj=$increment -delta} result] {
            APSMpReturn error "Problem setting mod anode voltage: $result"
        }
        incr steps
        if {$reflectedPowerCheck} {
            if {[catch {exec cavget -list=BRF:INJ:ED1:Ch1KWatt,BRF:INJ:ED2:Ch1KWatt,BRF:EXT:ED1:Ch1KWatt,BRF:EXT:ED2:Ch1KWatt -list=.HIHI -pend=5} hihiList]} {
                APSMpReturn error "$hihiList"
            }
            if {[catch {APScavget -list=BRF:INJ:ED1:Ch1KWatt,BRF:INJ:ED2:Ch1KWatt,BRF:EXT:ED1:Ch1KWatt,BRF:EXT:ED2:Ch1KWatt -repeat=num=5,pause=1,average} result]} {
                APSMpReturn error "$result"
            }
            foreach value $result hihi $hihiList pv "BRF:INJ:ED1:Ch1KWatt BRF:INJ:ED2:Ch1KWatt BRF:EXT:ED1:Ch1KWatt BRF:EXT:ED2:Ch1KWatt" {
                if {$value >= $hihi} {
                    APSMpReturn error "Reflected power PV $pv is greater than $hihi KWatts"
                }
            }
        } else {
            after 4000
        }
        update
    }
    if {($forceTempCheck != 0) && ($tempCheck != 0)} {
    } else {
        if {!$steps || !$tempCheck} {
            APSMpReturn ok
        }
    }
    set tempHasRisen 0
    set tempIsFalling 0
    set steps 1
    set limit 32
    global status
    set status "Waiting for body temp to rise, then fall below 32C"
    while {$steps<$limit} {
        incr steps 1
        if [catch {exec cavget -list=BRF:K5:CollectorSupT_AI} bodyTemp] {
            APSMpReturn error "Problem getting klystron body temperature"
        }
        if {$tempIsFalling && $bodyTemp<32.0} {
            APSMpReturn ok
        }
        if $tempHasRisen {
            if $lastBodyTemp>$bodyTemp {
                set tempIsFalling 1
                if $tempCheck==1 {
                    # "Careful" mode---return now.
                    # "Very careful" mode waits for temp to fall below 32C.
                    APSMpReturn ok
                }
            }
        } elseif [expr $bodyTemp-$origTemp>0.2] {
            set tempHasRisen 1
        } 
        set lastBodyTemp $bodyTemp
        update
        set status "Body temp now $bodyTemp."
        if [catch {APSBRFCheckCathodeSupply}] {
            APSMpReturn error "Cathode supply  not on."
        }
        if [catch {APSBRFCheckModAnodeSupply}] {
            APSMpReturn error "Mod anode supply not on."
        }
        if $steps>12 {
            # must have missed it after two minutes
            set tempHasRisen 1
        }
        after 10000
    }
    if $bodyTemp<32.0 {
        APSMpReturn ok "Klystron body temperature ok, but behavior unexpected."
    }
    if $tempIsFalling {
        set choice \
          [APSMultipleChoice [APSUniqueName .] -modal 1 \
             -question "Temperature didn't fall as rapidly as expected. You may proceed in spite of this (after waiting if you wish) or abort." \
             -labelList {Proceed Abort} -returnList {Proceed Abort} \
             -contextHelp "Dialog for choosing what action to take when klystron body temperature hasn't fallen off as expected."]
        global status
        if {$choice == "Abort"} {
            set status "Shutting down rf system..."
            if [catch {APSMpBRFShutDown}] {
                APSMpReturn error "Problem shutting down RF system!"
            }
            APSMpReturn error "Startup aborted due to klystron temperature problem.  System shut down."
        }
        APSMpReturn ok "Proceeding with startup in spite of tuning problem with cavity."
    }
    set status "Klystron body temperature behavior is unacceptable---shutting down."
    if [catch {APSMpBRFShutDown}] {
        APSMpReturn error "Problem shutting down RF system!"
    }
    APSMpReturn error "Klystron body temperature too high."
}

proc APSMpBRFLowerBeamCurrent {args} {
    set target 0
    APSStrictParseArguments {target}
    
    # if BRF:P5: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 {APSBRFCheckCathodeSupply}] {
            APSMpReturn error "Cathode supply  not on."
        }
        if [catch {APSBRFCheckModAnodeSupply}] {
            APSMpReturn error "Mod anode supply not on."
        }
        if [catch {exec cavget -list=BRF:P5:beamCurrent} current] {
            APSMpReturn error "Problem getting 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 {APSBRFCheckCathodeSupply}] {
            APSMpReturn error "Cathode supply not on."
        }
        if [catch {exec cavput -list=BRF:P5:modAnodeVoltageAdj=$increment -delta} result] {
            APSMpReturn error "Problem setting mod anode voltage: $result"
        }
        incr steps
        after 4000
        update
    }
    APSMpReturn ok
}

proc APSMpBRFTurnOnRF {} {
    lappend testPVList B:K:PmRfFltSum B:K:RfDriveBI B:K:RfInterlockBI 
    lappend desiredTestValList 0 1 1
    lappend resetPVList B:K:PmMasterRst B:K:RfDriveOnBO B:K:RfInterlockBO 
    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 {APSBRFCheckCathodeSupply}] {
        APSMpReturn error "Cathode supply  not on."
    }
    if [catch {APSBRFCheckModAnodeSupply}] {
        APSMpReturn error "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 {exec cavget -list=$testPV -numerical} result] {
                APSMpReturn error "Problem reading PV $testPV: $result"
            }
            if [string compare $result [lindex $desiredTestValList $index]]==0 \
              break
            set status "Reseting [lindex $descripList $index] (now $result)"
            bell
            if [catch {exec cavput -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 "Failed to reset [lindex $descripList $index]"
        }
        incr index
    }
    after 2000
    if [catch {APSBRFCheckForwardPower -require 50} result] {
        APSMpReturn error "$result"
    }

    APSMpReturn ok
}

proc APSMpBRFGetTunerLocked {args} {
    set cavity 0
    APSStrictParseArguments {cavity}
    lappend revPwrPV BRF:INJ:ED1:Ch1KWatt BRF:INJ:ED2:Ch1KWatt \
      BRF:EXT:ED1:Ch1KWatt BRF:EXT:ED2:Ch1KWatt
    lappend tunerPhasePV BRF:INJ:FB1:pidSpCh0AO BRF:INJ:FB1:pidSpCh1AO \
      BRF:EXT:FB1:pidSpCh0AO BRF:EXT:FB1:pidSpCh1AO

    if {[catch {exec cavget -list=BRF:INJ:ED1:Ch1KWatt,BRF:INJ:ED2:Ch1KWatt,BRF:EXT:ED1:Ch1KWatt,BRF:EXT:ED2:Ch1KWatt -list=.HIHI -pend=5} hihiList]} {
        APSMpReturn error "$hihiList"
    }
    if [catch {APSBRFCheckCathodeSupply}] {
        APSMpReturn error "Cathode supply  not on."
    }
    if [catch {APSBRFCheckModAnodeSupply}] {
        APSMpReturn error "Mod anode supply not on."
    }
    if {$cavity<=0 || $cavity>4} {
        APSMpReturn error "Cavity number not valid: $cavity"
    }
    set index [expr $cavity-1]
    # if more than 5kW refl power,
    #     slide set point to 10V, then to 0V
    # if more than 5kW refl power,
    #     slide set point to -10V, then to 0V
    global status
    for {set try 0} {$try<3} {incr try} {
        foreach setPoint {10 -10} {
            if [catch {APSBRFCheckForwardPower -require 125} result] {
                APSMpReturn error "$result"
            }
            set rpPV [lindex $revPwrPV $index]
            set hihi [lindex $hihiList $index]
            if [catch {exec cavget -list=$rpPV -repeat=num=10,pause=1,average} result] {
                APSMpReturn error "Problem reading reflected power for cavity $cavity: $result"
            }
            if $result < $hihi {
                APSMpReturn ok
            }
            set status "Trying to tune cavity $cavity using setpoint of $setPoint"
            if [catch {exec cavput -list=[lindex $tunerPhasePV $index]=$setPoint} result] {
                APSMpReturn error "Problem moving tuner phase setpoint for cavity $cavity: $result"
            }
            update
            after 500
            if [catch {exec cavput -list=[lindex $tunerPhasePV $index]=0 } result] {
                APSMpReturn error "Problem moving tuner phase setpoint for cavity $cavity: $result"
            }
            set status "Waiting for tuner to move."
            APSWaitWithUpdate -waitSeconds 20 -updateInterval 1
            if [catch {exec cavget -list=$rpPV -repeat=num=10,pause=1,average} result] {
                APSMpReturn error "Problem reading reflected power for cavity $cavity: $result"
            }
            if $result < $hihi {
                APSMpReturn ok
            }
        }
        update
        after 500
    }
    APSMpReturn error "Unable to get cavity $cavity tuner to lock."
}

proc APSMpBRFRaisePower {args} {
    set forwardTarget 0
    set finalCurrent 0
    set collectorLimit 0
    set modAnodeLimit 0
    APSStrictParseArguments {forwardTarget finalCurrent collectorLimit modAnodeLimit}

    # while forwardTarget > BRF:K5:ED1:Ch1KWatt &&
    #       collectorLimit > BRF:K5:PCollectorCC &&
    #       modAnodeLimit > BRF:P5:anodeVoltage-1e3
    #   raise mod anode by 1000
    set increment 500
    while 1 {
        if {[catch {APSBRFCheckCathodeSupply}]} {
            APSMpReturn error "Cathode supply  not on."
        }
        if {[catch {APSBRFCheckModAnodeSupply}]} {
            APSMpReturn error "Mod anode supply not on."
        }
        #        if {[catch {exec cavget -list=BRF:K5:ED1:Ch1KWatt,BRF:K5:PCollectorCC,BRF:P5:anodeVoltage} results]} {
        #            APSMpReturn error "Problem reading PVs: $result"
        #        }
        if {[catch {exec cavget -list=BRF:K5:ED1:Ch1KWatt,BRF:K5:CollectorCalAI,BRF:P5:anodeVoltage,BRF:P5:beamCurrent} 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 {exec cavput -list=BRF:P5:modAnodeVoltageAdj=30e3} 
            APSMpReturn error "Less that 180kW forward power---can't proceed"
        }
        if {$fwdPwr > 449} {
            catch {exec cavput -list=BRF:P5:modAnodeVoltageAdj=30e3} 
            APSMpReturn error "More than 449kW 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 {exec cavput -list=BRF:P5:modAnodeVoltageAdj=30e3}
            APSMpReturn error "Collector power was $colPwr, which is in excess of limit of $collectorLimit"
        }
        if {$anode > $modAnodeLimit} {
            APSMpReturn error "Can't raise forward power---would exceed mod anode limit of $modAnodeLimit"
        }
        if {[catch {exec cavput -list=BRF:P5:modAnodeVoltageAdj=$increment -delta} result]} {
            APSMpReturn error "Problem setting mod anode voltage: $result"
        }
        APSWaitWithUpdate -waitSeconds 5 -updateInterval 1
    }
}

proc APSMpBRFMinimizeReflectedPower {args} {
    set cavity 0
    APSStrictParseArguments {cavity}
    #    slide cavity phase to minimize reflected power
}

proc APSMpBRFLowerModAnode {args} {
    set target 0
    APSStrictParseArguments {target}
    set step 0
    while 1 {
        if [catch {exec cavget -printErrors -list=BRF:P5:anodeVoltage} voltage] {
            APSMpReturn error "Problem reading mod anode voltage: $voltage"
        }
        set diff [expr $voltage-$target]
        if {$diff > 0} {
            if {$diff > 2300} {
                if [catch {exec cavput -list=BRF:P5:modAnodeVoltageAdj=-1000 -delta} result] {
                    APSMpReturn error "Problem changing mod anode voltage: $result"
                }
                incr step
                if {$step == 150} {
                    if {[tk_dialog2 .warningDialog "Warning Message" \
                           "Having trouble lowering BRF Mod Anode to $target \nPlease fix then click continue" \
                           warning -1 "Continue" "Abort"] == 1} {
                        APSMpReturn error "Having trouble lowering BRF Mod Anode to $target. Aborted by user."
                    } else {
                        APSMpReturn ok
                    }
                }
            } else {
                if {$diff > 1500} {
                    if [catch {exec cavput -list=BRF:P5:modAnodeVoltageAdj=-1000 -delta} result] {
                        APSMpReturn error "Problem changing mod anode voltage: $result"
                    }
                }
                APSMpReturn ok
            }
        } else {
            APSMpReturn ok
        }
        after 1000
        update
    }
}

proc APSMpBRFLowerBeamVoltage {args} {
    set target 0
    set tolerance 3000
    APSStrictParseArguments {target tolerance}
    # check for BRF:P5:beamVoltageV<target
    # if not:
    #   send target value to BRF:P5:beamVoltageAdj
    if [catch {exec cavget -list=BRF:P5:beamVoltage} beamVoltage] {
        APSMpReturn error "Problem getting value of beam voltage"
    }
    if {$beamVoltage<$target} {
        APSMpReturn ok "Beam voltage at $beamVoltage---not changed."
    }
    if [catch {exec cavput -list=BRF:P5:beamVoltageAdj=$target} result] {
        APSMpReturn error "Problem sending value for beam voltage."
    }

    global status
    set status "Waiting for voltage to fall...[exec date +%H:%M:%S]"
    set index 0
    while 1 {
        if [catch {exec cavget -list=BRF:P5:beamVoltage} result] {
            APSMpReturn error $result
        }
        set diff [expr ($result-$target)]
        if $diff<$tolerance {
            APSMpReturn ok 
        }
        APSWaitWithUpdate -waitSeconds 5 -updateInterval 1
        update
        set status "Waiting for voltage to fall...[exec date +%H:%M:%S]"
        incr index
    }
    APSMpReturn ok
}

proc APSBRFCheckCathodeSupply {} {
    if {[catch {exec cavget -list=BRF:P5:cathodeSupplyOnOff -numerical} result] || \
          [string compare $result 0]==0} {
        catch {exec cavput -list=BRF:P5:=0 -list=beamVoltageAdj,modAnodeVoltageAdj}
        return -code error 
    }
    return -code ok
}

proc APSBRFCheckModAnodeSupply {} {
    if {[catch {exec cavget -list=BRF:P5:modAnodeOnOff -numerical} result] || \
          [string compare $result 0]==0} {
        catch {exec cavput -list=BRF:P5:modAnodeVoltageAdj=0}
        return -code error 
    }
    return -code ok
}

proc APSBRFCheckForwardPower {args} {
    set require 0
    set safeLevel 30000.0
    APSStrictParseArguments {require safeLevel}
    
    set try 1
    while {1} {
        if [catch {exec cavget -list=BRF:K5:ED1:Ch1KWatt} fwdPwr] {
            APSMpReturn error "Problem reading forward power: $fwdPwr"
        }
        if {$fwdPwr<$require} {
            if {$try > 3} {
                set answer [tk_dialog2 .warningDialog "Warning Message" \
                              "Forward power of $fwdPwr less than required $require" \
                              warning -1 "Continue" "Check Again" "Abort"]
                if {$answer == 2} {
                    if {$safeLevel>0} {
                        catch {exec cavput -list=BRF:P5:modAnodeVoltageAdj=$safeLevel}
                    }
                    APSMpReturn error "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 APSMpBRFTakeOutOfDiodeMode {} {
    # check if system is on at operating levels
    if [catch {exec cavget -numerical \
                 -list=B:K:RfInterlockBI,BRF:P5:faultInterlock,BRF:K5:ED1:Ch1KWatt,BRF:P5:anodeVoltage} 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 {APSMpBRFLowerModAnode -target 10e3} result] {
        APSMpReturn error "Problem lowering mod anode voltage: $result"
    }
    APSMpReturn ok 
}

proc APSMpBRFGoToDiodeMode {} {
    if [catch {APSMpBRFLowerModAnode -target 13.35e3} result] {
        APSMpReturn error "Problem lowering mod anode voltage: $result"
    }
    if [catch {exec cavput -list=B:K:RfDriveOffBO=1} result] {
        APSMpReturn error "Problem turning off rf: $result"
    }
    if [catch {APSMpBRFLowerBeamVoltage -target 30e3} result] {
        APSMpReturn error "Problem lowering beam voltage: $result"
    }
    APSMpReturn ok
}
