
set PLETSnapshotDir /home/helios/oagData/SCR/snapshots/LPL
set controlFilesDir /home/helios/oagData/controlFiles

proc APSPARLETDefaultEnergy {} {
    return 425
}

proc APSMpPARStartUpInfo {} {
    return "This procedure starts up the PAR, including turning on DC and pulsed power supplies and rf systems.  It also conditions magnets, opens valves, removes flags, and restores a configuration."
}

proc APSMpPARStartUp {args} {
    global status PLETSnapshotDir
    
    set energy [APSPARLETDefaultEnergy]
    set restoreFile ""
    set conditioningTime 14
    set DCPS 1
    set PulsedPS 1
    set rfSystems 1
    set restoreDCPS 1
    set useSystemReference 0

    APSParseArguments {rfSystems restoreDCPS useSystemReference}

    global execMode

    if {$execMode != "Automatic"} {
        if {[catch {exec cavget -list=ACIS:LAOL_INH_GUN,ACIS:LBL_GUN_INH,ACIS:LA_BP_MODE,ACIS:LB_BP_MD -num -pend=20} acisState]} {
            APSMpReturn error "APSMpPARStartUp: $acisState"
        }
        if {([lindex $acisState 0] == 1) || ([lindex $acisState 1] == 1)} {
            if {[APSPEMTKDialog .warningDialog \
                   -text "Linac/PAR is in an acis inhibit state."] == 1} {
                APSMpReturn error "APSMpPARStartUp: Linac/PAR is in an acis inhibit state."
            }
        } elseif {([lindex $acisState 2] == 0) || ([lindex $acisState 3] == 0)} {
            if {[APSPEMTKDialog .warningDialog \
                   -text "Linac/PAR is in an acis trip state."] == 1} {
                APSMpReturn error "APSMpPARStartUp: Linac/PAR is in an acis trip state."
            }
        }
    }

    if {$rfSystems == 0} {
        set rf1 0
        set rf12 0
    } else {
        set rf1 1
        set rf12 1
    }

    if {[catch {APScavget -list=PAR:Fnd:SystemSelect} rf1amp]} {
        APSMpReturn error "APSMpPARStartUp: Error reading the selected rf1 amplifier"
    }
    if {{"SYSTEM #1"} == $rf1amp} {
        set rf1amp 1
    } else {
        set rf1amp 2
    }
    if {[catch {APScavget -list=PAR:Har:SystemSelect} rf12amp]} {
        APSMpReturn error "APSMpPARStartUp: Error reading the selected rf12 amplifier"
    }
    if {{"SYSTEM #1"} == $rf12amp} {
        set rf12amp 1
    } else {
        set rf12amp 2
    }

    APSParseArguments {energy conditioningTime DCPS PulsedPS restoreFile rf1 rf12 rf1amp rf12amp}

    set ShortFilename $restoreFile
    set Description ""



    APSMpStep init -promptDialog APSMpPARStartUpInitDialog \
      -vars {energy conditioningTime restoreFile DCPS PulsedPS rf1 rf12 rfSystems ShortFilename Description rf1amp rf12amp}

    set paramString ""
    foreach param {energy conditioningTime DCPS PulsedPS rfSystems rf1 rf12 rf1amp rf12amp restoreFile} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure APSMpPARStartUp -action initialize \
             -state ok -parameters $paramString}

    set restoreFile $ShortFilename
    if {[string length $restoreFile] && ![file exists $PLETSnapshotDir/$restoreFile]} {
        APSMpReturn error "File [file tail $restoreFile] not found."
    }
    if {![llength $restoreFile]} {
        APSMpReturn error "No SCR file selected."
    }
    if {[catch {exec sdds2stream $PLETSnapshotDir/$restoreFile -parameter=SnapshotDescription -page=1 -noquotes} results]} {
        APSMpReturn error "APSMpPARStartUp: Invalid SCR file"
    }    
    if {[string first "Limited save:" $results] != -1} {
        if {[catch {exec sddssort $PLETSnapshotDir/$restoreFile -pipe=out -column=Beamline -unique | sdds2stream -pipe=in -col=Beamline} results]} {
            APSMpReturn error "APSMpPARStartUp: Problem reading beamlines categories from the SCR file"
        } else {
            if {([lsearch -exact $results PAR] == -1)} {
                APSMpReturn error "APSMpPARStartUp: LIMITED SAVE SCR file does not include the PAR beamline category"
            }
        }
    }

    if {$DCPS} {
        APSMpStep "PAR: Turn On DCPS (optional)" -proc "APSMpPARTurnOnDCPS"
        if {[catch {APSMpPARTurnOnDCPS} result]} {
            APSMpReturn error "Error turning on PAR DCPS: $result"
        }
    }

    if {$PulsedPS} {
        APSMpStep "PAR: Turn On Pulsed PS (optional)" -proc "APSMpPARTurnOnPulsedPS"
        set ppsID [APSMpParallel \
                     -procedure "APSMpPARTurnOnPulsedPS -restoreFile $restoreFile" \
                     -mode Automatic]
    }

    if {$rf1 || $rf12} {
        APSMpStep "PAR: Turn On Rf1 and RF12 (optional)" -proc "APSMpPARTurnOnRf"
        set rfID [APSMpParallel -procedure "APSMpPARTurnOnRf -restoreFile $restoreFile -rf1 $rf1 -rf12 $rf12 -rf1amp $rf1amp -rf12amp $rf12amp -useSystemReference $useSystemReference" -mode Automatic]
    }
    
    if {$DCPS} {
        APSMpStep "PAR: Condition DCPS (optional)" -proc "APSMpPARCondition"
        if {[catch {APSMpPARCondition -energy $energy -restoreFile $restoreFile \
                      -conditioningTime $conditioningTime} result]} {
            APSMpReturn error "Error initiating PAR conditioning: $result"
        }
    }

    if {[string length $restoreFile]} {
        APSMpStep "PAR: Restore SCR Data"
        set tmpFile /tmp/[APSTmpString]
        if {$restoreDCPS} {
            # Don't restore RF or Pulsed PS.  Done above if requested.
            if {[catch {exec sddsprocess $PLETSnapshotDir/$restoreFile $tmpFile \
                          -match=column,IsReadOnly=+y,! \
                          -match=column,Beamline=PAR -match=column,Category=*RF*,! \
                          -match=column,Category=PulsedPS,! -match=column,ValueString=,! \
                          -match=column,ControlName=PRF:H:FBM2:pidSpCh1AO,ControlName=PRF:H:FBM1:pidSpCh0AO,|,! \
                          -match=column,ControlName=PRF:F:FBM2:pidSpCh1AO,ControlName=PRF:F:FBM1:pidSpCh0AO,|,!} result]} {
                APSMpReturn error "Error preparing data from $restoreFile for PAR: $result"
            }
        } else {
            # Don't restore RF or Pulsed PS.  Done above if requested.
            if {[catch {exec sddsprocess $PLETSnapshotDir/$restoreFile $tmpFile \
                          -match=column,IsReadOnly=+y,! \
                          -match=column,Beamline=PAR -match=column,Category=*RF*,! \
                          -match=column,Category=SteeringPS,Category=MainPS,|,Category=PulsedPS,|,! -match=column,ValueString=,! \
                          -match=column,ControlName=PRF:H:FBM2:pidSpCh1AO,ControlName=PRF:H:FBM1:pidSpCh0AO,|,! \
                          -match=column,ControlName=PRF:F:FBM2:pidSpCh1AO,ControlName=PRF:F:FBM1:pidSpCh0AO,|,!} result]} {
                APSMpReturn error "Error preparing data from $restoreFile for PAR: $result"
            }
        }
        if {[catch {exec sddscasr -restore $tmpFile} result]} {
#	    tk_dialog .warningDialog "Warning Message" "Problem restoring SCR file: APSMpPARStartUp: $result" warning -1 Continue
            catch {APSSendEMail -address soliday \
                     -subject "Problem restoring SCR file."  \
                     -message "Problem restore SCR file\nAPSMpPARStartUp\n${PLETSnapshotDir}/${restoreFile}\n$result"} 	    
            #            APSMpReturn error "Error writing back values from $restoreFile for PAR: $result"
        }
        file delete -force $tmpFile
    }

    APSMpAbort all -onError 1
    if {$PulsedPS} {
        APSMpStep "PAR: Complete Pulsed PS Startup"
        if {[catch {APSMpJoin $ppsID} ppsStatus]} {
            APSMpReturn error "APSMpPARStartUp: $ppsStatus"
        }
    }
    if {$rf1 || $rf12} {
        APSMpStep "PAR: Complete RF1 and RF12 Startup"
        if {[catch {APSMpJoin $rfID} rfStatus]} {
            APSMpReturn error "APSMpPARStartUp: $rfStatus"
        }
    }

    APSMpStep "PAR: Clear Beam Aperture (of flags/valves)" -proc "APSMpPARClearAperture"
    if {[catch {APSMpPARClearAperture} result]} {
        APSMpReturn error "Unable to clear beam aperture: $result."
    }

    APSMpReturn ok
}

proc APSMpPARStartUpInitDialog {frame} {
    global APSMpPARStartUp
    pack [frame ${frame}.top] -fill x
    pack [frame ${frame}.top.f1] -side left -anchor n
    pack [frame ${frame}.top.f2] -side left -anchor n
    pack [frame ${frame}.top.f3] -side left -anchor n
    
     APSCheckButtonFrame .cb1 -parent $frame.top.f1 -label "Systems: " \
      -buttonList {"Fundamental RF" "Harmonic RF" DCPS "Pulsed PS"} \
      -allNone 1 \
      -variableList {APSMpPARStartUp(rf1) APSMpPARStartUp(rf12) APSMpPARStartUp(DCPS) APSMpPARStartUp(PulsedPS)} \
      -orientation vertical -allNone 1 -contextHelp \
      "Use to select or deselect systems to be included in startup."

    APSRadioButtonFrame .rb1 -parent $frame.top.f2 -label "RF1 Amp: " \
      -variable APSMpPARStartUp(rf1amp) \
      -contextHelp "Choose which RF1 amp to use." \
      -buttonList "{Tube Amp System \#1} {Tube Amp System \#2}" -valueList "1 2"
    
    APSRadioButtonFrame .rb12 -parent $frame.top.f2 -label "RF12 Amp: " \
      -variable APSMpPARStartUp(rf12amp) \
      -contextHelp "Choose which RF12 amp to use." \
      -buttonList "{Tube Amp System \#1} {Tube Amp System \#2}" -valueList "1 2"
    
    APSLabeledEntry .le1 -parent $frame.top.f3 -label "Energy (MeV): " \
      -textVariable APSMpPARStartUp(energy) \
      -contextHelp "Enter the energy of the beam you will be using in MeV."

    APSLabeledEntry .le2 -parent $frame.top.f3 -label "Minutes for conditioning: " \
      -textVariable APSMpPARStartUp(conditioningTime) \
      -contextHelp "Enter the number of minutes you want to allow for conditioning.  The actual conditioning time may be longer, since each magnet must be put through at least one ramp cycle."



    if 0 {
        APSCheckButtonFrame .cb1 -parent $frame -label "Systems: " \
          -buttonList {DCPS "Pulsed PS"} \
          -allNone 1 \
          -variableList {APSMpPARStartUp(DCPS) APSMpPARStartUp(PulsedPS)} \
          -orientation vertical -allNone 1 -contextHelp \
          "Use to select or deselect systems to be included in startup."
    }
    APSAddSCRDialog .scr -parent $frame -system LPL -arrayName APSMpPARStartUp \
      -defaultFile $APSMpPARStartUp(ShortFilename)
}

proc APSMpPARTurnOnPulsedPSInfo {} {
    return "This procedure turns on the pulsed PAR magnets, and restores pulsed magnet configuration and all PAR/LET timing configuration as a bonus."
}

proc APSMpPARTurnOnPulsedPS {args} {
    global status PLETSnapshotDir

    set restoreFile ""
    APSStrictParseArguments {restoreFile}

    catch {APSLogScriptAction -procedure APSMpPARTurnOnPulsedPS -action start \
             -state ok -parameters "restoreFile=$restoreFile"}

    set ShortFilename $restoreFile
    APSMpStep init -promptDialog APSMpPARTurnOnPulsedPSInitDialog -vars {ShortFilename}
    set restoreFile $ShortFilename

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

    if {[string length $restoreFile] && ![file exists ${PLETSnapshotDir}/$restoreFile]} {
        APSMpReturn error "Restore file $restoreFile not found"
    }
    if {![llength $restoreFile]} {
        APSMpReturn error "No SCR file selected."
    }
    if {[catch {exec sdds2stream $PLETSnapshotDir/$restoreFile -parameter=SnapshotDescription -page=1 -noquotes} results]} {
        APSMpReturn error "APSMpPARTurnOnPulsedPS: Invalid SCR file"
    }    
    if {[string first "Limited save:" $results] != -1} {
        if {[catch {exec sddssort $PLETSnapshotDir/$restoreFile -pipe=out -column=Beamline -unique | sdds2stream -pipe=in -col=Beamline} results]} {
            APSMpReturn error "APSMpPARTurnOnPulsedPS: Problem reading beamlines categories from the SCR file"
        } else {
            if {([lsearch -exact $results PAR] == -1)} {
                APSMpReturn error "APSMpPARTurnOnPulsedPS: LIMITED SAVE SCR file does not include the PAR beamline category"
            }
        }
    }

    APSMpStep "PAR: Warm Up Pulsed PS (Parallel)"
    set wusID [APSMpParallel -procedure "APSMpTurnOnSeptum" -mode Automatic]
    APSMpStep "PAR: Started septum turn on"
    set wukID [APSMpParallel -procedure "APSMpWarmupKickers -kickerList {P1IK P2IK P4EK}" \
                 -mode Automatic]
    APSMpStep "PAR: Started kicker warm up"
    if {[catch {APSMpJoin $wukID} wukResult]} {
        APSMpReturn error "APSMpPARTurnOnPulsedPS: Problem with APSMpWarmupKickers: $wukResult"
    }
    if {[catch {APSMpJoin $wusID} wusResult]} {
        APSMpReturn error "APSMpPARTurnOnPulsedPS: Problem with APSMpTurnOnSeptum: $wukResult"
    }
    
    APSMpStep "PAR: Turn On Kicker HV"
    if {[catch {APScavput -list=P1IK,P2IK,P4EK -list=:OnBO=ON } result]} {
        APSMpReturn error "Error sending on signals: $result"
    }

    if {[string length $restoreFile]} {
        APSMpStep "PAR: Configure Pulsed Magnets"
        if {![file exists ${PLETSnapshotDir}/$restoreFile]} {
            APSMpReturn error "Restore file $restoreFile not found"
        }
        set tmpfile /tmp/[APSTmpString]
        if {[catch \
               {exec sddsprocess ${PLETSnapshotDir}/$restoreFile $tmpfile \
                  -match=column,IsReadOnly=+y,! \
                  -match=col,Beamline=PAR \
                  -match=col,Category=PulsedPS,Category=Timing,|} result]} {
            APSMpReturn error "Error preparing data from $restoreFile for PAR PPS: $result"
        }
        if {[catch {exec sddscasr -restore $tmpfile} result]} {
            APSMpReturn error "Error writing back values for PAR PPS from $restoreFile: $result"
        }
        file delete -force $tmpfile
    }
    APSMpReturn ok
}

proc APSMpPARTurnOnPulsedPSInitDialog {frame} {
    global APSMpPARTurnOnPulsedPS

    APSAddSCRDialog .scr -parent $frame -system LPL -arrayName APSMpPARTurnOnPulsedPS \
      -defaultFile $APSMpPARTurnOnPulsedPS(ShortFilename)
}

