proc APSMpSRTurnOnKickersDialog {frame} {
    global status APSMpSRTurnOnKickers
    APSCheckButtonFrame .ikButtons \
      -parent $frame \
      -label "Select SR/Booster Kickers" \
      -variableList {APSMpSRTurnOnKickers(IK1) \
                       APSMpSRTurnOnKickers(IK2) \
                       APSMpSRTurnOnKickers(IK3) \
                       APSMpSRTurnOnKickers(DK0) \
                       APSMpSRTurnOnKickers(FOK1) \
                       APSMpSRTurnOnKickers(EK)} \
      -buttonList "S39-IES:IK1 S39-IES:IK2 S39-IES:IK3 S38-IES:DK0 {S36C:FOK1  } {B:EK       }" \
      -allNone 1
    APSCheckButtonFrame .isButtons \
      -parent $frame \
      -label "Select SR/Booster Septums" \
      -variableList {APSMpSRTurnOnKickers(IS1) \
                       APSMpSRTurnOnKickers(ES1) \
                       APSMpSRTurnOnKickers(ES2)} \
      -buttonList "S39-IES:IS1 {B:ES1      } {B:ES2      }" \
      -allNone 1
    APSCheckButtonFrame .scrRestore \
      -parent $frame \
      -label "Restore IES Voltages" \
      -variableList {APSMpSRTurnOnKickers(restore)} \
      -buttonList {"Restore from User Beam\nOperator Preferred SCR file"} \
      -allNone 0
    return 
}


proc APSMpSRTurnOnKickers {args} {
    set IK1 1
    set IK2 1
    set IK3 1
    set DK0 1
    set EK  0
    set IS1 1
    set ES1 0
    set ES2 0
    set FOK1 1
    set restore 0
    set SCRFile SR-UserBeamPreferred.gz
    APSStrictParseArguments {IK1 IK2 IK3 DK0 EK IS1 ES1 ES2 FOK1 restore SCRFile}
    APSMpStep init -promptDialog APSMpSRTurnOnKickersDialog \
      -vars "IK1 IK2 IK3 DK0 EK IS1 ES1 ES2 FOK1 restore"

    if {$restore} {
        if {[catch {exec sddsprocess /home/helios/oagData/SCR/snapshots/SR/$SCRFile -pipe=out "-match=column,ControlName=S38-IES:DK0:PS:VoltageC,ControlName=S39-IES:IK1:PS:VoltageC,|,ControlName=S39-IES:IK2:PS:VoltageC,|,ControlName=S39-IES:IK3:PS:VoltageC,|,ControlName=S39-IES:IS1:SetRefVoltageC,|,ControlName=S36C:FOK1:PS:SetVoltageC,|" | sdds2stream -pipe=in -col=ControlName,ValueString} results]} {
            APSMpReturn error "APSMpSRTurnOnKickers: $results"
        }
        foreach "pv value" $results {
            set voltage($pv) $value
        }
    }

    if {$EK || $ES1 || $ES2} {
        set btsPulsed [APSMpParallel -procedure "APSMpBPSTurnOnPulsedSupplies -IS 0 -IK 0 -EK $EK -ES1 $ES1 -ES2 $ES2 -doRestore 0" -mode "Semi-Automatic"]
        if {[catch {APSMpJoin $btsPulsed} status]} {
            APSMpReturn error "APSMpSRTurnOnKickers: $status"
        }
    }


    if {[catch {APSGetMagnetPVNamesAndInfo -arrayName magnetPVs} results]} {
        APSMpReturn error  "APSMpSRTurnOnKickers: $results"
    }
    set IKList ""
    set ISList ""
    set FOKList ""
    foreach val "FOK1" magnet "S36C:FOK1" {
        if [set $val] {
            lappend FOKList $magnet
        }
    }
    foreach val "IK1 IK2 IK3 DK0" magnet "S39-IES:IK1 S39-IES:IK2 S39-IES:IK3 S38-IES:DK0" {
        if [set $val] {
            lappend IKList $magnet
            lappend IKStatusPVs $magnetPVs(${magnet}.statusPV)
            lappend IKStatusOnValues $magnetPVs(${magnet}.statusOnValue)
            lappend IKStatus2PVs ${magnet}:PS:StatusM
            lappend IKStatusPosOutPVs ${magnet}:PS:EnablePosOutM
            lappend IKStatusNegOutPVs ${magnet}:PS:EnableNegOutM
        }
    }
    foreach val "IS1" magnet "S39-IES:IS1" {
        if [set $val] {
            lappend ISList $magnet
            lappend ISStatusPVs $magnetPVs(${magnet}.statusPV)
            lappend ISStatusOnValues $magnetPVs(${magnet}.statusOnValue)
        }
    }
    if {(![llength $IKList]) && (![llength $ISList]) && (![llength $FOKList])} {
        APSMpReturn ok
    }

    if {[llength $FOKList]} {
        APSMpStep "SR: Resetting S36C:FOK1"
        if {[catch {APScavput -list=S36C:FOK1:PS:ResetSupplyC.PROC=1 -pend=5} results]} {
            APSMpReturn error "Problem resetting S36C:FOK1"
        }
        set 15min [expr [clock seconds] + (60 * 15) + 1]
    }
    
    if {[llength $ISList]} {
        
        
        set isResetList ""
        foreach is $ISList {
            if {[catch {APScavget -num -printErrors -list=${is}:FaultsM} fault]} {
                APSMpReturn error "Problem reading septum status PVs"
            }
            if {$fault != 0} {
                APSMpStep "SR: Resetting $is"
                lappend isResetList $is
                catch {APScavput -list=$magnetPVs(${is}.resetPV)=$magnetPVs(${is}.resetValue)}
            }
        }
        if {[llength $isResetList]} {
            APSWaitWithUpdate -waitSeconds 30
        }

        APSMpStep "SR: Turn on Septums"
        set retries 10
        while {$retries} {
            incr retries -1
            if {[catch {APScavget -num -printErrors -list=[join $ISStatusPVs ,]} statusList]} {
                APSMpReturn error "Problem reading septum status PVs"
            }
            set pass 1
            foreach is $ISList status $statusList onValue $ISStatusOnValues {
                if {$status == $onValue} {
                    continue
                }
                set pass 0
                if {[catch {APScavput -list=$magnetPVs(${is}.turnOnPV)=$magnetPVs(${is}.turnOnValue)} result]} {
                    APSMpReturn error "Error sending on signal to $is septum: $result"
                }
            }
            if {!$pass} {
                if {$retries == 0} {
                    if {[APSPEMTKDialog .warningDialog -text "Unknown problem turning on septums.\nYou may attempt to turn it on by hand and then click continue."] == 1} {
                        APSMpReturn error "Unknown problem turning on septum."
                    }
                    set retries 1
                } else {
                    APSMpStep "SR: Wait 40 seconds for septums to warmup"
                    APSWaitWithUpdate -waitSeconds 35
                }
            } else {
                break
            }
        }
        APSMpStep "SR: Turn on $is septum succeeded"
    }
    if {[llength $IKList]} {
        APSMpStep "SR: Turn On Kickers"
        if {[catch {APScavget -num -printErrors -list=[join $IKStatusPVs ,]} statusList]} {
            APSMpReturn error "Problem reading kicker status PVs"
        }
        if {[catch {APScavget -num -printErrors -list=[join $IKStatus2PVs ,]} status2List]} {
            APSMpReturn error "Problem reading kicker status PVs"
        }
        if {[catch {APScavget -num -printErrors -list=[join $IKStatusPosOutPVs ,]} posOutList]} {
            APSMpReturn error "Problem reading kicker Pos Out PVs"
        }
        if {[catch {APScavget -num -printErrors -list=[join $IKStatusNegOutPVs ,]} negOutList]} {
            APSMpReturn error "Problem reading kicker Neg Out PVs"
        }
        foreach ik $IKList status $statusList onValue $IKStatusOnValues status2 $status2List posOut $posOutList negOut $negOutList {
            if {($status == $onValue) && ($status2 == 0) && ($posOut == 1) && ($negOut == 1)} {
                continue
            }
            if {[catch {APScavput -list=$magnetPVs(${ik}.turnOffPV)=$magnetPVs(${ik}.turnOffValue)} result]} {
                APSMpReturn error "APSMpSRTurnOnKickers: $result"
            }
            if {[catch {APScavput -list=$magnetPVs(${ik}.setVoltagePV)=5000} result]} {
                APSMpReturn error "APSMpSRTurnOnKickers: $result"
            }
            APSWaitWithUpdate -waitSeconds 30
            if {[catch {APScavput -list=${ik}:PS:EnablePosOutC=1,${ik}:PS:EnableNegOutC=1} result]} {
                APSMpReturn error "APSMpSRTurnOnKickers: $result"
            }
            if {[catch {APScavput -list=$magnetPVs(${ik}.turnOnPV)=$magnetPVs(${ik}.turnOnValue)} result]} {
                APSMpReturn error "APSMpSRTurnOnKickers: $result"
            }
            after 5000
        }
        if {[catch {APScavget -num -printErrors -list=[join $IKStatusPVs ,]} statusList]} {
            APSMpReturn error "Problem reading kicker status PVs"
        }
        if {[catch {APScavget -num -printErrors -list=[join $IKStatus2PVs ,]} status2List]} {
            APSMpReturn error "Problem reading kicker status PVs"
        }
        if {[catch {APScavget -num -printErrors -list=[join $IKStatusPosOutPVs ,]} posOutList]} {
            APSMpReturn error "Problem reading kicker Pos Out PVs"
        }
        if {[catch {APScavget -num -printErrors -list=[join $IKStatusNegOutPVs ,]} negOutList]} {
            APSMpReturn error "Problem reading kicker Neg Out PVs"
        }
        foreach ik $IKList status $statusList onValue $IKStatusOnValues status2 $status2List posOut $posOutList negOut $negOutList {
            if {($status == $onValue) && ($status2 == 0) && ($posOut == 1) && ($negOut == 1)} {
                continue
            }
            APSMpReturn error "Unable to reset kicker $ik"
        }
    }
    if {$restore} {
        set values ""
        set pause 1

        if {$IS1} {
            if {[catch {APScavput -list=S-INJ:IS1:EnableRequestC=1} result]} { 
                APSMpReturn error "APSMpSRTurnOnKickers: $result"
            }
        }
        if {$IS1 && [info exists voltage(S39-IES:IS1:SetRefVoltageC)]} {
            lappend values S39-IES:IS1:SetRefVoltageC=$voltage(S39-IES:IS1:SetRefVoltageC)
            set pause 10
        }
        if {$DK0 && [info exists voltage(S38-IES:DK0:PS:VoltageC)]} {
            lappend values S38-IES:DK0:PS:VoltageC=$voltage(S38-IES:DK0:PS:VoltageC)
        }
        if {$IK1 && [info exists voltage(S39-IES:IK1:PS:VoltageC)]} {
            lappend values S39-IES:IK1:PS:VoltageC=$voltage(S39-IES:IK1:PS:VoltageC)
        }
        if {$IK2 && [info exists voltage(S39-IES:IK2:PS:VoltageC)]} {
            lappend values S39-IES:IK2:PS:VoltageC=$voltage(S39-IES:IK2:PS:VoltageC)
        }
        if {$IK3 && [info exists voltage(S39-IES:IK3:PS:VoltageC)]} {
            lappend values S39-IES:IK3:PS:VoltageC=$voltage(S39-IES:IK3:PS:VoltageC)
        }
        if {[llength $values]} {
            if {[catch {APScavput -list=[join $values ,] -ramp=step=10,pause=${pause}} result]} {
                APSMpReturn error "APSMpSRTurnOnKickers: $result"
            }
        }
        if {$IS1} {
            set value [expr $voltage(S39-IES:IS1:SetRefVoltageC) - 10]
            if {[catch {exec cawait -waitFor=S39-IES:IS1:MeasVoltageM,above=$value -timeLimit=60} result]} {
                APSMpReturn error "APSMpSRTurnOnKickers: S39-IES:IS1 voltage readback is not reaching setpoint"
            }
            if {[catch {APScavput -list=S-INJ:IS1:EnableRequestC=0} result]} { 
                APSMpReturn error "APSMpSRTurnOnKickers: $result"
            }
        }
    }
    if {[llength $FOKList]} {
        
        while {[clock seconds] < $15min} {
            APSMpStep "SR: Waiting for S36C:FOK1 15 timer to complete"
            set sec [expr $15min - [clock seconds]]
            if {$sec > 60} {
                set sec 60
            }
            if {[catch {exec cawait -waitFor=S36C:FOK1:PS:ThyWarmupCounterM,equalTo=0 -timeLimit=60} result]} {
                continue
            }
            break
        }
        if {[catch {exec cawait -waitFor=S36C:FOK1:PS:ThyWarmupCounterM,equalTo=0 -timeLimit=1} result]} {
            APSMpReturn error "APSMpSRTurnOnKickers: S36C:FOK1:PS:ThyWarmupCounterM never went to 0"
        }
        after 1000
        if {[catch {APScavput -list=S36C:FOK1:PS:ResetSupplyC.PROC=1 -pend=5} results]} {
            APSMpReturn error "Problem resetting S36C:FOK1"
        }
        after 5000
        if {[catch {APScavget -list=S36C:FOK1:PS:FaultsM} results]} {
            APSMpReturn error "Unable to read S36C:FOK1 fault PVs"
        }
        foreach value $results {
            if {$value != "No Fault"} {
                APSMpReturn error "Cannot turn on S36C:FOK1, fault detected"
            }
        }
        if {[catch {APScavput -list=S36C:FOK1:PS:SupplyOnOffC=1 -pend=5} result]} {
            APSMpReturn error "Problem turning on S36C:FOK1"
        }
        after 5000
        if {[info exists voltage(S36C:FOK1:PS:SetVoltageC)]} {
            if {[catch {APScavput -list=S36C:FOK1:PS:SetVoltageC=$voltage(S36C:FOK1:PS:SetVoltageC) -pend=5} result]} {
                APSMpReturn error "APSMpSRTurnOnKickers: $result"
            }
        }
    }

    APSMpReturn ok
}