proc APSMpPARTurnOnDCPS {args} {
    set retries 5
    APSMpStep init -promptDialog "APSMpPromptInitDialog"
    catch {APSLogScriptAction -procedure APSMpPARTurnOnDCPS -action start \
             -state ok -parameters "retries=$retries"}

    #Check MPEOB
    APSMpStep "Check that the MPEOBs are pulled out"
    while {1} {
        if {[catch {APSPLETMPEOBsAreOut} mpeob]} {
            if {[APSPEMTKDialog .warningDialog -text "APSMpPARTurnOnDCPS: Error checking MPEOB: $mpeob"] == 1} {
                APSMpReturn error "APSMpPARTurnOnDCPS: Error checking MPEOB: $mpeob"
            }
            continue
        }
        if {!$mpeob} {
            if {[APSPEMTKDialog .warningDialog -text "APSMpPARTurnOnDCPS: Both MPEOBs must be pulled out to start DCPS."] == 1} {
                APSMpReturn error "APSMpPARTurnOnDCPS: Both MPEOBs must be pulled out to start DCPS."
            }
            continue
        }
        break
    }

    APSStrictParseArguments {retries}
    while {$retries} {
        set statusList \
          [APScavget -list=P: -list=BM,SF,SD,S1,Q1,Q2,Q3BP,Q4 -list=:StatusCALC -label]
        set statusList \
          [concat $statusList \
             [APScavget \
                -list=P2H1,P2H3,P3H2,P3H1,P4H1,P4H2,P1H3,P1H1,P1H2  \
                -list=:StatusCALC -label]]
        set statusList \
          [concat $statusList \
             [APScavget -list=P2V2,P1V2,P1V1,P1V3,P2V1,P2V3,P3V1,P3V2,P4V1,P4V2 \
                -list=:StatusCALC -label]]
        set statusList \
          [concat $statusList \
             [APScavget -list=P -list=1,2,3,4 -list=BMT -list=1,2 \
                -list=:StatusCALC -label]]
        set toDoList0 [APSSearchAssociateListForValue -list $statusList -value 2]
        set toDoList [concat $toDoList0 [APSSearchAssociateListForValue -list $statusList -value 3]]
        regsub -all {:StatusCALC} $toDoList {} toDoList
        if {[llength $toDoList]} {
            if {[catch {APScavput -list=[join $toDoList ,] -list=:ResetSEQ=1 } result]} {
                APSMpReturn error "Error sending on commands to PAR magnets ([join $toDoList ,]): $result"
            }
            after 24000
        } else {
            break
        }
        incr retries -1
    }
    set status2List0 [APSSearchAssociateListForValue -list $statusList -value 2]
    set status2List [concat $status2List0 [APSSearchAssociateListForValue -list $statusList -value 3]]
    if {[llength $status2List]} {
        APSMpReturn error "Unable to turn on PAR DC power supplies: $status2List."
    }
    set status1List [APSSearchAssociateListForValue -list $statusList -value 1]
    if {[llength $status1List]} {
        regsub -all :StatusCALC [join $status1List ,] "" probList
        APSAlertBox [APSUniqueName .] \
          -errorMessage "Warning: some PAR DC power supplies may need manual turn on.  Look at these supplies: $probList"
    }
    APSMpReturn ok 
}

proc APSMpPARSextStandardizeInfo {} {
    return "This procedure standardizes the PAR sextupoles."
}

proc APSMpPARSextStandardize {args} {
    global status controlFilesDir PLETSnapshotDir

    set energy [APSPARLETDefaultEnergy]
    set restoreFile ""
    set block 1
    set excludeS1 1
    APSStrictParseArguments {energy restoreFile block excludeS1}

    set ShortFilename $restoreFile
    APSMpStep init -promptDialog APSMpPARSextStandardizeInitDialog \
      -vars {energy ShortFilename excludeS1}

    set paramString ""
    foreach param {energy ShortFilename} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure APSMpPARSextStandardize \
             -action initialize -state ok -parameters $paramString}

    set restoreFile $ShortFilename
    if {[string length $restoreFile]} {
        if {![file exists $PLETSnapshotDir/$restoreFile]} {
            APSMpReturn error "File [file tail $restoreFile] not found."
        }
        if {[catch {exec sdds2stream $PLETSnapshotDir/$restoreFile -parameter=SnapshotDescription -page=1 -noquotes} results]} {
            APSMpReturn error "APSMpPARSextStandardize: Invalid SCR file"
        }    
        if {[string first "Limited save:" $results] != -1} {
            if {[catch {exec sddssort $PLETSnapshotDir/$restoreFile -pipe=out -column=Beamline -unique | sdds2stream -pipe=in -col=Beamline} results]} {
                APSMpReturn error "APSMpPARSextStandardize: Problem reading beamlines categories from the SCR file"
            } else {
                if {([lsearch -exact $results PAR] == -1)} {
                    APSMpReturn error "APSMpPARSextStandardize: LIMITED SAVE SCR file does not include the PAR beamline category"
                }
            }
        }
    }

    set file ${controlFilesDir}/PAR/P${energy}MeV.Sstd
    if {![file exists $file]} {
        APSMpReturn error "PAR standardization file for $energy MeV not found"
    }
    set tmpRoot /tmp/[APSTmpString]
    if {[string length $restoreFile]} {
        if {$excludeS1} {
            set matchOption -match=column,ControlName=P:SD:*,ControlName=P:SF:*,|
        } else {
            set matchOption -match=column,ControlName=P:S?:*
        }
        if {[catch {exec sddsprocess $PLETSnapshotDir/$restoreFile $tmpRoot.1 \
                      $matchOption \
                      -edit=column,ElementName,ControlName,%/:CurrentAO// \
                      -scan=column,Finish,ValueString,%le
            exec sddsconvert $file -pipe=out -delete=column,Finish \
                      | sddsxref -pipe=in $tmpRoot.1 $tmpRoot.2 -take=Finish -nowarning \
                      -match=ControlName=ElementName
            exec standardize $tmpRoot.2} result]} {
            eval file delete -force $tmpRoot.1 $tmpRoot.2
            APSMpReturn error "Error initiating standardization of PAR sextupoles: $result"
        }
        eval file delete -force $tmpRoot.1 $tmpRoot.2
    } else {
        if {$excludeS1} {
            set matchOption -match=column,ControlName=P:SD*,ControlName=P:SF*,|
        } else {
            set matchOption -match=column,ControlName=P:S?*
        }
        set theFile $file
        if {$excludeS1} {
            exec sddsprocess $file $tmpRoot.1 $matchOption
            set $theFile $tmpRoot.1
        }
        if {[catch {exec standardize $theFile} result]} {
            file delete $tmpRoot.1
            APSMpReturn error "Error initiating standardization of PAR sextupoles: $result"
        }
        file delete $tmpRoot.1
    }

    if {$excludeS1} {
        set condList [APScavget -list=P:S -list=D,F -list=:StandardizeSUB.PROC -label]
    } else {
        set condList [APScavget -list=P:S -list=D,F,1 -list=:StandardizeSUB.PROC -label]
    }
    set problemCond [APSSearchAssociateListForValue -list $condList -value 0]
    if {[llength $problemCond]} {
        APSMpReturn error "[llength $problemCond] PAR sextupoles not conditioning as expected."
    }
    set status "Standardization initiated for sextupoles for $energy MeV."

    if {$block} {
        set loopCount 0
        while {1} {
            if {[expr $loopCount%15==0]} {
                APSMpStep "PAR: Wait For Conditioning for sextupoles"
            }
            update
            incr loopCount
            if {[catch {APScavget -list=P:S:CondCALC -pend=120} result] || \
                  [string compare $result ?]==0} {
                APSMpReturn error "APSMpPARSextStandardize: Problem reading P:S:CondCALC---timed out."
            }
            if {!$result} break
            after 2000
        }
    }

    APSMpReturn ok
}

proc APSMpPARSextStandardizeInitDialog {frame} {
    global APSMpPARSextStandardize
    
    APSLabeledEntry .le1 -parent $frame -label "Energy (MeV): " \
      -textVariable APSMpPARSextStandardize(energy) \
      -contextHelp "Enter the energy of the beam you will be using in MeV."
    APSRadioButtonFrame .rb1 -parent $frame -label "Exclude S1: " \
      -variable APSMpPARSextStandardize(excludeS1) \
      -contextHelp "Choose whether to exclude S1 from standardization.  Recommended." \
      -buttonList "Yes No" -valueList "1 0"
    APSAddSCRDialog .scr -parent $frame -system LPL -arrayName APSMpPARSextStandardize \
      -defaultFile $APSMpPARSextStandardize(ShortFilename)
}

proc APSMpPARConditionInfo {} {
    return "This is a procedure which conditions PAR magnets.  It waits for conditioning to complete."
}


proc APSMpPARConditionInitDialog {frame} {
    global APSMpPARCondition
    
    pack [frame $frame.frame]
    APSLabeledEntry .le1 -parent $frame.frame -label "Energy (MeV): " \
      -textVariable APSMpPARCondition(energy) \
      -contextHelp "Enter the energy of the beam you will be using in MeV."

    APSLabeledEntry .le2 -parent $frame.frame -label "Minutes for conditioning: " \
      -textVariable APSMpPARCondition(conditioningTime) \
      -contextHelp "Enter the number of minutes you want to allow for conditioning.  The actual conditioning time may be longer, since each magnet must be put through at least one ramp cycle."

    APSCheckButtonFrame .cb1 -parent $frame -label "Power Supplies:" \
      -buttonList {Dipole Quads Sextupoles Correctors} \
      -variableList {APSMpPARCondition(dipole) APSMpPARCondition(quads) APSMpPARCondition(sextupoles) APSMpPARCondition(correctors)}

    APSAddSCRDialog .scr -parent $frame -system LPL -arrayName APSMpPARCondition \
      -defaultFile $APSMpPARCondition(ShortFilename)
   
}

proc APSMpPARCondition {args} {
    global status PLETSnapshotDir controlFilesDir

    set energy [APSPARLETDefaultEnergy]
    set conditioningTime 14
    set restoreFile ""
    set dipoleAndQuads 1
    set sextupoles 1
    set correctors 1
    APSStrictParseArguments {energy conditioningTime restoreFile dipoleAndQuads sextupoles correctors}
    if {$dipoleAndQuads} {
        set dipole 1
        set quads 1
    } else {
        set dipole 0
        set quads 0
    }
   
    global execMode

    if {$execMode != "Automatic"} {
        if {[catch {exec cavget -list=ACIS:LAOL_INH_GUN,ACIS:LBL_GUN_INH,ACIS:LA_BP_MODE,ACIS:LB_BP_MD -num -pend=20} acisState]} {
            APSMpReturn error "APSMpPARCondition: $acisState"
        }
        if {([lindex $acisState 0] == 1) || ([lindex $acisState 1] == 1)} {
            if {[APSPEMTKDialog .warningDialog \
                   -text "Linac/PAR is in an acis inhibit state."] == 1} {
                APSMpReturn error "APSMpPARCondition: Linac/PAR is in an acis inhibit state."
            }
        } elseif {([lindex $acisState 2] == 0) || ([lindex $acisState 3] == 0)} {
            if {[APSPEMTKDialog .warningDialog \
                   -text "Linac/PAR is in an acis trip state."] == 1} {
                APSMpReturn error "APSMpPARCondition: Linac/PAR is in an acis trip state."
            }
        }
    }

    set ShortFilename $restoreFile
    set Description ""
    APSMpStep init -promptDialog APSMpPARConditionInitDialog \
      -vars {energy conditioningTime ShortFilename dipole quads sextupoles correctors}

    set paramString ""
    foreach param {energy conditioningTime ShortFilename} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure APSMpPARCondition -action initialize \
             -state ok -parameters $paramString}

    set restoreFile $ShortFilename
    if {[string length $restoreFile] && ![file exists $PLETSnapshotDir/$restoreFile]} {
        APSMpReturn error "File [file tail $restoreFile] not found."
    }
    if {[string length $restoreFile]} {
        if {[catch {exec sdds2stream $PLETSnapshotDir/$restoreFile -parameter=SnapshotDescription -page=1 -noquotes} results]} {
            APSMpReturn error "APSMpPARCondition: Invalid SCR file"
        }    
        if {[string first "Limited save:" $results] != -1} {
            if {[catch {exec sddssort $PLETSnapshotDir/$restoreFile -pipe=out -column=Beamline -unique | sdds2stream -pipe=in -col=Beamline} results]} {
                APSMpReturn error "APSMpPARCondition: Problem reading beamlines categories from the SCR file"
            } else {
                if {([lsearch -exact $results PAR] == -1)} {
                    APSMpReturn error "APSMpPARCondition: LIMITED SAVE SCR file does not include the PAR beamline category"
                }
            }
        }
    }

    if {$dipole || $quads} {
        APSMpStep "PAR: Initiate Dipole/Quad Standardization" -proc "APSMpPARStandardizeBQ"
        if {[catch {APSMpPARStandardizeBQ -energy $energy -conditioningTime $conditioningTime \
                      -restoreFile $restoreFile -block 0 \
                      -BM $dipole -Q1 $quads -Q2 $quads -Q3BP $quads -Q4 $quads} result]} {
            APSMpReturn error "Error initiating standardization of PAR BM and Q: $result"
        }
    }

    if {$sextupoles} {
        APSMpStep "PAR: Initiate Sextupole Standardization" -proc "APSMpPARSextStandardize"
        if {[catch {APSMpPARSextStandardize -energy $energy \
                      -restoreFile $restoreFile -block 0 -excludeS1 1}  result]} {
            APSMpReturn error "Error initiating standardization of PAR sextupoles: $result"
        }
    }

    if {$correctors} {
        APSMpStep "PAR: Initiate Corrector Degaussing (wait for completion)" -proc "APSMpPARDegauss"
        if {[catch {APSMpPARDegauss -block 1 -degaussTime $conditioningTime -excludeSDSF 1} result]} {
            APSMpReturn error "Error degaussing PAR correctors: $result"
        }
    }

    if {$dipole} {
        APSMpStep "PAR: Wait For Dipole Conditioning"
        set result ""
        set loopCount 0
        while {1} {
            if {[catch {APScavget -list=P:Q:BM:CondCALC -pend=120} result]} {
                APSMpReturn error "Error getting PAR conditioning status: $result"
            }
            if {[string compare $result ?]==0} {
                APSMpReturn error "Error getting PAR conditioning status: IOC communications error."
            }
            if {!$result} break
            if {[expr $loopCount%15==0]} {
                APSMpStep "PAR: Waiting For Conditioning"
            }
            incr loopCount
            update
            after 2000
        }   
    }
    if {$quads} {
        APSMpStep "PAR: Wait For Quad Conditioning"
        set result ""
        set loopCount 0
        while {1} {
            if {[catch {APScavget -list=P: -list=Q1,Q2,Q3BP,Q4 -list=:StandardizeSUB.PROC -pend=120} results]} {
                APSMpReturn error "Error getting PAR conditioning status: $results"
            }
            set pass 1
            foreach result $results {
                if {[string compare $result ?]==0} {
                    APSMpReturn error "Error getting PAR conditioning status: IOC communications error."
                }
                if {$result != 0} {
                    set pass 0
                }
            }
            if {$pass} break
            if {[expr $loopCount%15==0]} {
                APSMpStep "PAR: Waiting For Conditioning"
            }
            incr loopCount
            update
            after 2000
        }   
    }
    if {$sextupoles} {
        APSMpStep "PAR: Wait For Sextupole Conditioning"
        set result ""
        set loopCount 0
        while {1} {
            if {[catch {APScavget -list=P:S:CondCALC -pend=120} result]} {
                APSMpReturn error "Error getting PAR conditioning status: $result"
            }
            if {[string compare $result ?]==0} {
                APSMpReturn error "Error getting PAR conditioning status: IOC communications error."
            }
            if {!$result} break
            if {[expr $loopCount%15==0]} {
                APSMpStep "PAR: Waiting For Conditioning"
            }
            incr loopCount
            update
            after 2000
        }   
    }

    if {[string length $restoreFile]} {
        if {$dipole} {
            APSMpStep "PAR: Restore Dipole SCR Values"
            set tmpFile /tmp/[APSTmpString]
            APSAddToTmpFileList -ID APSMpPARCondition -fileList $tmpFile
            if {[catch {exec sddsprocess $PLETSnapshotDir/$restoreFile $tmpFile \
                          -match=column,IsReadOnly=+y,! -match=col,Beamline=PAR \
                          -match=column,Category=MainPS,Category=SteeringPS,| \
                          -match=column,ControlName=P:BM:*,ControlName=P?BMT*,|
                exec sddscasr -restore $tmpFile} result]} {
                file delete -force $tmpFile
                APSMpReturn error "Error restoring DC power supply setpoints: $result"
            }
            file delete -force $tmpFile
        }
        if {$quads} {
            APSMpStep "PAR: Restore Quad SCR Values"
            set tmpFile /tmp/[APSTmpString]
            APSAddToTmpFileList -ID APSMpPARCondition -fileList $tmpFile
            if {[catch {exec sddsprocess $PLETSnapshotDir/$restoreFile $tmpFile \
                          -match=column,IsReadOnly=+y,! -match=col,Beamline=PAR \
                          -match=column,Category=MainPS,Category=SteeringPS,| \
                          -match=column,ControlName=P:Q*
                exec sddscasr -restore $tmpFile} result]} {
                file delete -force $tmpFile
                APSMpReturn error "Error restoring DC power supply setpoints: $result"
            }
            file delete -force $tmpFile
        }
        if {$sextupoles} {
            APSMpStep "PAR: Restore Sextupole SCR Values"
            set tmpFile /tmp/[APSTmpString]
            APSAddToTmpFileList -ID APSMpPARCondition -fileList $tmpFile
            if {[catch {exec sddsprocess $PLETSnapshotDir/$restoreFile $tmpFile \
                          -match=column,IsReadOnly=+y,! -match=col,Beamline=PAR \
                          -match=column,Category=MainPS,Category=SteeringPS,| \
                          -match=column,ControlName=P:S*
                exec sddscasr -restore $tmpFile} result]} {
                file delete -force $tmpFile
                APSMpReturn error "Error restoring DC power supply setpoints: $result"
            }
            file delete -force $tmpFile
        }
        if {$correctors} {
            APSMpStep "PAR: Restore Correctors SCR Values"
            set tmpFile /tmp/[APSTmpString]
            APSAddToTmpFileList -ID APSMpPARCondition -fileList $tmpFile
            if {[catch {exec sddsprocess $PLETSnapshotDir/$restoreFile $tmpFile \
                          -match=column,IsReadOnly=+y,! -match=col,Beamline=PAR \
                          -match=column,Category=MainPS,Category=SteeringPS,| \
                          -match=column,ControlName=P?H*,ControlName=P?V*,|
                exec sddscasr -restore $tmpFile} result]} {
                file delete -force $tmpFile
                APSMpReturn error "Error restoring DC power supply setpoints: $result"
            }
            file delete -force $tmpFile
        }
    }

    APSMpReturn ok
}

proc APSMpPARStandardizeBQInfo {} {
    return "Standardizes PAR Q1, Q2, Q3, Q4, and BM magnets.  Allows choosing a subset of the magnets for conditioning, as well as specifying the standardization time and the energy.  Does not turn the power supplies on, but assumes they are already on."
}

proc APSMpPARStandardizeBQInitDialog {frame} {
    global APSMpPARStandardizeBQ

    APSLabeledEntry .le1 -parent $frame -label "Energy (MeV): " \
      -textVariable APSMpPARStandardizeBQ(energy) \
      -contextHelp "Enter the energy of the beam you will be using in MeV."

    APSLabeledEntry .le2 -parent $frame -label "Minutes for conditioning: " \
      -textVariable APSMpPARStandardizeBQ(conditioningTime) \
      -contextHelp "Enter the number of minutes you want to allow for conditioning.  The actual conditioning time may be longer, since each magnet must be put through at least one ramp cycle."

    APSCheckButtonFrame .cb1 -parent $frame -label "Magnets: " -orientation horizontal \
      -buttonList {Q1 Q2 Q3 Q4 BM} \
      -variableList {APSMpPARStandardizeBQ(Q1) APSMpPARStandardizeBQ(Q2) \
                       APSMpPARStandardizeBQ(Q3BP) \
                       APSMpPARStandardizeBQ(Q4) APSMpPARStandardizeBQ(BM)} \
      -contextHelp "Choose which magnets you want to standardize.  If none are chosen, no action will be taken."
    
    APSAddSCRDialog .scr -parent $frame -system LPL -arrayName APSMpPARStandardizeBQ \
      -defaultFile $APSMpPARStandardizeBQ(ShortFilename)
}

proc APSMpPARStandardizeBQ {args} {
    global controlFilesDir PLETSnapshotDir

    set conditioningTime 14
    set energy [APSPARLETDefaultEnergy]
    set Q1 1
    set Q2 1
    set Q3BP 1
    set Q4 1
    set BM 1
    set restoreFile ""
    set block 1
    APSStrictParseArguments {energy conditioningTime Q1 Q2 Q3BP Q4 BM restoreFile block}

    set ShortFilename $restoreFile
    set Description ""
    APSMpStep init -promptDialog APSMpPARStandardizeBQInitDialog \
      -vars {Q1 Q2 Q4 Q3BP BM energy conditioningTime ShortFilename}

    set paramString ""
    foreach param {Q1 Q2 Q4 Q3BP BM energy conditioningTime ShortFilename} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure APSMpPARStandardizeBQ \
             -action initialize -state ok -parameters $paramString}

    set restoreFile $ShortFilename
    if {[string length $restoreFile] && ![file exists $PLETSnapshotDir/$restoreFile]} {
        APSMpReturn error "File [file tail $restoreFile] not found."
    }
    if {[string length $restoreFile]} {
        if {[catch {exec sdds2stream $PLETSnapshotDir/$restoreFile -parameter=SnapshotDescription -page=1 -noquotes} results]} {
            APSMpReturn error "APSMpPARStandardizeBQ: Invalid SCR file"
        }    
        if {[string first "Limited save:" $results] != -1} {
            if {[catch {exec sddssort $PLETSnapshotDir/$restoreFile -pipe=out -column=Beamline -unique | sdds2stream -pipe=in -col=Beamline} results]} {
                APSMpReturn error "APSMpPARStandardizeBQ: Problem reading beamlines categories from the SCR file"
            } else {
                if {([lsearch -exact $results PAR] == -1)} {
                    APSMpReturn error "APSMpPARStandardizeBQ: LIMITED SAVE SCR file does not include the PAR beamline category"
                }
            }
        }
    }


    set nameList ""
    foreach var {Q1 Q2 Q3BP Q4 BM} {
        if {[subst \$$var]} {
            lappend nameList P:$var
        }
    }
    if {[llength $nameList]==0} {
        APSMpReturn ok
    }
    set nameString [join $nameList ,]

    set file ${controlFilesDir}/PAR/P${energy}MeV.std
    if {![file exists $file]} {
        APSMpReturn error "Standardization file for $energy MeV not found"
    }
    
    set tmpfile /tmp/[APSTmpString]
    if {[catch \
           {exec sddsprocess $file $tmpfile \
              "-redefine=col,NumCycles,$conditioningTime Minutes Seconds 60 / + 2 * / int 4 > ? 4 : $conditioningTime Minutes Seconds 60 / + 2 * / int \$ ,type=long" \
          } result]} {
        APSMpReturn error "Error during processing prior to standardizing PAR BM and Q: $result"
    }
    if {[string length $restoreFile]} {
        set tmpfile2 /tmp/[APSTmpString]
        set tmpfile3 /tmp/[APSTmpString]
        if {[catch {exec sddsprocess $PLETSnapshotDir/$restoreFile $tmpfile2 \
                      -match=column,ControlName=P:BM:CurrentAO,ControlName=P:Q*:CurrentAO,| \
                      -edit=column,ElementName,ControlName,%/:CurrentAO// \
                      -scan=column,Finish,ValueString,%le
            exec sddsconvert $tmpfile -pipe=out -delete=column,Finish \
                      | sddsxref -pipe=in $tmpfile2 $tmpfile3 -match=ControlName=ElementName -take=Finish 
            file rename -force $tmpfile3 $tmpfile
            file delete -force $tmpfile2} result]} {
            eval file delete -force $tmpfile $tmpfile2 $tmpfile3
            APSMpReturn error "Error setting up standardization of PAR BM and Q: $result"
        }
    }
    if {[catch {exec standardize -configure $tmpfile } result]} {
        APSMpReturn error "Error configuring standardization of PAR BM and Q: $result"
    }
    if {[catch {APScavput -list=$nameString -list=:StandardizeSUB.PROC=1} result]} {
        APSMpReturn error "Error initiating standardization of $nameString: $result"
    }

    set condList [APScavget -list=$nameString -list=:StandardizeSUB.PROC -label]
    set problemCond [APSSearchAssociateListForValue -list $condList -value 0]
    if {[llength $problemCond]} {
        APSMpReturn error "[llength $problemCond] PAR magnets not conditioning as expected."
    }

    if {$block} {
        APSMpStep "PAR: Wait For Conditioning for Dipole/Quad"
        while {1} {
            if {[catch {APScavget -list=P:Q:BM:CondCALC -pend=120} result] || \
                  [string compare $result ?]==0} {
                APSMpReturn error "APSMpPARStandardizeBQ: Problem reading P:Q:BM:CondCALC---timed out."
            }
            if {!$result} break
            update
            after 2000
        }
    }

    APSMpReturn ok
}

proc APSMpWarmupKickersInfo {} {
    return "Warms up kickers (if needed)."
}

proc APSMpWarmupKickers {args} {
    global status

    set kickerList ""
    APSStrictParseArguments {kickerList}
    
    set paramString "kickerList=\"$kickerList\""
    catch {APSLogScriptAction -procedure APSMpWarmupKickers -action start \
             -state ok -parameters $paramString}

    if {![llength $kickerList]} {
        APSMpReturn error "no kickers selected."
    }

    APSMpStep "Reset Kickers" 
    # send some resets just in case the supply is warm but not fully on
    set retries 5
    for {set try 0} {$try<$retries} {incr try } {
        if {[catch {APScavput -list=[join $kickerList ,] -list=:ResetBO=1} result]} {
            APSMpReturn error "Unable to send reset for kickers ($kickerList): $result"
        }
        after 1000
    }
    APSWaitWithUpdate -waitSeconds 30.0 -updateInterval 1.0
    if {[catch {APScavget -list=[join $kickerList ,] -list=:TStart -num -printErrors} startList]} {
        APSMpReturn error "Unable to read kicker status ($kickerList): $startList"
    }
    set failed 0
    foreach val $startList kick $kickerList {
        if {$val == 0} {
            set failed 1
            if {[catch {APScavput -list=$kick -list=:ResetBO=1} result]} {
                APSMpReturn error "Unable to send reset for kickers ($kick): $result"
            }
        }
    }
    if {$failed} {
        APSWaitWithUpdate -waitSeconds 30.0 -updateInterval 1.0
        if {[catch {APScavget -list=[join $kickerList ,] -list=:TStart -num -printErrors} startList]} {
            APSMpReturn error "Unable to read kicker status ($kickerList): $startList"
        }
        set failed 0
        foreach val $startList kick $kickerList {
            if {$val == 0} {
                set failed 1
                lappend failedList $kick
            }
        }
        if {$failed} {
            if {[APSPEMTKDialog .warningDialog -text "Unable to initiate kicker reset for [join $failedList ,]\nYou may attempt to initiate it and then click continue"] == 1} {
                APSMpReturn error "APSMpSRTurnOnKickers: Unable to initiate kicker reset for [join $failedList ,]"
            }
	    #tk_dialog .warningDialog "Warning Message" "Unable to initiate kicker reset for $failedList" warning -1 Continue
        }
    }

    set tries 17
    while {$tries} {
        set offList [APSSelectKickersNeedingWarmUp -kickerList $kickerList]
        if {[llength $offList]==0} {
            for {set try 0} {$try<$retries} {incr try } {
                if {[catch {APScavput -list=[join $kickerList ,] -list=:ResetBO=1} result]} {
                    APSMpReturn error "Unable to send reset for kickers ($kickerList): $result"
                }
                after 1000
            }
            APSMpStep "Kicker warmup done"
            APSMpReturn ok
        }
        set offList [join $offList ","]
        if {[catch {APScavput -list=$offList -list=:VoltageAO=0,:OnBO=OFF} result]} {
            APSMpReturn error "Error sending resets: $result"
        }
        if {($tries == 16) || ($tries == 10)} {
            if {[catch {APScavput -list=$offList -list=:ResetBO=1} result]} {
                APSMpReturn error "Unable to send reset for kickers ($offList): $result"
            }
        }
        incr tries -1
        APSMpStep "Waiting for kicker warmup (could take up to $tries minutes)"
        APSWaitWithUpdate -waitSeconds 60.0 -updateInterval 1.0
    } 
    set offList [APSSelectKickersNeedingWarmUp -kickerList $kickerList]

    set retries 5
    for {set try 0} {$try<$retries} {incr try } {
	if {[catch {APScavput -list=[join $kickerList ,] -list=:ResetBO=1} result]} {
	    APSMpReturn error "Unable to send reset for kickers ($kickerList): $result"
	}
        after 1000
    }

    if {[llength $offList]==0} {
        APSMpStep "Kicker warmup done"
        APSMpReturn ok
    }
    APSMpStep "Kicker warmup failed: $offList"
    APSMpReturn error
}

proc APSSelectKickersNeedingWarmUp {args} {
    APSStrictParseArguments {kickerList}

    # check (using cathode low bit -- different of different machines) to see if kickers need warmup 
    set paramString "kickerList=\"$kickerList\""
    catch {APSLogScriptAction -procedure APSSelectKickersNeedingWarmUp \
             -action start -state ok -parameters $paramString}

    set offList ""
    foreach kicker $kickerList {
        if {[string match "S:IK\[1-5\]" $kicker]} {
            set cathodeLow [APScavget -list=$kicker -list=:Bit11BI]
        } else {
            set cathodeLow [APScavget -list=$kicker -list=:Bit1BI]
        }
        if {[string compare $cathodeLow ON]==0} {
            lappend offList $kicker
        } else {
            if {![string match "S:IK\[1-5\]" $kicker]} {
                set psStatus [APScavget -list=$kicker -list=:Bit7BI]
                if {[string compare $psStatus ON]==0} {
                    lappend offList $kicker
                }
            }
        }
    }
    return $offList
}


proc APSMpTurnOnSeptum {args} {
    set retries 10
    APSStrictParseArguments {retries}
    set paramString "retries=$retries"
    APSMpStep "APSMpTurnOnSeptum: $paramString" 
    catch {APSLogScriptAction -procedure APSMpTurnOnSeptum -action start \
             -state ok -parameters $paramString}
    while {$retries} {
        APSMpStep "APSMpTurnOnSeptum: retry $retries"
        if {![APScavget -list=P:ISP:StatusCALC]}  break
        if {[catch {APScavput -list=P:ISP:ResetSEQ=1} result]} {
            APSMpReturn error "Error sending on signal: $result"
        }
        after 5000
        incr retries -1
    }
    if {!$retries} {
        APSMpReturn error "Unknown problem turning on septum."
    }
    APSMpStep "APSMpTurnOnSeptum: succeeded"
    APSMpReturn ok
}

proc APSMpPARStopConditioningInfo {} {
    return "This procedure stop the PAR magnet conditioning."
}

proc APSMpPARStopConditioning {} {
    global status
    APSMpStep init -promptDialog "APSMpPromptInitDialog"

    if [catch {APSLinkToDeviceConfigPVs -device par} result] {
	return -code error "APSMpPARStopConditioning: $result"
    }
    if {[catch {APSDevSend \
		  -releaseLinks 1 \
                  -group PSOps \
                  -operation StopConditioning \
                  -deviceList {"P:BM" "P1BMT1" "P1BMT2" "P2BMT1" "P2BMT2" "P3BMT1" "P3BMT2" "P4BMT1" "P4BMT2" "P1H1" "P1H2" "P1H3" "P2H1" "P2H3" "P3H1" "P3H2" "P4H1" "P4H2" "P1V1" "P1V2" "P1V3" "P2V1" "P2V2" "P2V3" "P3V1" "P3V2" "P4V1" "P4V2" "P:Q1" "P:Q2" "P:Q3BP" "P:Q4" "P:S1" "P:SD" "P:SF"}} result]} {
	APSMpReturn error "APSMpPARStopConditioning: Error stopping conditioning of PAR DCPS: $result"
    }
    APSMpReturn ok
}