proc APSMpSRTurnOffKickersDialog {frame} {
    global status APSMpSRTurnOffKickers
    APSCheckButtonFrame .ikButtons \
      -parent $frame \
      -label "Select SR/Booster Kickers" \
      -variableList {APSMpSRTurnOffKickers(IK1) \
                       APSMpSRTurnOffKickers(IK2) \
                       APSMpSRTurnOffKickers(IK3) \
                       APSMpSRTurnOffKickers(DK0) \
                       APSMpSRTurnOffKickers(FOK1) \
                       APSMpSRTurnOffKickers(EK)} \
      -buttonList "S39-IES:IK1 S39-IES:IK2 S39-IES:IK3 S38-IES:DK0 {S36C:FOK1  } {B:EK       }" \
      -allNone 1
    APSCheckButtonFrame .isButtons \
      -parent $frame \
      -label "Select SR/Booster Septums" \
      -variableList {APSMpSRTurnOffKickers(IS1) \
                       APSMpSRTurnOffKickers(ES1) \
                       APSMpSRTurnOffKickers(ES2)} \
      -buttonList "S39-IES:IS1 {B:ES1      } {B:ES2      }" \
      -allNone 1
    return 
}

proc APSMpSRTurnOffKickers {args} {
    set IK1 1
    set IK2 1
    set IK3 1
    set DK0 1
    set EK  0
    set IS1 1
    set ES1 0
    set ES2 0
    set FOK1 1
    APSStrictParseArguments {IK1 IK2 IK3 DK0 EK IS1 ES1 ES2 FOK1}
    APSMpStep init -promptDialog APSMpSRTurnOffKickersDialog \
      -vars "IK1 IK2 IK3 DK0 EK IS1 ES1 ES2 FOK1"

    if {$EK || $ES1 || $ES2} {
        #This should be launched in parallel
        if {[catch {APSMpBPSTurnOffPulsedSupplies -IS 0 -IK 0 -EK $EK -ES1 $ES1 -ES2 $ES2} results]} {
            APSMpReturn error  "APSMpSRTurnOffKickers: $results"
        }
    }

    if {[catch {APSGetMagnetPVNamesAndInfo -arrayName magnetPVs} results]} {
        APSMpReturn error  "APSMpSRTurnOffKickers: $results"
    }
    set magnetList ""
    set magnetReadVoltagePVs ""
    set magnetOffValue ""
    foreach val "IK1 IK2 IK3 DK0 IS1 FOK1" \
      magnet "S39-IES:IK1 S39-IES:IK2 S39-IES:IK3 S38-IES:DK0 S39-IES:IS1 S36C:FOK1" \
      offValue "5000 5000 5000 5000 0 0" {
        if [set $val] {
            lappend magnetList $magnet
            lappend magnetReadVoltagePVs $magnetPVs(${magnet}.readVoltagePV)
            lappend magnetOffValue $offValue
        }
    }
    if {![llength $magnetList]} {
        APSMpReturn ok
    }
    if {$IS1} {
        if {[catch {APScavput -list=S-INJ:IS1:EnableRequestC=1} result]} { 
            APSMpReturn error "APSMpSRTurnOffKickers: $result"
        }
    }

    APSMpStep "SR: Set selected Kicker and Septum setpoints to 5000"
    set values ""
    foreach magnet $magnetList value $magnetOffValue {
        lappend values $magnetPVs(${magnet}.setVoltagePV)=$value
    }
    if {[llength $values]} {
        if [catch {APScavput -list=[join $values ,] -ramp=step=10,pause=1} result] { 
            APSMpReturn error "APSMpSRTurnOffKickers: $result"
        }
    }
    
    APSMpStep "SR: Wait up to 60 seconds for selected Kickers and Septums readbacks to reach 5000"
    set i 0
    while {$i < 60} {
        incr i
        APSWaitWithUpdate -waitSeconds 1
        if {[catch {APScavget -printErrors -list=[join $magnetReadVoltagePVs ,]} result]} {
            APSMpStep "SR: Problem reading kicker and/or septum readbacks: Trying again"
        } else {
            set pass 1
            foreach rb $result value $magnetOffValue {
                if {$rb > [expr $value + 1]} {
                    set pass 0
                }
            }
            if {$pass} { break }
        }	
    }
    
    if {$IS1} {
        if {[catch {APScavput -list=S-INJ:IS1:EnableRequestC=0} result]} { 
            APSMpReturn error "APSMpSRTurnOffKickers: $result"
        }
    }

    APSMpStep "SR: Turn Off selected Kickers and Septums"
    foreach magnet $magnetList {
        if [catch {APScavput -list=$magnetPVs(${magnet}.turnOffPV)=$magnetPVs(${magnet}.turnOffValue)} result] { 
            APSMpReturn error "APSMpSRTurnOffKickers: $result"
        }
    }

    APSMpReturn ok
}