proc APSMpStopConditioning {args} {
    
    APSStrictParseArguments {magnetList}

    if {![llength $magnetList]} {
        APSMpReturn ok "no magnets selected."

    }
    set magnetList [join $magnetList ","]
    if {[catch {APScavput -list=$magnetList -list=:StandardizeSUB.PROC=0 } result]} {
        APSMpReturn error "Error sending stop conditioning command to $magnetList: $result"
    }
    APSMpReturn ok
}

proc APSMpPARDegauss {args} {
    global controlFilesDir status

    set block 1
    set degaussTime 0
    set excludeSDSF 1
    APSStrictParseArguments {block degaussTime excludeSDSF}
    APSMpStep init -promptDialog "APSMpPromptInitDialog"
    set paramString ""
    foreach param {block degaussTime} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure APSMpPARDegauss -action start \
             -state ok -parameters $paramString}

    APSMpStep "PAR: Configure Degaussing"
    set file ${controlFilesDir}/PAR/PAR_degauss.sdds
    set deleteFile 0
    if {0} {
        if {$degaussTime} {
            set newfile /tmp/[APSTmpString]
            exec sddsconvert $file -pipe=out -delete=col,DecayMinutes,DecaySeconds \
              | sddsprocess -pipe=in $newfile \
              "-define=col,DecayTime,$degaussTime NumDecay /" \
              {-define=col,DecayMinutes,DecayTime int,type=long} \
              {-define=col,DecaySeconds,DecayTime DecayMinutes - 60 * int,type=long}
            set file $newfile
            set deleteFile 1
        }
    }
    if {$excludeSDSF} {
        # Degauss only the H1 correctors.  These are the only ones that are not 
        # normally powered as sextupoles.
        set newfile /tmp/[APSTmpString]
        exec sddsprocess $file $newfile -nowarning -match=column,ControlName=P*H1
        if {$deleteFile} {
            file delete $file
        }
        set file $newfile
        set deleteFile 1
        if {[catch {APScavput -list=P:S1:CurrentAO=0,P1H2:CurrentAO=0,P1H3:CurrentAO=0,P1V1:CurrentAO=0,P1V2:CurrentAO=0,P1V3:CurrentAO=0,P2H2:CurrentAO=0,P2H3:CurrentAO=0,P2V1:CurrentAO=0,P2V2:CurrentAO=0,P2V3:CurrentAO=0,P3H2:CurrentAO=0,P3V1:CurrentAO=0,P3V2:CurrentAO=0,P4H2:CurrentAO=0,P4V1:CurrentAO=0,P4V2:CurrentAO=0 -pend=20} result]} {
            APSMpReturn error "APSMpPARDegauss: Unable to set some PAR correctors to 0: $result"
        }
    } else {
        if {[catch {APScavput -list=P:S -list=D,F,1 -list=:CurrentAO=0} result]} {
            APSMpReturn error "APSMpPARDegauss: Unable to set P:SD, SF, S1 to 0."
        }
    }
    APSMpStep "PAR: Initiate Degaussing"
    if {[catch {exec degauss $file } result]} {
        if {$deleteFile} { file delete -force $file }
        APSMpReturn error "APSMpPARDegauss: Error starting degaussing: $result"
    }
    if {$deleteFile} {
        file delete -force $file
    }
    APSWaitWithUpdate -updateInterval 1 -waitSeconds 2

    APSMpStep "PAR: Check Degaussing"
    if {$excludeSDSF} {
        set condList [APScavget -list=P2H1,P3H1,P4H1,P1H1 \
                        -list=:StandardizeSUB.PROC -label]
    } else {
        set condList [APScavget -list=P2H1,P2V2,P2H3,P3H2,P3H1,P4H1,P4H2,P1H3,P1V2,P1H1 \
                        -list=:StandardizeSUB.PROC -label]
    }
    set problemCond [APSSearchAssociateListForValue -list $condList -value 0]
    if {[llength $problemCond]} {
        APSMpReturn error "APSMpPARDegauss: [llength $problemCond] PAR magnets are not conditioning as expected: $problemCond."
    }

    if {$block} {
        APSMpStep "PAR: Wait For Degaussing"
        while {1} {
            if {[catch {APScavget -list=P:HV:CondCALC -pend=120} result] || \
                  [string compare $result ?]==0} {
                APSMpReturn error "APSMpPARDegauss: Problem reading P:HV:CondCALC---timed out."
            }
            if {!$result} break
            update
            after 2000
        }
    }
    APSMpReturn ok
}

proc APSMpPARTurnOnRfInfo {} {
    return "Please refer to the document OpsDoc_PAR_PEM001_rev.2 for a detailed description of what this software does and how to use it.

Brings both the PAR fundamental (rf1) and harmonic (rf12) rf systems up to full power from any initial state.  Figure 2 shows the operator dialog interface that is brought up when the procedure is started.  When the interface is brought up, the tube amplifier system presently operating rf1 and rf12 is indicated by the depressed radio button at the top of the window.  The operator should select an SCR file (or reference file) containing rf1 and rf12 parameters for good SR bunch purity.  The reference files for the four combinations of rf system (rf1 and rf12) plus tube amplifier (tube amp 1 and tube amp 2) are shown at the bottom of Figure 2.  These reference files are used by this procedure to restore the low level RF parameters for normal operation for BOTH systems.  The SCR file (or reference file) selected by the operator is used to restore the most recent rf1 and rf12 tuner, phase, AGC and source phase setpoints that result in good SR bunch purity.  Figures 3, 4, 7 and 8 show these important setpoints. 
The operator must select the tube amplifier for each rf system using the radio buttons at the top of figure 2 as well as a SCR file containing rf1 and rf12 tuner, phase, AGC and source phase parameters which result in good bunch purity.  The machine procedure will then configure both rf1 and rf12 systems in parallel for both good operation based on the reference file and good bunch purity based on the file selected by the operator (which could be a reference file but must be the reference file corresponding to the radio buttons selected by the operator).

Note that you must select an SCR file date and time range that includes at least one
saved file to be displayed.  After you have set the range, hit the Refresh button to
display the archived files."
}

proc APSMpPARTurnOnRf {args} {
    global PLETSnapshotDir
    set restoreFile ""

    set rf1 1
    set rf12 1
    set rf1UseSystemReference 0
    set rf12UseSystemReference 0
    set useSystemReference 0
    if {[catch {APScavget -list=PAR:Fnd:SystemSelect} rf1amp]} {
        APSMpReturn error "APSMpPARTurnOnRf: Error reading the selected rf1 amplifier"
    }
    if {{"SYSTEM #1"} == $rf1amp} {
        set rf1amp 1
    } else {
        set rf1amp 2
    }
    if {[catch {APScavget -list=PAR:Har:SystemSelect} rf12amp]} {
        APSMpReturn error "APSMpPARTurnOnRf: Error reading the selected rf12 amplifier"
    }
    if {{"SYSTEM #1"} == $rf12amp} {
        set rf12amp 1
    } else {
        set rf12amp 2
    }
    
    APSStrictParseArguments {restoreFile rf1 rf12 rf1UseSystemReference rf12UseSystemReference useSystemReference rf1amp rf12amp}

    set ShortFilename $restoreFile
    set Description ""
    APSMpStep init -promptDialog APSMpPARTurnOnRfInitDialog -vars {ShortFilename rf1amp rf12amp useSystemReference}
    set restoreFile $ShortFilename

    if {$useSystemReference != 2} {
        set rf1UseSystemReference $useSystemReference
        set rf12UseSystemReference $useSystemReference
    }

    set paramString ""
    foreach param {restoreFile rf1 rf12 rf1UseSystemReference rf12UseSystemReference rf1amp rf12amp} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure APSMpPARTurnOnRf -action initialize \
             -state ok -parameters $paramString}

    #Check if either rf1 or rf12 is to be turned on
    if {(!$rf1) && (!$rf12)} {
        APSMpReturn ok
    }

    #Check if we are not to use a system reference file
    if { (($rf1)  && (($rf1UseSystemReference == 0)  || ($rf1UseSystemReference == 1))) || (($rf12) && (($rf12UseSystemReference == 0) || ($rf12UseSystemReference == 1)))} {

        if {[catch {exec sddsselect $PLETSnapshotDir/$restoreFile /home/helios/oagData/pem/par/SCRFilterFile -match=ControlName -pipe=out | sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
            APSMpReturn error "APSMpPARTurnOnRf: Invalid SCR file"
        }
        set PARRF1On "Off"
        set PARRF12On "Off"
        foreach {controlName valueString} $results {
            if {$controlName == "PAR:RF1:abBoA0C7S0"} {
                set PARRF1On $valueString
            } elseif {$controlName == "PAR:RF12:abBoA1C5S2"} {
                set PARRF12On $valueString
            }
        }
        
        if {($rf1) && (!$rf1UseSystemReference)} {
            if {($PARRF1On != "On")} {
                if {[APSPEMTKDialog .warningDialog -text "RF1 was not on when the SCR file was created. RF1 values will now be taken from the system reference file."] == 1} {
                    APSMpReturn error "APSMpPARTurnOnRf: RF1 was not on when the SCR file was created."
                }
                set rf1UseSystemReference 2
            }
        }
        if {($rf12) && (!$rf12UseSystemReference)} {
            if {($PARRF12On != "On")} {
                if {[APSPEMTKDialog .warningDialog -text "RF12 was not on when the SCR file was created. RF12 values will now be taken from the system reference file."] == 1} {
                    APSMpReturn error "APSMpPARTurnOnRf: RF1 was not on when the SCR file was created."
                }
                set rf12UseSystemReference 2
            }
        }
    }

    #Suspend 12th Harmonic Feed Forward
    APSMpStep "Suspend 12th Harmonic Feed Forward"
    if {[catch {APScavput -list=PAR:RF12:TunerFeedFwdRC.SUSP=1} result]} {
        APSMpReturn error "APSMpPARTurnOnRf: $result"
    }
    #Turn on the RF systems
    if {$rf1} {
        APSMpStep "PAR: Turn On Rf1 (optional)" -proc "APSMpPARTurnOnRf1"
        set rf1ID [APSMpParallel -procedure "APSMpPARTurnOnRf1 -restoreFile $restoreFile -rf1amp $rf1amp -useSystemReference $rf1UseSystemReference -rf12amp $rf12amp" -mode Automatic]
    }
    if {$rf12} {
        APSMpStep "PAR: Turn On Rf12 (optional)" -proc "APSMpPARTurnOnRf12"
        set rf12ID [APSMpParallel -procedure "APSMpPARTurnOnRf12 -restoreFile $restoreFile -rf12amp $rf12amp -useSystemReference $rf12UseSystemReference -rf1amp $rf1amp" -mode Automatic]
    }
#    APSMpAbort all -onError 1
    if {$rf12} {
        APSMpStep "PAR: Complete RF12 Startup"
        if {[catch {APSMpJoin $rf12ID} rf12Status]} {
            APSMpReturn error "APSMpPARTurnOnRf: $rf12Status"
        }
    }
    if {$rf1} {
        APSMpStep "PAR: Complete RF1 Startup"
        if {[catch {APSMpJoin $rf1ID} rf1Status]} {
            APSMpReturn error "APSMpPARTurnOnRf: $rf1Status"
        }
    }
    #Resume 12th Harmonic Feed Forward
    APSMpStep "Resume 12th Harmonic Feed Forward"
    if {[catch {APScavput -list=PAR:RF12:TunerFeedFwdRC.SUSP=0} result]} {
        APSMpReturn error "APSMpPARTurnOnRf: $result"
    }
    APSMpReturn ok
}

proc APSMpPARTurnOnRfInitDialog {frame} {
    global APSMpPARTurnOnRf

    APSRadioButtonFrame .rb1 -parent $frame -label "RF1 Amp: " \
      -variable APSMpPARTurnOnRf(rf1amp) \
      -contextHelp "Choose which RF amp to use." \
      -buttonList "{Tube Amp System \#1} {Tube Amp System \#2}" \
      -valueList "1 2"

    APSRadioButtonFrame .rb12 -parent $frame -label "RF12 Amp: " \
      -variable APSMpPARTurnOnRf(rf12amp) \
      -contextHelp "Choose which RF amp to use." \
      -buttonList "{Tube Amp System \#1} {Tube Amp System \#2}" \
      -valueList "1 2"

    APSRadioButtonFrame .rb2 -parent $frame -label "System Reference File: " \
      -variable APSMpPARTurnOnRf(useSystemReference) \
      -contextHelp "Choose how to use the system reference file" \
      -buttonList "{Use Selected SCR File} {Use System Reference File}" -valueList "0 2"

    APSAddSCRDialog .scr -parent $frame -system LPL -arrayName APSMpPARTurnOnRf \
      -defaultFile $APSMpPARTurnOnRf(ShortFilename)

    global PLETSnapshotDir
    set APSMpPARTurnOnRf(ShortFilename) LPL-SysRef_PAR_RF.gz
    set APSMpPARTurnOnRf(Description) SysRef_PAR_RF
    set APSMpPARTurnOnRf(Filename) $PLETSnapshotDir/LPL-SysRef_PAR_RF.gz
}

proc APSMpPARTurnOnRf1Info {} {
    return "This procedure is contains only the rf1 half of the APSMpPARTurnOnRf procedure."
}

proc APSMpPARTurnOnRf1 {args} {
    global PLETSnapshotDir
    set restoreFile ""
    set useSystemReference 0
    if {[catch {APScavget -list=PAR:Fnd:SystemSelect} rf1amp]} {
        APSMpReturn error "Error reading the selected rf1 amplifier"
    }
    if {{"SYSTEM #1"} == $rf1amp} {
        set rf1amp 1
    } else {
        set rf1amp 2
    }
    if {[catch {APScavget -list=PAR:Har:SystemSelect} rf12amp]} {
        APSMpReturn error "APSMpPARTurnOnRf: Error reading the selected rf12 amplifier"
    }
    if {{"SYSTEM #1"} == $rf12amp} {
        set rf12amp 1
    } else {
        set rf12amp 2
    }
    set currentAmp $rf1amp

    APSStrictParseArguments {restoreFile rf1amp useSystemReference rf12amp}

    set ShortFilename $restoreFile
    set Description ""
    APSMpStep init -promptDialog APSMpPARTurnOnRf1InitDialog -vars {ShortFilename rf1amp rf12amp useSystemReference}

    set paramString ""
    foreach param {restoreFile rf1amp useSystemReference rf12amp} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure APSMpPARTurnOnRf1 -action initialize \
             -state ok -parameters $paramString}

    set restoreFile $ShortFilename
    if {($useSystemReference == 0) || ($useSystemReference == 1)} {
        if {[string length $restoreFile] && ![file exists $PLETSnapshotDir/$restoreFile]} {
            APSMpReturn error "File [file tail $restoreFile] not found."
        }
        if {![llength $restoreFile]} {
            APSMpReturn error "No SCR file selected."
        }
        if {[catch {exec sdds2stream $PLETSnapshotDir/$restoreFile -parameter=SnapshotDescription -page=1 -noquotes} results]} {
            APSMpReturn error "APSMpPARTurnOnRf1: Invalid SCR file"
        }
        if {[string first "Limited save:" $results] != -1} {
            if {[catch {exec sddssort $PLETSnapshotDir/$restoreFile -pipe=out -column=Beamline -unique | sdds2stream -pipe=in -col=Beamline} results]} {
                APSMpReturn error "APSMpPARTurnOnRf1: Problem reading beamlines categories from the SCR file"
            } else {
                if {([lsearch -exact $results PAR] == -1)} {
                    APSMpReturn error "APSMpPARTurnOnRf1: LIMITED SAVE SCR file does not include the PAR beamline category"
                }
            }
        }

        if {[catch {exec sddsselect $PLETSnapshotDir/$restoreFile /home/helios/oagData/pem/par/SCRFilterFile -match=ControlName -pipe=out | sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
            APSMpReturn error "APSMpPARTurnOnRf1: Invalid SCR file"
        }
        set PARRF1On "Off"
        set PARRF1PhaseShift ""
        foreach {controlName valueString} $results {
            if {$controlName == "PAR:RF1:abBoA0C7S0"} {
                set PARRF1On $valueString
            }
        }
        if {$PARRF1On != "On"} {
            if {[APSPEMTKDialog .warningDialog -text "RF1 was not on when the SCR file was created. RF1 values will now be taken from the system reference file."] == 1} {
                APSMpReturn error "APSMpPARTurnOnRf1: RF1 was not on when the SCR file was created."
            }
            set useSystemReference 2
        }
    }

    set ampSwitched 0
    if {$rf1amp != $currentAmp} {
        set ampSwitched 1
    }
    #Suspend 12th Harmonic Feed Forward
    APSMpStep "Suspend 12th Harmonic Feed Forward"
    if {[catch {APScavput -list=PAR:RF12:TunerFeedFwdRC.SUSP=1} result]} {
        APSMpReturn error "APSMpPARTurnOnRf1: $result"
    }
    APSMpStep "PAR: Switch Rf1 amp if needed" -proc "APSMpPARSwitchRfSystem"
    if {[catch {APSMpPARSwitchRfSystem -amp $rf1amp -system 1} result]} {
        APSMpReturn error "Error switching rf1 amp: $result"
    }
    APSMpStep "PAR: Turn On Rf1" -proc "APSMpPARTurnOnRfSystem"
    if {[catch {APSMpPARTurnOnRfSystem -restoreFile $restoreFile -system 1 -useSystemReference $useSystemReference -rf1amp $rf1amp -rf12amp $rf12amp -ampSwitched $ampSwitched} result]} {
        APSMpReturn error "Error turning on rf1: $result"
    }
    APSMpReturn ok
}

proc APSMpPARTurnOnRf1InitDialog {frame} {
    global APSMpPARTurnOnRf1

    APSRadioButtonFrame .rb1 -parent $frame -label "Amp: " \
      -variable APSMpPARTurnOnRf1(rf1amp) \
      -contextHelp "Choose which RF amp to use." \
      -buttonList "{Tube Amp System \#1} {Tube Amp System \#2}" -valueList "1 2"

    APSRadioButtonFrame .rb2 -parent $frame -label "System Reference File: " \
      -variable APSMpPARTurnOnRf1(useSystemReference) \
      -contextHelp "Choose how to use the system reference file" \
      -buttonList "{Use Selected SCR File} {Use System Reference File}" -valueList "0 2"

    APSAddSCRDialog .scr -parent $frame -system LPL -arrayName APSMpPARTurnOnRf1 \
      -defaultFile $APSMpPARTurnOnRf1(ShortFilename)

    global PLETSnapshotDir
    set APSMpPARTurnOnRf1(ShortFilename) LPL-SysRef_PAR_RF.gz
    set APSMpPARTurnOnRf1(Description) SysRef_PAR_RF
    set APSMpPARTurnOnRf1(Filename) $PLETSnapshotDir/LPL-SysRef_PAR_RF.gz
}

proc APSMpPARTurnOnRf12Info {} {
    return "This procedure is contains only the rf12 half of the APSMpPARTurnOnRf procedure."
}

proc APSMpPARTurnOnRf12 {args} {
    global PLETSnapshotDir
    set restoreFile ""
    set useSystemReference 0
    if {[catch {APScavget -list=PAR:Fnd:SystemSelect} rf1amp]} {
        APSMpReturn error "Error reading the selected rf1 amplifier"
    }
    if {{"SYSTEM #1"} == $rf1amp} {
        set rf1amp 1
    } else {
        set rf1amp 2
    }
    if {[catch {APScavget -list=PAR:Har:SystemSelect} rf12amp]} {
        APSMpReturn error "Error reading the selected rf12 amplifier"
    }
    if {{"SYSTEM #1"} == $rf12amp} {
        set rf12amp 1
    } else {
        set rf12amp 2
    }
    set currentAmp $rf12amp

    APSStrictParseArguments {restoreFile rf12amp useSystemReference rf1amp}

    set ShortFilename $restoreFile
    set Description ""
    APSMpStep init -promptDialog APSMpPARTurnOnRf12InitDialog -vars {ShortFilename rf1amp rf12amp useSystemReference}

    set paramString ""
    foreach param {restoreFile rf1amp useSystemReference rf12amp} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure APSMpPARTurnOnRf12 -action initialize \
             -state ok -parameters $paramString}

    set restoreFile $ShortFilename
    if {($useSystemReference == 0) || ($useSystemReference == 1)} {
        if {[string length $restoreFile] && ![file exists $PLETSnapshotDir/$restoreFile]} {
            APSMpReturn error "File [file tail $restoreFile] not found."
        }
        if {![llength $restoreFile]} {
            APSMpReturn error "No SCR file selected."
        }
        if {[catch {exec sdds2stream $PLETSnapshotDir/$restoreFile -parameter=SnapshotDescription -page=1 -noquotes} results]} {
            APSMpReturn error "APSMpPARTurnOnRf12: Invalid SCR file"
        }    
        if {[string first "Limited save:" $results] != -1} {
            if {[catch {exec sddssort $PLETSnapshotDir/$restoreFile -pipe=out -column=Beamline -unique | sdds2stream -pipe=in -col=Beamline} results]} {
                APSMpReturn error "APSMpPARTurnOnRf12: Problem reading beamlines categories from the SCR file"
            } else {
                if {([lsearch -exact $results PAR] == -1)} {
                    APSMpReturn error "APSMpPARTurnOnRf12: LIMITED SAVE SCR file does not include the PAR beamline category"
                }
            }
        }
        
        if {[catch {exec sddsselect $PLETSnapshotDir/$restoreFile /home/helios/oagData/pem/par/SCRFilterFile -match=ControlName -pipe=out | sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
            APSMpReturn error "APSMpPARTurnOnRf12: Invalid SCR file"
        }
        set PARRF12On "Off"
        foreach {controlName valueString} $results {
            if {$controlName == "PAR:RF12:abBoA1C5S2"} {
                set PARRF12On $valueString
            }
        }
        if {$PARRF12On != "On"} {
            if {[APSPEMTKDialog .warningDialog -text "RF12 was not on when the SCR file was created. RF12 values will now be taken from the system reference file."] == 1} {
                APSMpReturn error "APSMpPARTurnOnRf12: RF12 was not on when the SCR file was created."
            }
            set useSystemReference 2
        }
    }

    set ampSwitched 0
    if {$rf12amp != $currentAmp} {
        set ampSwitched 1
#	catch {exec rm /home/helios/oagData/controllaw/BOOSTER/longBooster/B2C8P2/longBooster.tests}
#	if {[catch {exec ln -fs /home/helios/oagData/controllaw/BOOSTER/longBooster/B2C8P2/longBooster.parRf12Act_Sys${rf12amp}.tests-0000 /home/helios/oagData/controllaw/BOOSTER/longBooster/B2C8P2/longBooster.tests} result]} {
#	    APSMpReturn error "Error switching rf12 amp: $result"
#	}
    }
    #Suspend 12th Harmonic Feed Forward
    APSMpStep "Suspend 12th Harmonic Feed Forward"
    if {[catch {APScavput -list=PAR:RF12:TunerFeedFwdRC.SUSP=1} result]} {
        APSMpReturn error "APSMpPARTurnOnRf12: $result"
    }
    APSMpStep "PAR: Switch Rf12 amp if needed" -proc "APSMpPARSwitchRfSystem"
    if {[catch {APSMpPARSwitchRfSystem -amp $rf12amp -system 12} result]} {
        APSMpReturn error "Error switching rf12 amp: $result"
    }
    APSMpStep "PAR: Turn On Rf12" -proc "APSMpPARTurnOnRfSystem"
    if {[catch {APSMpPARTurnOnRfSystem -restoreFile $restoreFile -system 12 -useSystemReference $useSystemReference -rf1amp $rf1amp -rf12amp $rf12amp -ampSwitched $ampSwitched} result]} {
        APSMpReturn error "Error turning on rf12: $result"
    }
    APSMpStep "PAR: Tune Rf12 Cavity" -proc "APSMpPARTuneRfCavity"
    if {[catch {APSMpPARTuneRfCavity -system 12 -stepSize .01} result]} {
        APSMpReturn error "Error tuning rf12: $result"
    }
    APSMpReturn ok
}

proc APSMpPARTurnOnRf12InitDialog {frame} {
    global APSMpPARTurnOnRf12

    APSRadioButtonFrame .rb1 -parent $frame -label "Amp: " \
      -variable APSMpPARTurnOnRf12(rf12amp) \
      -contextHelp "Choose which RF amp to use." \
      -buttonList "{Tube Amp System \#1} {Tube Amp System \#2}" -valueList "1 2"

    APSRadioButtonFrame .rb2 -parent $frame -label "System Reference File: " \
      -variable APSMpPARTurnOnRf12(useSystemReference) \
      -contextHelp "Choose how to use the system reference file" \
      -buttonList "{Use Selected SCR File} {Use System Reference File}" -valueList "0 2"

    APSAddSCRDialog .scr -parent $frame -system LPL -arrayName APSMpPARTurnOnRf12 \
      -defaultFile $APSMpPARTurnOnRf12(ShortFilename)

    global PLETSnapshotDir
    set APSMpPARTurnOnRf12(ShortFilename) LPL-SysRef_PAR_RF.gz
    set APSMpPARTurnOnRf12(Description) SysRef_PAR_RF
    set APSMpPARTurnOnRf12(Filename) $PLETSnapshotDir/LPL-SysRef_PAR_RF.gz
}


proc APSMpPARSwitchRfSystem {args} {
    global PLETSnapshotDir status
    set onPV(1)  PAR:RF1:abBoA0C7S0
    set onPV(12) PAR:RF12:abBoA1C5S2

    set amp 1
    set system 1
    APSStrictParseArguments {system amp}

    set paramString "amp=$amp system=$system"
    catch {APSLogScriptAction -procedure APSMpPARSwitchRfSystem -action start \
             -state ok -parameters $paramString}

    if {[string compare $system 12]==0} {
        if {[catch {APScavget -list=PAR:Har:SystemSelect} currentAmp]} {
            APSMpReturn error "Error reading the selected rf12 amplifier"
        }
        if {{"SYSTEM #1"} == $currentAmp} {
            set currentAmp 1
        } elseif {{"SYSTEM #2"} == $currentAmp} {
            set currentAmp 2
        } else {
            APSMpReturn error "Error reading the selected rf12 amplifier: $currentAmp"
        }
    } else {
        if {[catch {APScavget -list=PAR:Fnd:SystemSelect} currentAmp]} {
            APSMpReturn error "Error reading the selected rf1 amplifier"
        }
        if {{"SYSTEM #1"} == $currentAmp} {
            set currentAmp 1
        } elseif {{"SYSTEM #2"} == $currentAmp} {
            set currentAmp 2
        } else {
            APSMpReturn error "Error reading the selected rf1 amplifier: $currentAmp"
        }
    }
    if {$amp == $currentAmp} {
        APSMpReturn ok
    }
    if {[string compare $system 12]==0} {
        if {$amp == 1} {
            if {[catch {APScavget -list=PAR:RF12:envDet2Ch0Watt} result]} {
                APSMpReturn error "Error checking for backup rf12 forward power: $result"
            }
        } else {
            if {[catch {APScavget -list=PAR:RF12:envDet2Ch2Watt} result]} {
                APSMpReturn error "Error checking for backup rf12 forward power: $result"
            }
        }
        if {$result > 10} {
            APSMpReturn error "Backup rf12 forward power is $result which is greater than 10 Watts. Please contact the RF people before proceeding."
        }
    } else {
        if {[catch {APScavget -list=PAR:Fnd${amp}:RfPowerFwdCalc} result]} {
            APSMpReturn error "Error checking for backup rf1 forward power: $result"
        }
        if {$result > 10} {
            APSMpReturn error "Backup rf1 forward power is $result which is greater than 10 Watts. Please contact the RF people before proceeding."
        }
    }
    
    #Stop Bunch Cleaning
#    APSMpStep "Stop Bunch Cleaning"
#    if {[catch {APSMpPARStopBunchCleaning} result]} {
#        APSMpReturn error "APSMpPARSwitchRfSystem: $result"
#    }

    #Suspend 12th Harmonic Feed Forward
    APSMpStep "Suspend 12th Harmonic Feed Forward"
    if {[catch {APScavput -list=PAR:RF12:TunerFeedFwdRC.SUSP=1} result]} {
        APSMpReturn error "APSMpPARSwitchRfSystem: $result"
    }

    #Suspend Booster Longitudinal Controllaw
    APSMpStep "Suspend Booster Longitudinal Controllaw"
    if {[catch {APScavput -list=Booster:ControlLawLongRC.SUSP=1} result]} {
        APSMpReturn error "APSMpPARSwitchRfSystem: $result"
    }


    if {[catch {APScavput -list=$onPV($system)=Off} result]} {
        APSMpReturn error "Error sending command to turn off rf: $result"
    }
    if {[catch {APScavput -list=$onPV($system)=0} result]} {
        APSMpReturn error "Error sending command to turn off rf: $result"
    }
    if {[string compare $system 12]==0} {
        APSMpStep "Setting RF12 into standby mode"
        if {[catch {APScavput -list=PAR:Har:RemoteStandBy=1} result]} {
            APSMpReturn error "Error putting rf12 amplifier in standby mode."
        }

        if {[catch {APScavget -list=PAR:Har:SystemSelect} selectedAmp]} {
            APSMpReturn error "Error reading the selected rf12 amplifier"
        }
        APSMpStep "Send the Fault Reset for RF12 switch"
        if {[catch {APScavput -list=PAR:Har:SW:ErrAckBO=1} result]} {
            APSMpReturn error "Error sending the fault reset for harmonic RF switch."
        }
        if {{"SYSTEM #1"} == $selectedAmp} {
            set selectedAmp 1
        } elseif {{"SYSTEM #2"} == $selectedAmp} {
            set selectedAmp 2
        } else {
            APSMpReturn error "Error reading the selected rf12 amplifier: $selectedAmp"
        }
        if {$selectedAmp == 2} {
            APSMpStep "Waiting for RF12 switch drain voltage to be below 5.75"
            for {set i 0} {$i <= 120} {incr i} {
                if {[catch {APScavget -list=PRF:H:SSA2:DA_DrainVoltM -num} result]} {
                    APSMpReturn error "Error reading PRF:H:SSA2:DA_DrainVoltM: $result"
                }
                if {$result < 5.75} {
                    break
                }
                if {$i == 120} {
                    if {[APSPEMTKDialog .warningDialog -text "RF12 switch drain voltage never got below 5.75"] == 1} {
                        APSMpReturn error "RF12 switch drain voltage never got below 5.75: $result"
                    }
                    break
                }
                APSWaitWithUpdate -waitSeconds 1
            }
        }

        APSMpStep "Start Enable \#1 in the RF12 switch"
        if {[catch {APScavput -list=PAR:Har:SW:Ena1BO=0} result]} {
            APSMpReturn error "Error switching harmonic RF switch: $result"            
        }
        for {set i 0} {$i <= 60} {incr i} {
            if {[catch {APScavget -list=PAR:Har:SW:Ena1StatBI -num} result]} {
                APSMpReturn error "Error switching harmonic RF switch: $result"            
            }
            if {$result == 1} {
                break
            }
            if {$i == 60} {
                APSMpReturn error "Error switching harmonic RF switch: $result"
            }
            APSWaitWithUpdate -waitSeconds 1
        }
        APSMpStep "Start Enable \#2 in the RF12 switch"
        if {[catch {APScavput -list=PAR:Har:SW:Ena2BO=0} result]} {
            APSMpReturn error "Error switching harmonic RF switch: $result"            
        }
        for {set i 0} {$i <= 60} {incr i} {
            if {[catch {APScavget -list=PAR:Har:SW:Ena2StatBI -num} result]} {
                APSMpReturn error "Error switching harmonic RF switch: $result"
            }
            if {$result == 1} {
                break
            }
            if {$i == 60} {
                APSMpReturn error "Error switching harmonic RF switch: $result"
            }
            APSWaitWithUpdate -waitSeconds 1
        }
        APSMpStep "Start Enable \#3 in the RF12 switch"
        if {[catch {APScavput -list=PAR:Har:SW:Ena3BO=0} result]} {
            APSMpReturn error "Error switching harmonic RF switch: $result"            
        }
        for {set i 0} {$i <= 60} {incr i} {
            if {[catch {APScavget -list=PAR:Har:SW:Ena3StatBI -num} result]} {
                APSMpReturn error "Error switching harmonic RF switch: $result"            
            }
            if {$result == 1} {
                break
            }
            if {$i == 60} {
                APSMpReturn error "Error switching harmonic RF switch: $result"
            }
            APSWaitWithUpdate -waitSeconds 1
        }
        APSMpStep "Clicking the Start Switch in the RF12 switch"
        if {[catch {APScavput -list=PAR:Har:SW:StartSeqBO=1} result]} {
            APSMpReturn error "Error switching harmonic RF switch: $result"            
        }
        APSWaitWithUpdate -waitSeconds 1
        for {set i 0} {$i <= 60} {incr i} {
            if {[catch {APScavget -list=PAR:Har:SW:StateDoneBI,PAR:Har:SW:SS_1ErrBI,PAR:Har:SW:SS_2ErrBI,PAR:Har:SW:SS_3ErrBI,PAR:Har:SW:SS_4ErrBI,PAR:Har:SW:SS_5ErrBI -num} result]} {
                APSMpReturn error "Error switching harmonic RF switch: $result"            
            }
            set status [lindex $result 0]
            set fault1 [lindex $result 1]
            set fault2 [lindex $result 2]
            set fault3 [lindex $result 3]
            set fault4 [lindex $result 4]
            set fault5 [lindex $result 5]
            if {$status == 1} {
                break
            }
            if {($fault1 == 1) || ($fault2 == 1) || ($fault3 == 1) || ($fault4 == 1) || ($fault5 == 1)} {
                APSMpReturn error "Error switching harmonic RF switch: fault detected in switch sequence status"                
            } 
            if {$i == 60} {
                APSMpReturn error "Error switching harmonic RF switch: timed out"
            }
            APSWaitWithUpdate -waitSeconds 1
        }
    } else {

        APSMpStep "Turning off the plate in the RF1 switch"
        if {[catch {APScavput -list=PAR:Fnd:PlateOFF=1} result]} {
            APSMpReturn error "Error turning off the plate in rf1."
        }
        APSMpStep "Turning off the filament in the RF1 switch"
        if {[catch {APScavput -list=PAR:Fnd:FilamentOFF=1} result]} {
            APSMpReturn error "Error turning off the filament in rf1."
        }

        APSMpStep "Start Enable \#1 in the RF1 switch"
        if {[catch {APScavput -list=PAR:Fnd:SW:Ena1BO=0} result]} {
            APSMpReturn error "Error switching fundamental RF switch: $result"            
        }
        for {set i 0} {$i <= 60} {incr i} {
            if {[catch {APScavget -list=PAR:Fnd:SW:Ena1StatBI -num} result]} {
                APSMpReturn error "Error switching fundamental RF switch: $result"            
            }
            if {$result == 1} {
                break
            }
            if {$i == 60} {
                APSMpReturn error "Error switching fundamental RF switch: Enable \#1 button did not complete correctly"
            }
            APSWaitWithUpdate -waitSeconds 1
        }
        APSMpStep "Start Enable \#2 in the RF1 switch"
        if {[catch {APScavput -list=PAR:Fnd:SW:Ena2BO=0} result]} {
            APSMpReturn error "Error switching fundamental RF switch: $result"            
        }
        for {set i 0} {$i <= 60} {incr i} {
            if {[catch {APScavget -list=PAR:Fnd:SW:Ena2StatBI -num} result]} {
                APSMpReturn error "Error switching fundamental RF switch: $result"            
            }
            if {$result == 1} {
                break
            }
            if {$i == 60} {
                APSMpReturn error "Error switching fundamental RF switch:  Enable \#2 button did not complete correctly"
            }
            APSWaitWithUpdate -waitSeconds 1
        }
        APSMpStep "Start Enable \#3 in the RF1 switch"
        if {[catch {APScavput -list=PAR:Fnd:SW:Ena3BO=0} result]} {
            APSMpReturn error "Error switching fundamental RF switch: $result"            
        }
        for {set i 0} {$i <= 60} {incr i} {
            if {[catch {APScavget -list=PAR:Fnd:SW:Ena3StatBI -num} result]} {
                APSMpReturn error "Error switching fundamental RF switch: $result"            
            }
            if {$result == 1} {
                break
            }
            if {$i == 60} {
                APSMpReturn error "Error switching fundamental RF switch:  Enable \#3 button did not complete correctly"
            }
            APSWaitWithUpdate -waitSeconds 1
        }
        APSMpStep "Clicking the Start Switch in the RF1 switch"

        if {[catch {APScavput -list=PAR:Fnd:SW:StartSeqBO=1} result]} {
            APSMpReturn error "Error switching fundamental RF switch: $result"            
        }
        APSWaitWithUpdate -waitSeconds 1
        for {set i 0} {$i <= 60} {incr i} {
            if {[catch {APScavget -list=PAR:Fnd:SW:StateDoneBI,PAR:Fnd:SW:SS_1ErrBI,PAR:Fnd:SW:SS_2ErrBI,PAR:Fnd:SW:SS_3ErrBI,PAR:Fnd:SW:SS_4ErrBI,PAR:Fnd:SW:SS_5ErrBI -num} result]} {
                APSMpReturn error "Error switching fundamental RF switch: $result"            
            }
            set status [lindex $result 0]
            set fault1 [lindex $result 1]
            set fault2 [lindex $result 2]
            set fault3 [lindex $result 3]
            set fault4 [lindex $result 4]
            set fault5 [lindex $result 5]
            if {$status == 1} {
                break
            }
            if {($fault1 == 1) || ($fault2 == 1) || ($fault3 == 1) || ($fault4 == 1) || ($fault5 == 1)} {
                APSMpReturn error "Error switching fundamental RF switch: fault detected in switch sequence status"                
            } 
            if {$i == 60} {
                APSMpReturn error "Error switching fundamental RF switch: timed out"
            }
            APSWaitWithUpdate -waitSeconds 1
        }
    }
    APSMpReturn ok
}

proc APSMpPARTurnOnRfSystem {args} {
    global PLETSnapshotDir status
    set onPV(1)  PAR:RF1:abBoA0C7S0
    set onPV(12) PAR:RF12:abBoA1C5S2

    set restoreFile ""
    set system 1
    #useSystemReference=0 means only use restoreFile
    #useSystemReference=1 means use system reference file for everything but phaseShifter1Ch2 phaseShifter1Ch3 (NO LONGER USED)
    #useSystemReference=2 means use system reference file only
    set useSystemReference 0
    set rf1amp 1
    set rf12amp 1
    set ampSwitched 0
    set mode "fast"
    set mode "slow"
    APSStrictParseArguments {restoreFile system useSystemReference rf1amp rf12amp ampSwitched}

    set paramString ""
    foreach param {restoreFile system useSystemReference rf1amp rf12amp ampSwitched} {
	append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure APSMpPARTurnOnRfSystem -action start \
	     -state ok -parameters $paramString}
    
    set systemRefFile $PLETSnapshotDir/LPL-SysRef_PAR_RF.gz
    if {($useSystemReference == 0) || ($useSystemReference == 1)} {
	if {[string length $restoreFile]==0} {
	    set status "No restore file given for Rf$system turn on."
	    APSMpReturn error "No restore file given for Rf$system turn on."
	}
	if {![llength $restoreFile]} {
	    APSMpReturn error "No SCR file selected."
	}
	if {![file exists $PLETSnapshotDir/$restoreFile]} {
	    set status "File $restoreFile not found."
	    APSMpReturn error "File $restoreFile not found."
	}
	if {[catch {exec sdds2stream $PLETSnapshotDir/$restoreFile -parameter=SnapshotDescription -page=1 -noquotes} results]} {
	    APSMpReturn error "APSMpPARTurnOnRfSystem: Invalid SCR file"
	}
	if {[string first "Limited save:" $results] != -1} {
            if {[catch {exec sddssort $PLETSnapshotDir/$restoreFile -pipe=out -column=Beamline -unique | sdds2stream -pipe=in -col=Beamline} results]} {
                APSMpReturn error "APSMpPARTurnOnRfSystem: Problem reading beamlines categories from the SCR file"
            } else {
                if {([lsearch -exact $results PAR] == -1)} {
                    APSMpReturn error "APSMpPARTurnOnRfSystem: LIMITED SAVE SCR file does not include the PAR beamline category"
                }
            }
	}
        if {$useSystemReference == 0} {
            set systemRefFile $PLETSnapshotDir/$restoreFile
        }
    } else {
        #override the given restoreFile
        set restoreFile LPL-SysRef_PAR_RF.gz
    }



    if {[string compare $system 12]==0} {
        if {[catch {APScavget -list=PAR:RF12:gapVoltage1 -num} gapVoltage]} {
            APSMpReturn error "Error checking gap voltage"
        }
    } else {
        if {[catch {APScavget -list=PAR:RF1:gapVoltage1 -num} gapVoltage]} {
            APSMpReturn error "Error checking gap voltage"
        }
    }
    if {$gapVoltage < 1} {
        if {[catch {APScavput -list=$onPV($system)=Off} result]} {
            APSMpReturn error "Error sending command to turn off rf: $result"
        }
    }

    while {1} {
        
        
        APSMpStep "Checking state ACIS"
        if {[catch {APScavget -list=PAR:RF:ACISstatus -num} acis]} {
            APSMpReturn error "Error checking state ACIS"
        }
        if {$acis == 0} {
            APSMpStep "Reseting ACIS"
            if {[catch {APScavput -list=PAR:RF1:abBoA0C5S6=1} result]} {
                APSMpReturn error "Error reseting ACIS: $result"
            }
        }
        
        
        APSMpStep "Checking if RF is already on"
        if {[catch {APScavget -list=$onPV($system) -num} alreadyOn]} {
            APSMpReturn error "Error checking state of RF: $alreadyOn"
        }
        if {$alreadyOn == 1} {
            if {[string compare $system 1]==0} {
                APSMpStep "Checking state of interlock, filament and plate voltage"
                if {[catch {APScavget -list=PAR:Fnd:InterlockOK -num} interlock]} {
                    APSMpReturn error "Error checking state of RF interlock: $interlock"
                }
                if {[catch {APScavget -list=PAR:Fnd:FilOn -num} filament]} {
                    APSMpReturn error "Error checking state of RF filament: $filament"
                }
                if {[catch {APScavget -list=PAR:Fnd:PlateOn -num} plate]} {
                    APSMpReturn error "Error checking state of RF plate: $plate"
                }
                if {($interlock != 1) || ($filament != 1) || ($plate != 1)} {
                    set alreadyOn 0
                }
            }
        }
        if {$alreadyOn == 1} {
	    APSMpStep "PAR RF $system is already on."
	} else {
	    APSMpStep "PAR RF $system is not already on."
	}
        
        set tmpFile /tmp/[APSTmpString]
        if {[string compare $system 12]==0} {
            if {[catch {APScavget -list=PAR:Har:SystemSelect} selectedAmp]} {
                APSMpReturn error "Error reading the selected rf12 amplifier"
            }
            if {{"SYSTEM #1"} == $selectedAmp} {
                set selectedAmp 1
            } elseif {{"SYSTEM #2"} == $selectedAmp} {
                set selectedAmp 2
            } else {
                APSMpReturn error "Error reading the selected rf12 amplifier: $selectedAmp"
            }
            if {[catch {exec sddsselect $systemRefFile /home/helios/oagData/pem/par/SCRFilterFile \
                          -match=ControlName -pipe=out | \
                          sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
                APSMpReturn error "APSMpPARTurnOnRfSystem2: Invalid SCR file"
            }
            foreach {controlName valueString} $results {
                if {$controlName == "PRF:H:FBM2:pidSpCh1AO"} {
                    set tuner $valueString
                } elseif {$controlName == "PRF:H:FBM1:pidSpCh0AO"} {
                    set agc $valueString
                } elseif {$controlName == "PRF:H:FBM1:pidSpCh1AO"} {
                    set cavity $valueString
                } elseif {$controlName == "PAR:RF12:PhsShft2Ch2_3AO"} {
                    set phaseShifter $valueString
                }
            }
            if {0} {            
            if {[catch {exec sddsselect $PLETSnapshotDir/$restoreFile /home/helios/oagData/pem/par/SCRFilterFile \
                          -match=ControlName -pipe=out | \
                          sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
                APSMpReturn error "APSMpPARTurnOnRfSystem3: Invalid SCR file"
            }
            set PARRF12PhaseShift1Ch2 ""
            set PARRF12PhaseShift1Ch3 ""
            foreach {controlName valueString} $results {
                if {$controlName == "PAR:RF12:phaseShifter1Ch2"} {
                    set PARRF12PhaseShift1Ch2 $valueString
                } elseif {$controlName == "PAR:RF12:phaseShifter1Ch3"} {
                    set PARRF12PhaseShift1Ch3 $valueString
                }
            }
            }
            if {$alreadyOn != 1} {
#                APSMpStep "Set RF12 tuner phase setpoint to 0"
#                if {[catch {APScavput -list=PRF:H:FBM2:pidSpCh1AO=0} result]} {
#                    APSMpReturn error "Error writing feedback setpoints for rf12: $result"
#                }
                APSMpStep "Set RF12 tuner phase setpoint to -10.0"
                if {[catch {APScavput -list=PRF:H:FBM2:pidSpCh1AO=-10.0} result]} {
                    APSMpReturn error "Error writing feedback setpoints for rf12: $result"
                }
                APSMpStep "Set RF12 AGC to 0.1"
                if {[catch {APScavput -list=PRF:H:FBM1:pidSpCh0AO=0.1} result]} {
                    APSMpReturn error "Error writing feedback setpoints for rf12: $result"
                }
            }
            
            APSMpStep "Clicking Power Control On button"
            if {$selectedAmp == 1} {
                if {[catch {APScavget -list=PAR:Har:PowerOnStat -num} powerstate]} {
                    APSMpReturn error "Error getting the power control state: $powerstate"
                }
            } else {
                if {[catch {APScavget -list=PRF:H:SSA2:RF_CtlM -num} powerstate]} {
                    APSMpReturn error "Error getting the power control state: $powerstate"
                }
                set powerstate [expr !$powerstate]
            }
            for {set i 0} {$i <= 5} {incr i} {
                if {$powerstate == 0} {
                    break
                }
                if {$i == 1} {
                    if {$selectedAmp == 1} {
                        if {[catch {APScavput -list=PAR:Har:AmpFaultReset=1} result]} {
                            APSMpReturn error "Error resetting fault status."
                        }
                    } else {
                        if {[catch {APScavput -list=PRF:H:SSA2:FaultRstC=1} result]} {
                            APSMpReturn error "Error resetting fault status."
                        }
                        if {[catch {APScavput -list=PRF:H:CIR:FaultRstC=1} result]} {
                            APSMpReturn error "Error resetting fault status."
                        }
                        if {[catch {APScavput -list=PRF:H:CIR:FastRlyRstC=1} result]} {
                            APSMpReturn error "Error resetting fault status."
                        }
                        if {[catch {APScavput -list=PRF:H:CIR:FastIntlkRstC=1} result]} {
                            APSMpReturn error "Error resetting fault status."
                        }
                        if {[catch {APScavput -list=PRF:H:CIR:TunerPs1FaultRstC=1} result]} {
                            APSMpReturn error "Error resetting fault status."
                        }
                        if {[catch {APScavput -list=PRF:H:CIR:TunerPs2FaultRstC=1} result]} {
                            APSMpReturn error "Error resetting fault status."
                        }
                    }

                } elseif {$i == 3} {
                    if {[catch {APScavput -list=PAR:Har:RemoteStandBy=1} result]} {
                        APSMpReturn error "Error putting rf12 amplifier in standby mode."
                    }
                } elseif {$i == 5} {
                    if {[APSPEMTKDialog .warningDialog -text "Unable to turn on RF12 power control"] == 1} {
                        APSMpReturn error "Unable to turn on RF12 power control"
                    }
                }
                if {$i < 5} {
                    if {$selectedAmp == 1} {
                        if {[catch {APScavput -list=PAR:Har:RemotePwrOn=1} result]} {
                            APSMpReturn error "Error putting rf12 amplifier in standby mode."
                        }
                        APSWaitWithUpdate -waitSeconds 2
                        if {[catch {APScavget -list=PAR:Har:PowerOnStat -num} powerstate]} {
                            APSMpReturn error "Error getting the power control state: $powerstate"
                        }
                    } else {
                        if {[catch {APScavput -list=PAR:Har:RemotePwrOn=1} result]} {
                            APSMpReturn error "Error putting rf12 amplifier in standby mode."
                        }
                        APSWaitWithUpdate -waitSeconds 20
                        if {[catch {APScavput -list=PAR:Har:RemotePwrOn=1} result]} {
                            APSMpReturn error "Error putting rf12 amplifier in standby mode."
                        }
                        APSWaitWithUpdate -waitSeconds 20
                        if {[catch {APScavget -list=PRF:H:SSA2:RF_CtlM -num} powerstate]} {
                            APSMpReturn error "Error getting the power control state: $powerstate"
                        }
                        set powerstate [expr !$powerstate]
                    }
                }
            }
            
            if {[catch {exec sddsprocess $systemRefFile $tmpFile \
                          -match=column,IsReadOnly=+y,! \
                          -match=column,ValueString=,! -match=column,Beamline=PAR \
                          -match=column,Category=HarmonicRF \
                          -match=column,ControlName=PAR:RF12:PhsShft2Ch2_3AO,ControlName=PAR:RF12:phaseShifter1Ch0,|,ControlName=PRF:H:FBM2:pidSpCh1AO,|,ControlName=PRF:H:FBM1:pidSpCh0AO,|,ControlName=PRF:H:FBM1:pidSpCh1AO,|,! \
                      }  result]} {
                APSMpReturn error "Error preparing restore data: $result"
            }
            APSMpStep "Restoring RF12 SCR values"
            if {[catch {exec sddscasr -restore $tmpFile} result]} {
                catch {APSSendEMail -address soliday \
                         -subject "Problem restoring SCR file."  \
                         -message "Problem restore SCR file\nAPSMpPARTurnOnRfSystem\n$result"} 	    
            }

            #if {[catch {exec cavput -list=PAR:RF12:phaseShifter1Ch3=$PARRF12PhaseShift1Ch3} result]} {
            #    APSMpReturn error "Error setting PAR:RF12:phaseShifter1Ch3: $result"            
            #}

            APSMpStep "Loading RF12 trace memory waveforms"
            if {[catch {exec cavput -list=PRF:Har:WT2:StoreWF_BI.PROC=1} result]} {
                APSMpReturn error "Error creating waveform: $result"            
            }
            if {[catch {exec cavput -list=PRF:Har:WT2:LoadTraceBO.PROC=1} result]} {
                APSMpReturn error "Error loading trace mem waveform: $result"
            }
            if {[catch {exec cavput -list=PRF:Har:WT1:StoreWF_BI.PROC=1} result]} {
                APSMpReturn error "Error creating waveform: $result"            
            }
            if {[catch {exec cavput -list=PRF:Har:WT1:LoadTraceBO.PROC=1} result]} {
                APSMpReturn error "Error loading trace mem waveform: $result"
            }
                        
            APSMpStep "Setting cavity setpoint for RF12"
            if {[catch {APScavput -list=PRF:H:FBM1:pidSpCh1AO=$cavity} result]} {
                APSMpReturn error "Error setting cavity setpoint for RF${system}"
            }
            APSMpStep "Setting phase shifter for RF12"
            if {[catch {APScavput -list=PAR:RF12:PhsShft2Ch2_3AO=$phaseShifter} result]} {
                APSMpReturn error "Error setting phase shifter for RF${system}"
            }
            if {0} {
#                APSMpStep "Setting tuner RF12 phase setpoint to 0.8"
#                if {[catch {APScavput -list=PRF:H:FBM2:pidSpCh1AO=0.8} result]} {
#                    APSMpReturn error "Error setting tuner RF phase setpoint to 0.8"
#                }
            } else {
#                APSMpStep "Setting tuner RF12 phase setpoint to $tuner"
#                if {[catch {APScavput -list=PRF:H:FBM2:pidSpCh1AO=$tuner} result]} {
#                    APSMpReturn error "Error setting tuner RF phase setpoint to $tuner"
#                }
#                APSMpStep "Setting tuner RF12 phase setpoint to -10.0"
#                if {[catch {APScavput -list=PRF:H:FBM2:pidSpCh1AO=-10.0} result]} {
#                    APSMpReturn error "Error setting tuner RF phase setpoint to -10.0"
#                }
            }

            APSMpStep "Sending command to turn on RF12"
            if {[catch {APScavput -list=$onPV($system)=1} result]} {
                APSMpReturn error "Error sending command to turn on rf: $result"
            }

            APSMpStep "Ramping tuner phase setpoint for RF12"
            if {[catch {APScavget -list=PRF:H:FBM2:pidSpCh1AO} initTuner]} {
                set initTuner 0
            }
            if {[catch {APScaRamp -pvList PRF:H:FBM2:pidSpCh1AO -variableList tunerSetpoint$system \
                          -beginList $initTuner -endList $tuner -pause 3 -steps 11} result]} {
                APSMpReturn error "Error ramping tuner phase setpoint for RF${system} : $result"
            }

            for {set i 0} {$i <= 60} {incr i} {
                APSMpStep "Waiting for the RF12 tuner current to rise above 8 amps."
                if {[catch {APScavget -list=PRF:Har:PTM:AdcReg0AI -num} result]} {
                    APSMpReturn error "Error reading the RF12 tuner current readback."
                }
                if {$result > 8} {
                    break
                }
                if {$i == 10} {
                    APSMpReturn error "Error: The RF12 tuner current readback is not above 8 amps"
                }
                APSWaitWithUpdate -waitSeconds 1
            }
            
            APSMpStep "Ramping AGC setpoint for RF12"
            if {[catch {APScavget -list=PRF:H:FBM1:pidSpCh0AO} initAGC]} {
                set initAGC .1
            }
            if {$mode == "fast"} {
                if {[catch {APScaRamp -pvList "PRF:H:FBM1:pidSpCh0AO" \
                              -variableList "feedbackSetpoint$system" \
                              -beginList "$initAGC" -endList "$agc" \
                              -pause 2 -steps 11} result]} {
                    APSMpReturn error "Error ramping AGC setpoint for RF${system} : $result"
                }
            } else {
                if {[catch {APScaRamp -pvList "PRF:H:FBM1:pidSpCh0AO" \
                              -variableList "feedbackSetpoint$system" \
                              -beginList "$initAGC" -endList "$agc" \
                              -pause 5 -steps 11} result]} {
                    APSMpReturn error "Error ramping AGC setpoint for RF${system} : $result"
                }
            }
#### Ramping the tuner phase setpoint after the AGC ramp



        } else {
            if {[catch {APScavget -list=PAR:Fnd:SystemSelect} selectedAmp]} {
                APSMpReturn error "Error reading the selected rf1 amplifier"
            }
            if {{"SYSTEM #1"} == $selectedAmp} {
            } elseif {{"SYSTEM #2"} == $selectedAmp} {
            } else {
                APSMpReturn error "Error reading the selected rf1 amplifier: $selectedAmp"
            }
            
            if {[catch {exec sddsselect $systemRefFile /home/helios/oagData/pem/par/SCRFilterFile \
                          -match=ControlName -pipe=out | \
                          sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
                APSMpReturn error "APSMpPARTurnOnRfSystem4: Invalid SCR file"
            }
            foreach {controlName valueString} $results {
                if {$controlName == "PRF:F:FBM2:pidSpCh1AO"} {
                    set tuner $valueString
                } elseif {$controlName == "PRF:F:FBM1:pidSpCh0AO"} {
                    set agc $valueString
                } elseif {$controlName == "PRF:F:FBM1:pidSpCh1AO"} {
                    set cavity $valueString
                } elseif {$controlName == "PAR:LIST:PhsShft1Ch0_1"} {
                    set phaseShifter $valueString
                }
            }
            
            if {[catch {exec sddsselect $PLETSnapshotDir/$restoreFile /home/helios/oagData/pem/par/SCRFilterFile \
                          -match=ControlName -pipe=out | \
                          sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
                APSMpReturn error "APSMpPARTurnOnRfSystem5: Invalid SCR file"
            }
            set PARRF1PhaseShift1Ch2 ""
            set PARRF1PhaseShift1Ch3 ""
            foreach {controlName valueString} $results {
                if {$controlName == "PAR:RF1:phaseShifter1Ch2"} {
                    set PARRF1PhaseShift1Ch2 $valueString
                } elseif {$controlName == "PAR:RF1:phaseShifter1Ch3"} {
                    set PARRF1PhaseShift1Ch3 $valueString
                }
            }

            if {$alreadyOn != 1} {
                APSMpStep "Set RF1 tuner phase setpoint to -10"
                if {[catch {APScavput -list=PRF:F:FBM2:pidSpCh1AO=-10} result]} {
                    APSMpReturn error "Error writing feedback setpoints for rf1: $result"
                }
                APSMpStep "Set RF1 AGC to 0.1"
                if {[catch {APScavput -list=PRF:F:FBM1:pidSpCh0AO=0.1} result]} {
                    APSMpReturn error "Error writing feedback setpoints for rf1: $result"
                }
            }
            if {[catch {exec sddsprocess $systemRefFile $tmpFile \
                      -match=column,IsReadOnly=+y,! \
                          -match=column,ValueString=,! -match=column,Beamline=PAR \
                          -match=column,Category=FundamentalRF \
                          -match=column,ControlName=PRF:F:FBM1:pidSpCh0AO,ControlName=PRF:F:FBM2:pidSpCh1AO,|,ControlName=PRF:F:FBM1:pidSpCh1AO,|,ControlName=PAR:LIST:PhsShft1Ch0_1,|,ControlName=PAR:RF1:phaseShifter1Ch2,|,ControlName=PAR:RF1:phaseShifter1Ch3,|,ControlName=PAR:RF1:phaseShifter1Ch0,|,! \
                      } result]} {
                APSMpReturn error "Error preparing processing: $result"
            }
            
            APSMpStep "Restoring RF1 SCR values"
            if {[catch {exec sddscasr -restore $tmpFile} result]} {
                catch {APSSendEMail -address soliday \
                         -subject "Problem restoring SCR file."  \
                         -message "Problem restore SCR file\nAPSMpPARTurnOnRfSystem\n$result"} 	    
            }

            if {[catch {APScavput -list=PAR:RF1:phaseShifter1Ch3=$PARRF1PhaseShift1Ch3} result]} {
                APSMpReturn error "Error setting PAR:RF1:phaseShifter1Ch3: $result"
            }

            APSMpStep "Setting cavity setpoint for RF1"
            if {[catch {APScavput -list=PRF:F:FBM1:pidSpCh1AO=$cavity} result]} {
                APSMpReturn error "Error setting cavity setpoint for RF${system}"
            }
            APSMpStep "Setting LIST Phase Shifter 1 for RF1"
            if {[catch {APScavput -list=PAR:LIST:PhsShft1Ch0_1=$phaseShifter} result]} {
                APSMpReturn error "Error setting phase shifter for RF${system}"
            }
            APSWaitWithUpdate -waitSeconds 1
            APSMpStep "Checking state of RF1 interlock"
            if {[catch {APScavget -list=PAR:Fnd:InterlockOK -num} interlock]} {
                APSMpReturn error "Error checking state of RF interlock: $interlock"
            }
            APSMpStep "Checking state of RF1 filament"
            if {[catch {APScavget -list=PAR:Fnd:FilOn -num} filament]} {
                APSMpReturn error "Error checking state of RF filament: $filament"
            }
            APSMpStep "Checking state of RF1 plate"
            if {[catch {APScavget -list=PAR:Fnd:PlateOn -num} plate]} {
                APSMpReturn error "Error checking state of RF plate: $plate"
            }
            if {($interlock != 1) || ($filament != 1) || ($plate != 1)} {
                set alreadyOn 0
            }
            
            if {$alreadyOn != 1} {
                APSMpStep "Resetting the RF1 interlock"
                if {[catch {APScavput -list=PAR:Fnd:InterlockRESET=1} result]} {
                    APSMpReturn error "Error resetting the PRF1 interlock."
                }
                APSWaitWithUpdate -waitSeconds 1
                APSMpStep "Turning on the RF1 filament"
                if {[catch {APScavput -list=PAR:Fnd:FilamentON=1} result]} {
                    APSMpReturn error "Error turning on the PRF1 filament."
                }
                APSWaitWithUpdate -waitSeconds 1
                APSMpStep "Turning on the RF1 plate"
                if {[catch {APScavput -list=PAR:Fnd:PlateON=1} result]} {
                    APSMpReturn error "Error turning on the PRF1 plate."
                }
            }
            for {set i 0} {$i <= 60} {incr i} {
                APSMpStep "Waiting for the RF1 plate voltage to rise"
                if {[catch {APScavget -list=PAR:Fnd:PlateVoltLow -num} result]} {
                    APSMpReturn error "Error turning on the PRF1 plate."
                }
                if {$result == 0} {
                    break
                }
                if {$i == 60} {
                    APSMpReturn error "Error: the PRF1 plate voltage is low. (Amp may be locked out)"
                }
                APSWaitWithUpdate -waitSeconds 1
            }
            if {$ampSwitched} {
                APSMpStep "Setting AGC setpoint for RF1 to 0.1"
                if {[catch {APScavput -list=PRF:F:FBM1:pidSpCh0AO=0.1} result]} {
                    APSMpReturn error "Error setting AGC setpoint for RF${system}"
                }
            }

            if {$alreadyOn != 1} {
		APSMpStep "Ramping tuner phase setpoint for RF1"
		if {[catch {APScavget -list=PRF:F:FBM2:pidSpCh1AO} initTuner]} {
		    set initTuner 0
		}
		if {$mode == "fast"} {
		    if {[catch {APScaRamp -pvList PRF:F:FBM2:pidSpCh1AO -variableList tunerSetpoint$system \
				  -beginList $initTuner -endList 1.0 -pause 2 -steps 11} result]} {
			APSMpReturn error "Error ramping tuner phase setpoint for RF${system} : $result"
		    }
		} else {
		    if {[catch {APScaRamp -pvList PRF:F:FBM2:pidSpCh1AO -variableList tunerSetpoint$system \
				  -beginList $initTuner -endList 1.0 -pause 3 -steps 11} result]} {
			APSMpReturn error "Error ramping tuner phase setpoint for RF${system} : $result"
		    }
		}
		for {set i 0} {$i <= 60} {incr i} {
		    APSMpStep "Waiting for the RF1 tuner current to rise above 50 amps."
		    if {[catch {APScavget -list=PAR:RF1:tunerCurrentRb -num} result]} {
			APSMpReturn error "Error reading the RF1 tuner current readback."
		    }
		    if {$result > 50} {
			break
		    }
		    if {$i == 60} {
			APSMpReturn error "Error: The RF1 tuner current readback is not above 50 amps"
		    }
		    APSWaitWithUpdate -waitSeconds 1
		}
	    }
            if {0} {
                set PARRF1PhaseShiftOffset [expr {$PARRF1PhaseShift1Ch2 - 7}]
                APSMpStep "Setting tuner RF1 phase shifter to $PARRF1PhaseShiftOffset"
                if {[catch {APScavput -list=PAR:RF1:phaseShifter1Ch2=$PARRF1PhaseShiftOffset} result]} {
                    APSMpReturn error "Error setting tuner RF phase shifter to $PARRF1PhaseShiftOffset"
                }
            } else {
                APSMpStep "Setting tuner RF1 phase shifter to $PARRF1PhaseShift1Ch2"
                if {[catch {APScavput -list=PAR:RF1:phaseShifter1Ch2=$PARRF1PhaseShift1Ch2} result]} {
                    APSMpReturn error "Error setting tuner RF phase shifter to $PARRF1PhaseShift1Ch2"
                }
            }
            APSWaitWithUpdate -waitSeconds 1
            
            APSMpStep "Sending command to turn on RF1"
            if {[catch {APScavput -list=$onPV($system)=1} result]} {
                APSMpReturn error "Error sending command to turn on rf: $result"
            }
            if [catch {APScavget -list=PAR:RF1:tunerCurrentRb -num -printErrors} current0] {
                APSMpReturn error "Error reading tuner current: $current0"
            }
	    APSMpStep "Sending RF1 tuner phase setpoint to zero"
	    if {[catch {APScavput -list=PRF:F:FBM2:pidSpCh1AO=0} result]} {
		APSMpReturn error "Error sending RF1 tuner phase setpoint to zero"
	    }

            if {$alreadyOn != 1} {
                APSMpStep "Ramping AGC setpoint to -0.5"
                if {[catch {APScavget -list=PRF:F:FBM1:pidSpCh0AO} initAGC]} {
                    set initAGC .1
                }
                if {[catch {APScaRamp -pvList "PRF:F:FBM1:pidSpCh0AO" \
                              -variableList "feedbackSetpoint$system" \
                              -beginList "$initAGC" -endList "-.5" \
                              -pause 5 -steps 5} result]} {
                    APSMpReturn error "Error ramping AGC setpoint for RF${system} : $result"
                }
                
                APSMpStep "Wait for tuner current to drop more than 1Amp (current current is $current0 Amp)."
                for {set i 0} {$i <= 60} {incr i} {
                    if {[catch {APScavget -list=PAR:RF1:tunerCurrentRb -num} result]} {
                        APSMpReturn error "Error reading the RF1 tuner current readback: $result"
                    }
                    if {[expr $current0 - $result]>1} {
                        break
                    }
                    if {$i == 60} {
                        APSMpReturn error "Error: The RF1 tuner current readback does not drop within 60 seconds after setting tuner phase to 0"
                    }
                    APSWaitWithUpdate -waitSeconds 1
                }
                APSMpStep "Check reflect power (should be <150W)"
                for {set i 0} {$i <= 60} {incr i} {
                    if {[catch {APScavget -list=PAR:Fnd:RfPowerRefl -num} result]} {
                        APSMpReturn error "Error reading the PAR:Fnd:RfPowerRefl : $result  ."
                    }
                    if {$result<150} {
                        break
                    }
                    if {$i == 60} {
                        APSMpReturn error "Error: The RF1 reflect power could not drop after setting tuner phase setpoint to zero"
                    }
                    APSWaitWithUpdate -waitSeconds 1
                }
            }

            APSMpStep "Ramping AGC setpoint and tuner RF phase shifter for RF1"
            if {[catch {APScavget -list=PRF:F:FBM1:pidSpCh0AO} initAGC]} {
                set initAGC .1
            }
            if {$mode == "fast"} {
                if {[catch {APScaRamp -pvList "PRF:F:FBM1:pidSpCh0AO" \
                              -variableList "feedbackSetpoint$system" \
                              -beginList "$initAGC" -endList "$agc" \
                              -pause 2 -steps 11} result]} {
                    APSMpReturn error "Error ramping AGC setpoint for RF${system} : $result"
                }
            } else {
                if {[catch {APScaRamp -pvList "PRF:F:FBM1:pidSpCh0AO" \
                              -variableList "feedbackSetpoint$system" \
                              -beginList "$initAGC" -endList "$agc" \
                              -pause 5 -steps 11} result]} {
                    APSMpReturn error "Error ramping AGC setpoint for RF${system} : $result"
                }
            }
            #check for RF1 phase loop error
            APSMpStep "Check for phase loop error"
            if {[catch {APScavget -list=PRF:F:FBM1:pidErrCh1CC} phaseloopError]} {
                APSMpReturn error "Error checking RF1 phase loop error: $phaseloopError"
            }
            if {($phaseloopError > .1) || ($phaseloopError < -.1)} {
                APSMpStep "RF1 phase loop unlocked condition detected"

                APSMpStep "Disable PAR injection"
                if {[catch {APScavput -list=It:Ddg2chan4.GATE=0} result]} {
                    APSMpReturn error "Error disabling PAR injection: $result"
                }
                APSMpStep "Enable PAR extraction kickers"
                if {[catch {APScavput -list=It:ER1:er.OTL2=1} result]} {
                    APSMpReturn error "Error enabling PAR extraction kickers: $result"
                }
                APSWaitWithUpdate -waitSeconds 5
                APSMpStep "Disable PAR extraction kickers"
                if {[catch {APScavput -list=It:ER1:er.OTL2=0} result]} {
                    APSMpReturn error "Error disabling PAR extraction kickers: $result"
                }
                APSMpStep "Set PAR:RF1:phaseShifter1Ch3 to zero"
                if {[catch {APScavput -list=PAR:RF1:phaseShifter1Ch3=0} result]} {
                    APSMpReturn error "Error setting PAR:RF1:phaseShifter1Ch3: $result"
                }
                APSMpStep "Set PAR:RF1:phaseShifter1Ch3 to $PARRF1PhaseShift1Ch3"
                if {[catch {APScavput -list=PAR:RF1:phaseShifter1Ch3=$PARRF1PhaseShift1Ch3} result]} {
                    APSMpReturn error "Error setting PAR:RF1:phaseShifter1Ch3: $result"
                }
                APSMpStep "Zeroing RF1 phase loop error"
                if {[catch {APScavget -list=PAR:RF1:phaseDet1Ch0V} phaseloop]} {
                    APSMpReturn error "Error attempting to lock RF1 phase loop: $phaseloop"
                }
                set phaseloop [expr {$phaseloop * -1}]
                if {[catch {APScavput -list=PRF:F:FBM1:pidSpCh1AO=$phaseloop} result]} {
                    APSMpReturn error "Error attempting to lock RF1 phase loop: $result"
                }
                APSWaitWithUpdate -waitSeconds 5
                if {[catch {APScavget -list=PRF:F:FBM1:pidErrCh1CC} phaseloopError]} {
                    APSMpReturn error "Error checking RF1 phase loop error: $phaseloopError"
                }
                if {($phaseloopError > .1) || ($phaseloopError < -.1)} {
                    if {[catch {APScavput -list=PRF:F:FBM1:pidSpCh1AO=0} result]} {
                        APSMpReturn error "Error attempting to lock RF1 phase loop: $result"
                    }
                    if {[APSPEMTKDialog .warningDialog -text "Unable to lock the RF1 phase loop error. The tuner value has been reset to 0. You will have to fix this by hand. The PEM will exit normally now."] == 1} {
                        APSMpReturn error "Unable to lock the RF1 phase loop error. The tuner value has been reset to 0. You will have to fix this by hand."
                    }
                    APSMpReturn ok
                }
                for {set step 1} {$step <= 4} {incr step} {
                    APSMpStep "Ramping RF1 phase loop setpoint to -1 (step $step of 5)"
                    set value [expr {$phaseloop + ($step * (-1.0 - $phaseloop) / 5.0)}]
                    if {[catch {APScavput -list=PRF:F:FBM1:pidSpCh1AO=$value} result]} {
                        APSMpReturn error "Error attempting to lock RF1 phase loop: $result"
                    }
                    APSWaitWithUpdate -waitSeconds 5
                    if {[catch {APScavget -list=PRF:F:FBM1:pidErrCh1CC} phaseloopError]} {
                        APSMpReturn error "Error checking RF1 phase loop error: $phaseloopError"
                    }
                    if {($phaseloopError > .1) || ($phaseloopError < -.1)} {
                        if {[catch {APScavput -list=PRF:F:FBM1:pidSpCh1AO=0} result]} {
                            APSMpReturn error "Error attempting to lock RF1 phase loop: $result"
                        }
                        if {[APSPEMTKDialog .warningDialog -text "Unable to lock the RF1 phase loop error. The tuner value has been reset to 0. You will have to fix this by hand. The PEM will exit normally now."] == 1} {
                            APSMpReturn error "Unable to lock the RF1 phase loop error. The tuner value has been reset to 0. You will have to fix this by hand."
                        }
                        APSMpReturn ok
                    }
                }
                APSMpStep "Ramping RF1 phase loop setpoint to -1 (step 5 of 5)"
                if {[catch {APScavput -list=PRF:F:FBM1:pidSpCh1AO=-1.0} result]} {
                    APSMpReturn error "Error attempting to lock RF1 phase loop: $result"
                }
                APSWaitWithUpdate -waitSeconds 5
                if {[catch {APScavget -list=PRF:F:FBM1:pidErrCh1CC} phaseloopError]} {
                    APSMpReturn error "Error checking RF1 phase loop error: $phaseloopError"
                }
                if {($phaseloopError > .1) || ($phaseloopError < -.1)} {
                    if {[catch {APScavput -list=PRF:F:FBM1:pidSpCh1AO=0} result]} {
                        APSMpReturn error "Error attempting to lock RF1 phase loop: $result"
                    }
                    if {[APSPEMTKDialog .warningDialog -text "Unable to lock the RF1 phase loop error. The tuner value has been reset to 0. You will have to fix this by hand. The PEM will exit normally now."] == 1} {
                        APSMpReturn error "Unable to lock the RF1 phase loop error. The tuner value has been reset to 0. You will have to fix this by hand."
                    }
                    APSMpReturn ok
                }
            }
            
            APSMpStep "Resetting Arc Detectors"
            if {[catch {APScavput -list=PAR:Fnd:ArcDetect1RstC=1} result]} {
                APSMpReturn error "Error reseting arc detectors: $result"
            }
            if {[catch {APScavput -list=PAR:Fnd:ArcDetect2RstC=1} result]} {
                APSMpReturn error "Error reseting arc detectors: $result"
            }
        }

        if {[catch {APScavget -list=$onPV($system)} result]} {
            APSMpReturn error "Error checking if RF$system tripped: $result"
        }
        if {$result != "On"} {
            if {$mode == "fast"} {
		APSMpStep "PAR RF $system tripped, trying again in slow mode."
                set mode "slow"
                continue
            } else {
                APSMpReturn error "RF$system tripped off (Amp may be locked out)"
            }
        }

        APSMpReturn ok
    }
}

proc APSSearchAssociateListForValue {args} {
    
    APSStrictParseArguments {value list notvalue}
    if {[info exists value]} {
        set match {}
        set i 0
        set n [llength $list]
        while {$i != $n} {
            foreach item $value {
                if {$item == [lindex $list [expr $i + 1]]} {
                    lappend match [lindex $list $i]
                    break
                }
            }
            incr i 2
        }
        return $match
    }
    if {[info exists notvalue]} {
        set match {}
        set i 0
        set n [llength $list]
        while {$i != $n} {
            set include 1
            foreach item $notvalue {
                if {$item == [lindex $list [expr $i + 1]]} {
                    set include 0
                    break
                }
            }
            if {$include} {
                lappend match [lindex $list $i]
            }
            incr i 2
        }
        return $match
    }

}


proc APSMpPARClearAperture {args} {
    set retries 5
    APSStrictParseArguments {retries}
    APSMpStep init -promptDialog "APSMpPromptInitDialog"
    if {[catch {APSMpPARLETClearAperture -beamline PAR -retries $retries} result]} {
        APSMpReturn error "Unable to clear PAR aperture"
    }
    APSMpReturn ok
}

proc APSMpPARTuneRfCavityInfo {} {
    return "Tunes either the fundamental or harmonic to minimize RMS reflected power.  Does this by adjusting the tuner phase set point."
}

proc APSMpPARTuneRfCavity {args} {
    set system 1
    set settlingTime 2
    set averages 5
    set threshold 50 
    set stepSize 0.2
    APSStrictParseArguments {system settlingTime averages threshold stepSize}

    APSMpStep init -promptDialog APSMpPARTuneRfCavityInitDialog \
      -vars {system settlingTime averages threshold stepSize}

    set paramString ""
    foreach param {system settlingTime averages threshold stepSize} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure APSMpPARTuneRfCavity \
             -action initialize -state ok -parameters $paramString}

    if {$system == "1"} {
        set rv [APScavget -list=PAR:Fnd:RfPowerRefl]
	set initTunerPhase [APScavget -list=PRF:F:FBM2:pidSpCh1AO]
    } else {
        set rv [APScavget -list=PAR:Har:RfPowerRefl]
	set initTunerPhase [APScavget -list=PRF:H:FBM2:pidSpCh1AO]
    }
    if {$rv > 250} {
        if {[catch {exec squishPVs /home/helios/oagData/pem/par/rf${system}.squish \
                      -settlingTime=$settlingTime \
                      -averages=$averages,.3 \
                      -threshold=$threshold \
                      -pend=30 \
                      -criterion=rms -stepSize=$stepSize -subdivisions=2,2} result]} {
            APSMpReturn error "APSMpPARTuneRfCavity: $result\nOptions: -settlingTime=$settlingTime -averages=$averages -threshold=$threshold -stepSize=$stepSize"
        }
    }
    if {$system == "1"} {
        set rv [APScavget -list=PAR:Fnd:RfPowerRefl]
        if {$rv > 300} {
            APScavput -list=PRF:F:FBM1:pidSpCh0AO=.1
            APSMpReturn error "APSMpPARTuneRfCavity: Could not reduce PRF1 reflected power below 300W"
        }
    } else {
        set rv [APScavget -list=PAR:Har:RfPowerRefl]
        if {$rv > 300} {
            APScavput -list=PRF:H:FBM1:pidSpCh0AO=.1
            APSMpReturn error "APSMpPARTuneRfCavity: Could not reduce PRF12 reflected power below 300W"
        }
    }

    if {$system == "1"} {
	set postSquishTunerPhase [APScavget -list=PRF:H:FBM2:pidSpCh1AO]
	if {[catch {APScaRamp -pvList PRF:F:FBM2:pidSpCh1AO -variableList tunerSetpoint$system \
		      -beginList $postSquishTunerPhase -endList $initTunerPhase -pause 1 -steps 11} result]} {
	    APSMpReturn error "Error ramping tuner phase setpoint for RF${system} : $result"
	}
    } else {
	set postSquishTunerPhase [APScavget -list=PRF:H:FBM2:pidSpCh1AO]
	if {[catch {APScaRamp -pvList PRF:H:FBM2:pidSpCh1AO -variableList tunerSetpoint$system \
		      -beginList $postSquishTunerPhase -endList $initTunerPhase -pause 1 -steps 11} result]} {
	    APSMpReturn error "Error ramping tuner phase setpoint for RF${system} : $result"
	}
    }

    APSMpStep "Finished tuning PRF$system"
    APSMpReturn ok
}

proc APSMpPARTuneRfCavityInitDialog {frame} {
    global APSMpPARTuneRfCavity
    APSRadioButtonFrame .rb1 -parent $frame \
      -label "Cavity to tune: " -variable APSMpPARTuneRfCavity(system) \
      -buttonList {Fundamental Harmonic} -valueList {1 12} -contextHelp \
      "Choose whether to tune the fundamental or harmonic cavity."

    APSLabeledEntry .le1 -parent $frame \
      -label "Settling time (s): " -textVariable APSMpPARTuneRfCavity(settlingTime) \
      -contextHelp \
      "Enter the time to wait after making a change to allow the readbacks to settle."

    APSLabeledEntry .le2 -parent $frame \
      -label "Averages: " -textVariable APSMpPARTuneRfCavity(averages) \
      -contextHelp \
      "Enter the number of readbacks to average in order to get a value to use in tuning."

    APSLabeledEntry .le3 -parent $frame \
      -label "Threshold (W): " -textVariable APSMpPARTuneRfCavity(threshold) \
      -contextHelp \
      "Enter the threshold for the power change that is recognized as significant."

    APSLabeledEntry .le4 -parent $frame \
      -label "Step size (V): " -textVariable APSMpPARTuneRfCavity(stepSize) \
      -contextHelp \
      "Enter the step size for tuner phase setpoint changes."

}






