
proc APSMpSRUpDoubleSectorInfo {} {
    return "Brings two consecutive SR sectors up by turning the converters and corresponding raw supplies on and loading the appropriate set points after conditioning the power supplies."
}

proc APSMpSRUpDoubleSectorDialog {frame} {
    global status APSMpSRUpDoubleSector

    set status "Select SR Sectors"
    pack [frame $frame.f2]
    pack [frame $frame.f2.f1] -side left -fill y
    pack [frame $frame.f2.f2] -side left
    #    pack [frame $frame.f2.f3] -side left
    pack [label $frame.f2.f1.sectorSelectLabel -text "Storage Ring Sector Selection"]
    APSCheckButtonFrame .sectorSelectButtons \
        -parent $frame.f2.f1 \
        -label "" \
        -variableList {APSMpSRUpDoubleSector(S40:01) APSMpSRUpDoubleSector(S02:03) \
                           APSMpSRUpDoubleSector(S04:05) APSMpSRUpDoubleSector(S06:07) \
                           APSMpSRUpDoubleSector(S08:09) APSMpSRUpDoubleSector(S10:11) \
                           APSMpSRUpDoubleSector(S12:13) APSMpSRUpDoubleSector(S14:15) \
                           APSMpSRUpDoubleSector(S16:17) APSMpSRUpDoubleSector(S18:19) \
                           APSMpSRUpDoubleSector(S20:21) APSMpSRUpDoubleSector(S22:23) \
                           APSMpSRUpDoubleSector(S24:25) APSMpSRUpDoubleSector(S26:27) \
                           APSMpSRUpDoubleSector(S28:29) APSMpSRUpDoubleSector(S30:31) \
                           APSMpSRUpDoubleSector(S32:33) APSMpSRUpDoubleSector(S34:35) \
                           APSMpSRUpDoubleSector(S36:37) APSMpSRUpDoubleSector(S38:39)} \
        -buttonList {S40:01 S02:03 S04:05 S06:07 S08:09 S10:11 S12:13 \
                         S14:15 S16:17 S18:19 S20:21 S22:23 S24:25 S26:27 \
                         S28:29 S30:31 S32:33 S34:35 S36:37 S38:39} \
        -allNone 1 \
        -orientation horizontal \
        -limitPerRow 4
    APSButton .a -parent $frame.f2.f1.sectorSelectButtons.frame -text A -size small -command "$frame.f2.f1.sectorSelectButtons.frame.none.button invoke; for {set i 2} {\$i <= 8} {incr i} {set APSMpSRUpDoubleSector(S0\$i:0\[expr \$i + 1\]) 1} ; set APSMpSRUpDoubleSector(kickers) 0"
    APSButton .b -parent $frame.f2.f1.sectorSelectButtons.frame -text B -size small -command "$frame.f2.f1.sectorSelectButtons.frame.none.button invoke; for {set i 10} {\$i <= 16} {incr i} {set APSMpSRUpDoubleSector(S\$i:\[expr \$i + 1\]) 1} ; set APSMpSRUpDoubleSector(kickers) 0"
    APSButton .c -parent $frame.f2.f1.sectorSelectButtons.frame -text C -size small -command "$frame.f2.f1.sectorSelectButtons.frame.none.button invoke; for {set i 18} {\$i <= 22} {incr i} {set APSMpSRUpDoubleSector(S\$i:\[expr \$i + 1\]) 1} ; set APSMpSRUpDoubleSector(kickers) 0"
    APSButton .d -parent $frame.f2.f1.sectorSelectButtons.frame -text D -size small -command "$frame.f2.f1.sectorSelectButtons.frame.none.button invoke; for {set i 24} {\$i <= 28} {incr i} {set APSMpSRUpDoubleSector(S\$i:\[expr \$i + 1\]) 1} ; set APSMpSRUpDoubleSector(kickers) 0"
    APSButton .e -parent $frame.f2.f1.sectorSelectButtons.frame -text E -size small -command "$frame.f2.f1.sectorSelectButtons.frame.none.button invoke; for {set i 30} {\$i <= 35} {incr i} {set APSMpSRUpDoubleSector(S\$i:\[expr \$i + 1\]) 1} ; set APSMpSRUpDoubleSector(kickers) 0"
    APSButton .f -parent $frame.f2.f1.sectorSelectButtons.frame -text F -size small -command "$frame.f2.f1.sectorSelectButtons.frame.none.button invoke; for {set i 36} {\$i <= 38} {incr i} {set APSMpSRUpDoubleSector(S\$i:\[expr \$i + 1\]) 1}; set APSMpSRUpDoubleSector(S40:01) 1 ; set APSMpSRUpDoubleSector(kickers) 1"
#    $frame.f2.f1.sectorSelectButtons.frame.all.button configure -command "[$frame.f2.f1.sectorSelectButtons.frame.all.button cget -command] ; set APSMpSRUpDoubleSector(kickers) 1"
#    $frame.f2.f1.sectorSelectButtons.frame.none.button configure -command "[$frame.f2.f1.sectorSelectButtons.frame.none.button cget -command] ; set APSMpSRUpDoubleSector(kickers) 0"
    APSCheckButtonFrame .kicker \
        -parent $frame.f2.f1 \
        -label "" \
        -variableList APSMpSRUpDoubleSector(kickers) \
        -buttonList {"Turn on kickers and septums"} \
        -orientation horizontal

    pack [label $frame.f2.f2.groupSelectLabel -text "Power Supply Selection"]
    APSCheckButtonFrame .groupSelectButtons \
        -parent $frame.f2.f2 \
        -label "" \
        -variableList {APSMpSRUpDoubleSector(SM) APSMpSRUpDoubleSector(M) APSMpSRUpDoubleSector(QD) APSMpSRUpDoubleSector(CM) APSMpSRUpDoubleSector(Q) APSMpSRUpDoubleSector(Q7) \
                           APSMpSRUpDoubleSector(SQ) APSMpSRUpDoubleSector(S)  \
                           APSMpSRUpDoubleSector(H) APSMpSRUpDoubleSector(FH) APSMpSRUpDoubleSector(CH)} \
        -buttonList {"DIPOLE (S:M1 + S:M2)" "DIPOLE (M) + TRIMs (MT)" "DIPOLE (Q) + TRIMs (QT)" "CANTED DIPOLEs (CM)" "QUADs (Q1, Q2, Q3, Q6)" "Q7 QUADs" "SKEW QUADs (SQ)" "SEXTs  (S)" "HCORRs (H) + VCORRs (V)" "FAST HORRs (FH) + FAST VCORRs (FV)" "CANTED HCORRs (CH) + CANTED VCORRs (CV)"} \
        -allNone 1 \
        -orientation horizontal \
        -limitPerRow 1
    #    pack [label $frame.f2.f3.groupSelectLabel -text "Kicker Selection"]
    #    APSCheckButtonFrame .kickerSelectButtons -parent $frame.f2.f3 -label "" -variableList {APSMpSRUpDoubleSector(IK1) APSMpSRUpDoubleSector(IK2) APSMpSRUpDoubleSector(IK3) APSMpSRUpDoubleSector(IK4) APSMpSRUpDoubleSector(IK5)} -buttonList {"S:IK1" "S:IK2" "S:IK3" "S:IK4" "S:IK5"} -allNone 1 -orientation horizontal -limitPerRow 1
    pack [frame $frame.f1]
    APSLabeledEntry .cycles -parent $frame.f1 -label "Number of Cycles:" \
        -textVariable APSMpSRUpDoubleSector(cycles) -width 3 -packOption "-side top"
    APSLabeledEntry .filter -parent $frame.f1 -label "PS Name Filter:" \
        -textVariable APSMpSRUpDoubleSector(filter) -width 10 -packOption "-side top"

    bindtags $frame.f1.cycles.entry "Entry .promptDialog all $frame.f1.cycles.entry"
    bind $frame.f1.cycles.entry <KeyPress> "
    if \"(\[llength \[set APSMpSRUpDoubleSector(cycles)\]\]) && (\[string is integer \[set APSMpSRUpDoubleSector(cycles)\]\])\" \{
        if \"(\[llength \[set APSMpSRUpDoubleSector(cycles)\]\]) && (\[set APSMpSRUpDoubleSector(cycles)\] <= 3) && (\[set APSMpSRUpDoubleSector(cycles)\] >= 1)\" \{ $frame.f1.cycles.entry configure -bg white \} else \{ $frame.f1.cycles.entry configure -bg yellow \}
        \} else \{ $frame.f1.cycles.entry configure -bg yellow \}
    "
    bind $frame.f1.cycles.entry <ButtonRelease-2> "
    if \"(\[llength \[set APSMpSRUpDoubleSector(cycles)\]\]) && (\[string is integer \[set APSMpSRUpDoubleSector(cycles)\]\])\" \{
        if \"(\[llength \[set APSMpSRUpDoubleSector(cycles)\]\]) && (\[set APSMpSRUpDoubleSector(cycles)\] <= 3) && (\[set APSMpSRUpDoubleSector(cycles)\] >= 1)\" \{ $frame.f1.cycles.entry configure -bg white \} else \{ $frame.f1.cycles.entry configure -bg yellow \}
        \} else \{ $frame.f1.cycles.entry configure -bg yellow \}
    "


#    pack [checkbutton $frame.configure -text "Configure Power Supplies" -variable APSMpSRUpDoubleSector(configure) -padx 4 -pady 4 -relief ridge] -padx 5
    pack [checkbutton $frame.condition -text "Condition power supplies" \
              -variable APSMpSRUpDoubleSector(forcecondition) -padx 4 -pady 4 -relief ridge] -padx 5
#    pack [checkbutton $frame.launch -text "Launch APSCalibrateDCPS" -variable APSMpSRUpDoubleSector(apsCalibrate) -padx 4 -pady 4 -relief ridge] -padx 5
    global apsContextHelp
    set apsContextHelp($frame.condition) "Normally, magnets will not be conditioned if the IOC indicates that they are already properly conditioned.  If you have a good reason to override this, select Force Conditioning.  Don't use this unnecessarily since the purpose is to avoid excessive conditioning."

    update
    APSAddSCRDialog .scr -parent $frame -system SR -arrayName APSMpSRUpDoubleSector \
        -defaultFile $APSMpSRUpDoubleSector(ShortFilename) -description $APSMpSRUpDoubleSector(Description)
    
    return
}

proc APSMpSRUpDoubleSector {args} {
    set sectorGroups {S40:01 S02:03 S04:05 S06:07 S08:09 S10:11 S12:13 \
                          S14:15 S16:17 S18:19 S20:21 S22:23 S24:25 S26:27 \
                          S28:29 S30:31 S32:33 S34:35 S36:37 S38:39}
    set QS4Sectors {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40}
    #2013/09/19 QS4 replace A:V4 in above sectors, which means there will no AV4 correctors in QS4Sectors
    set QS4sectorList ""
    set VsectorList ""
    foreach sectorGroup $sectorGroups {
        set $sectorGroup 0
    }
    set forcecondition 1
    set cycles 5
    set filter "*"
    set ShortFilename [APSFindSCROperationFile -machine SR -arrayName APSMpSRUpDoubleSector]
    #set apsCalibrate 0
    set kickers 0
    set families "H V FH FV SQ QT M MT Q Q7 QD S SM CM CH CV"
    foreach family $families {
        set $family 1
    }
    #set SM 0
    APSStrictParseArguments "$sectorGroups ShortFilename cycles filter H V FH FV SQ QT M MT Q Q7 QD S SM CM CH CV forcecondition kickers"
    APSMpStep init \
        -promptDialog APSMpSRUpDoubleSectorDialog \
        -vars "$sectorGroups ShortFilename cycles filter H V FH FV SQ QT M MT Q Q7 QD S SM CM CH CV forcecondition kickers" -proc "APSUMpSRUpDownDoubleSector forcecondition"
    if {![string length $ShortFilename]} {
        APSMpReturn error "APSMpSRUpDoubleSector: SCR file not choosen!"
    }
    if {![file exists /home/helios/oagData/SCR/snapshots/SR/$ShortFilename]} {
        APSMpReturn error "SCR file $ShortFilename not found"
    }
    if {[catch {exec sdds2stream /home/helios/oagData/SCR/snapshots/SR/$ShortFilename -parameter=SnapshotDescription -page=1 -noquotes} results]} {
        APSMpReturn error "APSMpSRUpDoubleSector: Invalid SCR file"
    }    
    if {[string first "Limited save:" $results] != -1} {
        APSMpReturn error "APSMpSRUpDoubleSector: LIMITED SAVE SCR files cannot be used for this procedure."
    }

    set MT $M
    set QT $QD
    set V $H
    set FV $FH
    set CV $CH
    set sectorArgs ""
    foreach sectorGroup $sectorGroups {
        append sectorArgs "-$sectorGroup [set $sectorGroup] "
    }

    if {$kickers} {
        APSMpStep "Turning on the kickers and septums"
        set id1 [APSMpParallel -mode "Automatic" -procedure "APSMpSRTurnOnKickers -IK1 1 -IK2 1 -IK3 1 -DK0 1 -IS1 1 -EK 0 -ES1 0 -ES2 0 -FOK1 1 -restore 1 -SCRFile $ShortFilename"]
    }
    set id2 [eval APSMpParallel -mode "Automatic" -procedure "\"APSUMpSRUpDownDoubleSector $sectorArgs -state on -ShortFilename $ShortFilename -cycles $cycles -filter $filter -forcecondition $forcecondition -H $H -V $V -FH $FH -FV $FV -SQ $SQ -QT $QT -M $M -MT $MT -Q $Q -Q7 $Q7 -QD $QD -S $S -SM1 $SM -SM2 $SM -CH $CH -CV $CV -CM $CM\""]

    if {$kickers} {
        if {[catch {APSMpJoin $id1} results]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem occured turning the kickers and septums on: $results"] == 1} {
                APSMpReturn error "APSMpSRUpDoubleSector: $results"
            }
        } else {
            if {0} {
                set tmpFile /tmp/[APSTmpString]
                if [catch {exec sddsprocess /home/helios/oagData/SCR/snapshots/SR/$ShortFilename $tmpFile \
                             "-match=column,ControlName=S38-IES:DK0:PS:VoltageC,ControlName=S39-IES:IS1:SetRefVoltageC,|,ControlName=S39-IES:IK\[1-3\]:PS:VoltageC,|,ControlName=S36C:FOK1:PS:SetVoltageC,|"} result] {
                    APSPEMTKDialog .warningDialog -strings Continue -default 0 -text "Problem restoring kicker and septum setpoints: $result"
                    catch {APSSendEMail -address soliday \
                             -subject "Problem restoring  kicker and septum setpoints."  \
                             -message "Problem restoring  kicker and septum setpoints.\n$result"} 
                    
                }
                if [catch {exec sddscasr -restore=verify $tmpFile} result] {
                    APSPEMTKDialog .warningDialog -strings Continue -default 0 -text "Problem restoring kicker and septum setpoints: $result"
                    catch {APSSendEMail -address soliday \
                             -subject "Problem restoring  kicker and septum setpoints."  \
                             -message "Problem restoring  kicker and septum setpoints.\n$result"} 
                    
                }
                catch {file delete $tmpFile}
            }
            if {0} {
                #TEMP Changes until we can resolve the caused of the over voltage or over current condition. (Al Hillman)
                if {[catch {APSSRPulsedPSDischargeEnable -PSList IS1} results]} {
                    APSMpReturn error "APSMpSRUpDoubleSector: $results"
                }
                APSMpStep "SR: Wait for IS:1 septum to reach operating voltage"
                set retries 180
                while {$retries} {
                    after 1000
                    if {[catch {APScavget -list=S:IS1:VoltageSetSendAO,S:IS1:DacAI} results]} {
                        APSMpReturn error "APSMpSRUpDoubleSector: $results"
                    }
                    set percentage [expr [lindex $results 1] / [lindex $results 0]]
                    if {$percentage > .95} {
                        break
                    }
                    incr retries -1
                }
                if {[catch {APSSRPulsedPSDischargeEnable -PSList IS1 -disable 1} results]} {
                    APSMpReturn error "APSMpSRUpDoubleSector: $results"
                }

                #TEMP changes for IS2
                APSMpSRTurnOnKickers -IK1 0 -IK2 0 -IK3 0 -IK4 0 -IK5 0 -IS1 0 -IS2 1

                set tmpFile /tmp/[APSTmpString]
                if [catch {exec sddsprocess /home/helios/oagData/SCR/snapshots/SR/$ShortFilename $tmpFile \
                             "-match=column,ControlName=S:IS2:VoltageSetSendAO"} result] {
                    APSPEMTKDialog .warningDialog -strings Continue -default 0 -text "Problem restoring kicker and septum setpoints: $result"
                    catch {APSSendEMail -address soliday \
                             -subject "Problem restoring  kicker and septum setpoints."  \
                             -message "Problem restoring  kicker and septum setpoints.\n$result"} 

                }
                if [catch {exec sddscasr -restore=verify $tmpFile} result] {
                    APSPEMTKDialog .warningDialog -strings Continue -default 0 -text "Problem restoring kicker and septum setpoints: $result"
                    catch {APSSendEMail -address soliday \
                             -subject "Problem restoring  kicker and septum setpoints."  \
                             -message "Problem restoring  kicker and septum setpoints.\n$result"} 

                }
                catch {file delete $tmpFile}

                if {[catch {APSSRPulsedPSDischargeEnable -PSList IS2} results]} {
                    APSMpReturn error "APSMpSRUpDoubleSector: $results"
                }
                APSMpStep "SR: Wait for IS:2 septum to reach operating voltage"
                set retries 180
                while {$retries} {
                    after 1000
                    if {[catch {APScavget -list=S:IS2:VoltageSetSendAO,S:IS2:DacAI} results]} {
                        APSMpReturn error "APSMpSRUpDoubleSector: $results"
                    }
                    set percentage [expr [lindex $results 1] / [lindex $results 0]]
                    if {$percentage > .95} {
                        break
                    }
                    incr retries -1
                }
                if {[catch {APSSRPulsedPSDischargeEnable -PSList IS2 -disable 1} results]} {
                    APSMpReturn error "APSMpSRUpDoubleSector: $results"
                }
                #END temp changes
            }
        }
    }
    if {[catch {APSMpJoin $id2} results]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem occured starting double sectors: $results"] == 1} {
            APSMpReturn error "APSMpSRUpDoubleSector: $results"
        }
    }

    

    APSMpReturn ok
}

proc APSMpSRDownDoubleSectorInfo {} {
    return "Brings two consecutive SR sectors down\
by turning the converters and corresponding raw\
  supplies off."
}

proc APSMpSRDownDoubleSectorDialog {frame} {

    global status APSMpSRDownDoubleSector

    set status "Select SR Sectors"
    pack [frame $frame.f2]
    pack [frame $frame.f2.f1] -side left -fill y
    pack [frame $frame.f2.f2] -side left
    pack [label $frame.f2.f1.sectorSelectLabel -text "Storage Ring Sector Selection"]
    APSCheckButtonFrame .sectorSelectButtons \
        -parent $frame.f2.f1 \
        -label "" \
        -variableList {APSMpSRDownDoubleSector(S40:01) APSMpSRDownDoubleSector(S02:03) \
                           APSMpSRDownDoubleSector(S04:05) APSMpSRDownDoubleSector(S06:07) \
                           APSMpSRDownDoubleSector(S08:09) APSMpSRDownDoubleSector(S10:11) \
                           APSMpSRDownDoubleSector(S12:13) APSMpSRDownDoubleSector(S14:15) \
                           APSMpSRDownDoubleSector(S16:17) APSMpSRDownDoubleSector(S18:19) \
                           APSMpSRDownDoubleSector(S20:21) APSMpSRDownDoubleSector(S22:23) \
                           APSMpSRDownDoubleSector(S24:25) APSMpSRDownDoubleSector(S26:27) \
                           APSMpSRDownDoubleSector(S28:29) APSMpSRDownDoubleSector(S30:31) \
                           APSMpSRDownDoubleSector(S32:33) APSMpSRDownDoubleSector(S34:35) \
                           APSMpSRDownDoubleSector(S36:37) APSMpSRDownDoubleSector(S38:39)} \
        -buttonList {S40:01 S02:03 S04:05 S06:07 S08:09 S10:11 S12:13 \
                         S14:15 S16:17 S18:19 S20:21 S22:23 S24:25 S26:27 \
                         S28:29 S30:31 S32:33 S34:35 S36:37 S38:39} \
        -allNone 1 \
        -orientation horizontal \
        -limitPerRow 4
    APSButton .a -parent $frame.f2.f1.sectorSelectButtons.frame -text A -size small -command "$frame.f2.f1.sectorSelectButtons.frame.none.button invoke; for {set i 2} {\$i <= 8} {incr i} {set APSMpSRDownDoubleSector(S0\$i:0\[expr \$i + 1\]) 1} ; set APSMpSRDownDoubleSector(kickers) 0; set APSMpSRDownDoubleSector(btsoff) 0"
    APSButton .b -parent $frame.f2.f1.sectorSelectButtons.frame -text B -size small -command "$frame.f2.f1.sectorSelectButtons.frame.none.button invoke; for {set i 10} {\$i <= 16} {incr i} {set APSMpSRDownDoubleSector(S\$i:\[expr \$i + 1\]) 1} ; set APSMpSRDownDoubleSector(kickers) 0; set APSMpSRDownDoubleSector(btsoff) 0"
    APSButton .c -parent $frame.f2.f1.sectorSelectButtons.frame -text C -size small -command "$frame.f2.f1.sectorSelectButtons.frame.none.button invoke; for {set i 18} {\$i <= 22} {incr i} {set APSMpSRDownDoubleSector(S\$i:\[expr \$i + 1\]) 1} ; set APSMpSRDownDoubleSector(kickers) 0; set APSMpSRDownDoubleSector(btsoff) 0"
    APSButton .d -parent $frame.f2.f1.sectorSelectButtons.frame -text D -size small -command "$frame.f2.f1.sectorSelectButtons.frame.none.button invoke; for {set i 24} {\$i <= 28} {incr i} {set APSMpSRDownDoubleSector(S\$i:\[expr \$i + 1\]) 1} ; set APSMpSRDownDoubleSector(kickers) 0; set APSMpSRDownDoubleSector(btsoff) 0"
    APSButton .e -parent $frame.f2.f1.sectorSelectButtons.frame -text E -size small -command "$frame.f2.f1.sectorSelectButtons.frame.none.button invoke; for {set i 30} {\$i <= 35} {incr i} {set APSMpSRDownDoubleSector(S\$i:\[expr \$i + 1\]) 1} ; set APSMpSRDownDoubleSector(kickers) 0; set APSMpSRDownDoubleSector(btsoff) 0"
    APSButton .f -parent $frame.f2.f1.sectorSelectButtons.frame -text F -size small -command "$frame.f2.f1.sectorSelectButtons.frame.none.button invoke; for {set i 36} {\$i <= 38} {incr i} {set APSMpSRDownDoubleSector(S\$i:\[expr \$i + 1\]) 1}; set APSMpSRDownDoubleSector(S40:01) 1 ; set APSMpSRDownDoubleSector(kickers) 1; set APSMpSRDownDoubleSector(btsoff) 1"
#    $frame.f2.f1.sectorSelectButtons.frame.all.button configure -command "[$frame.f2.f1.sectorSelectButtons.frame.all.button cget -command] ; set APSMpSRDownDoubleSector(kickers) 1; set APSMpSRDownDoubleSector(btsoff) 1"
#    $frame.f2.f1.sectorSelectButtons.frame.none.button configure -command "[$frame.f2.f1.sectorSelectButtons.frame.none.button cget -command] ; set APSMpSRDownDoubleSector(kickers) 0; set APSMpSRDownDoubleSector(btsoff) 0"
    APSCheckButtonFrame .kicker \
        -parent $frame.f2.f1 \
        -label "" \
        -variableList APSMpSRDownDoubleSector(kickers) \
        -buttonList {"Turn off kickers and septums"} \
        -orientation horizontal
    APSCheckButtonFrame .bts \
        -parent $frame.f2.f1 \
        -label "" \
        -variableList APSMpSRDownDoubleSector(btsoff) \
        -buttonList {"Turn off SR side of the BTS"} \
        -orientation horizontal
    APSCheckButtonFrame .stopCond \
        -parent $frame.f2.f1 \
        -label "" \
        -variableList APSMpSRDownDoubleSector(stopConditionOnly) \
        -buttonList {"Stop conditioning only then exit"} \
        -orientation horizontal

    pack [frame $frame.f1]
    APSLabeledEntry .filter -parent $frame.f1 -label "PS Name Filter:" \
        -textVariable APSMpSRDownDoubleSector(filter) -width 10 -packOption "-side top"

    pack [label $frame.f2.f2.groupSelectLabel -text "Power Supply Selection"]
    APSCheckButtonFrame .groupSelectButtons \
        -parent $frame.f2.f2 \
        -label "" \
        -variableList {APSMpSRDownDoubleSector(SM) APSMpSRDownDoubleSector(M) APSMpSRDownDoubleSector(QD) APSMpSRDownDoubleSector(CM) \
                         APSMpSRDownDoubleSector(Q) APSMpSRDownDoubleSector(Q7) \
                           APSMpSRDownDoubleSector(SQ) APSMpSRDownDoubleSector(S)  \
                           APSMpSRDownDoubleSector(H) APSMpSRDownDoubleSector(FH) APSMpSRDownDoubleSector(CH) APSMpSRDownDoubleSector(excludeRaws)} \
        -buttonList {"DIPOLE (S:M1 + S:M2)" "DIPOLE (M) + TRIMs (MT)" "DIPOLE (Q) + TRIMs (QT)" "CANTED DIPOLEs (CM)" "QUADs (Q1, Q2, Q3, Q6)" "Q7 QUADs" "SKEW QUADs (SQ)" "SEXTs  (S)" "HCORRs (H) + VCORRs (V)" "FAST HORRs (FH) + FAST VCORRs (FV)" "CANTED HCORRs (CH) + CANTED VCORRs (CV)" "Exclude Raw Supplies"} \
        -allNone 1 \
        -orientation horizontal \
        -limitPerRow 1
    update
    APSAddSCRDialog .scr -parent $frame -system SR -arrayName APSMpSRDownDoubleSector \
        -defaultFile $APSMpSRDownDoubleSector(ShortFilename) -description $APSMpSRDownDoubleSector(Description)

    return
}

proc APSMpSRDownDoubleSector {args} {
    set sectorGroups {S40:01 S02:03 S04:05 S06:07 S08:09 S10:11 S12:13 \
                        S14:15 S16:17 S18:19 S20:21 S22:23 S24:25 S26:27 \
                        S28:29 S30:31 S32:33 S34:35 S36:37 S38:39}
    foreach sectorGroup $sectorGroups {
        set $sectorGroup 0
    }
    set ShortFilename [APSFindSCROperationFile -machine SR -arrayName APSMpSRDownDoubleSector]
    set families "H V FH FV SQ QT M MT Q Q7 QD S SM CH CV CM"
    foreach family $families {
        set $family 1
    }
    #set SM 0
    set excludeRaws 0
    set kickers 0
    set btsoff 0
    set stopConditionOnly 0
    set filter "*"
    APSStrictParseArguments "$sectorGroups ShortFilename excludeRaws kickers btsoff H V FH FV SQ QT M MT Q Q7 QD S SM CH CV CM filter stopConditionOnly"
    APSMpStep init \
      -promptDialog APSMpSRDownDoubleSectorDialog \
      -vars "$sectorGroups ShortFilename excludeRaws kickers btsoff btsoff H V FH FV SQ QT M MT Q Q7 QD S SM CH CV CM filter stopConditionOnly" -proc "APSUMpSRUpDownDoubleSector"
    if {![string length $ShortFilename]} {
        APSMpReturn error "APSMpSRDownDoubleSector: SCR file not choosen!"
    }
    if {![file exists /home/helios/oagData/SCR/snapshots/SR/$ShortFilename]} {
        APSMpReturn error "SCR file $ShortFilename not found"
    }
    if {[catch {exec sdds2stream /home/helios/oagData/SCR/snapshots/SR/$ShortFilename -parameter=SnapshotDescription -page=1 -noquotes} results]} {
        APSMpReturn error "APSMpSRDownDoubleSector: Invalid SCR file"
    }    
    if {[string first "Limited save:" $results] != -1} {
        APSMpReturn error "APSMpSRDownDoubleSector: LIMITED SAVE SCR files cannot be used for this procedure."
    }

    set MT $M
    set QT $QD
    set V $H
    set FV $FH
    set CV $CH
    set sectorArgs ""
    foreach sectorGroup $sectorGroups {
        append sectorArgs "-$sectorGroup [set $sectorGroup] "
    }
    if {$stopConditionOnly == 0} {
        if {$kickers} {
            APSMpStep "Turning off the kickers and septums"
            if {[catch {APSMpSRTurnOffKickers -IK1 1 -IK2 1 -IK3 1 -DK0 1 -IS1 1 -EK 0 -ES1 0 -ES2 0 -FOK1 1} results]} {
                APSMpReturn error "$results"
            }
        }
        if {$btsoff} {
            APSMpStep "Turning off the SR side of the BTS"
            if {[catch {APSMpBTSTurnOffPS -turnOffList "BTS:BH BTS:BV BTS:BQ BTS:BSQ BTS:CQ BTS:DQ BTS:BB1 BTS:CB1" -turnOffListDetailed "BTS:BH1 BTS:BH2 BTS:BV1 BTS:BV2 BTS:BV3 BTS:BQ1 BTS:BQ2 BTS:BQ3 BTS:BQ4 BTS:BQ5  BTS:BSQ1 BTS:BSQ2 BTS:BSQ3 BTS:BSQ4 BTS:BSQ5 BTS:BSQ6 BTS:BSQ1H BTS:BSQ2V BTS:BSQ5H BTS:BSQ6V BTS:CQ1 BTS:CQ2 BTS:CQ3 BTS:CQ1H BTS:CQ2V BTS:CQ3H BTS:DQ1 BTS:DQ2 BTS:DQ1H BTS:DQ2V BTS:BB1 BTS:CB1"} results]} {
                APSMpReturn error "$results"
            }
        }
    }
    if {[catch {eval APSUMpSRUpDownDoubleSector $sectorArgs -state off -ShortFilename $ShortFilename -cycles 0 -excludeRaws $excludeRaws -H $H -V $V -FH $FH -FV $FV -SQ $SQ -QT $QT -M $M -MT $MT -Q $Q -Q7 $Q7 -QD $QD -S $S -SM1 $SM -SM2 $SM -CH $CH -CV $CV -CM $CM -filter $filter -stopConditionOnly $stopConditionOnly} results]} {
        APSMpReturn error "$results"
    }
    APSMpReturn ok
}

proc WaitForTaskToFinish {args} {
    set cavget ""
    set checkExpression ""
    set waitLimit 3
    set updateInterval 10
    set message 1
    APSStrictParseArguments {cavget waitLimit updateInterval checkExpression message}
    if {![llength $cavget]} {
        return -code error "WaitForTaskToFinish: invalid cavget option"
    }
    if {![llength $checkExpression]} {
        return -code error "WaitForTaskToFinish: invalid checkExpression option"
    }
    set wait 1
    while {$wait} {
        set wait 0
        if {[incr waitLimit -1] < 0} {
            if {$message} {
                set waitLimit 1
                set answer [APSPEMTKDialog .warningDialog -text "[join $badList \n]\n\n1. Fix the problem manually then press Re-test Condition.\n\n2. Ignore the problem, i.e. do not re-test, and resume the PEM procedure. There is a risk involved as the problem may actually be important, and the PEM has no way of determining this.\n\n3. Press the Abort Procedure to which will cause the eventual exit of the PEM procedure." -strings {"Re-test Condition" "Continue without Re-testing" "Abort Procedure"}]
                
                #set answer [tk_dialog .warningDialog "Warning Message" "$pvName = $pvValue\n\nChoose one of the following:\n\nFix the problem manually then press Continue.\n\nPress Cancel to stop the procedure" warning -1 Continue Cancel "Continue at\nyour own risk"]
                case $answer {
                    0 { 
                    } 
                    1 {
                        return -code ok
                    }
                    2 {
                        return -code error "WaitForTaskToFinish: Timed out, $pvName = $pvValue"
                    } 
                }
            } else {
                return -code error "WaitForTaskToFinish: Timed out, $pvName = $pvValue"
            }
        }
        if {[catch {eval $cavget} results]} {
            return -code error "WaitForTaskToFinish: $results"
        }
        set badList ""
        foreach {name value} $results {
            if $checkExpression {
                if {$waitLimit == 0} {
                    set pvName $name
                    set pvValue $value
                    lappend badList $pvName=$value
                }
                set wait 1
                #break
            }
        }
        if {$wait} {
            APSWaitWithUpdate -waitSeconds $updateInterval
        }
    }
}

proc APSFindSCROperationFile {args} {
    set machine ""
    set preference ""
    set arrayName ""
    APSStrictParseArguments {machine preference arrayName}
    if {![string length $preference]} {
        set preference UserBeamPreferred
    }
    global $arrayName
    set oldDir [pwd]
    set dir /home/helios/oagData/SCR/snapshots/$machine
    cd $dir
    if {![file exist $machine-$preference.gz]} {
        cd $oldDir
        return -code error "$machine-$preference.gz does not exist!"
    }
    set file [file readlink $machine-$preference.gz]
    if [catch {file readlink $file} file1] {
	#file is not a link, do nothing
    } else {
	set file $file1
    }
    set ${arrayName}(Description) [exec sdds2stream $file -par=SnapshotDescription]
    cd $oldDir
    return  [file tail $file]
}

proc APSRampPVs {args} {
    set PVList ""
    set valueList ""
    set steps 30
    set pause 1
    set prefix ""
    set suffix ""
    APSStrictParseArguments {PVList valueList steps pause prefix suffix}

    if {[llength $PVList] != [llength $valueList]} {
        APSMpReturn error "APSRampPVs: mismatched length of list arguments."
    }
    if {$steps <=0 } {
        APSMpReturn error "APSRampPVs: invalid step value."
    }
    if {$pause <=0 } {
        APSMpReturn error "APSRampPVs: invalid pause value."
    }
    if {![llength $PVList]} return
    # get original values
    set name ""
    foreach PV $PVList {
        lappend name ${prefix}${PV}${suffix}
    }
    if {[catch {APScavget -list=[join $name ,] -pend=30} origValues]} {
        APSMpReturn error "APSRampPVs: $origValues"
    }
    for {set i 1} {$i <= $steps} {incr i} {
        set nameAndValue ""
        foreach PV $PVList target $valueList orig $origValues {
            set delta [expr 1.0 *($target - $orig)/ $steps]
            set value [expr 1.0 *$orig + $i * $delta]
            lappend nameAndValue ${prefix}${PV}${suffix}=$value
        }
        if {[catch {APScavput -list=[join $nameAndValue ,] -blunderAhead -pend=30} results]} {
            APSMpReturn error "APSRampPVs: $results"
        }
        if {$i < $steps} {
            after [expr int(1000 * $pause)]
        }
    }
}

proc APSMpSRDumpBeam {args} {
    if {[catch {APScavput -list=S:MPS:dumpBeamSQ=1 -pend=10} results]} {
        return -code error "Problem with setting S:MPS:dumpBeamSQ: $results"
    }
    APSWaitWithUpdate -waitSeconds 1
}

proc APSMpSRResetMPS {args} {
    # Commented out resetting AGC 
    # because there is a small but non-zero chance of conflict 
    # with rf group.
    if {0} {
        if {[catch {APScavput -list=SRF:AGC:FB_SoftEngage -list=1,2 -list=BO=1 -pend=30} results]} {
            return -code error "Problem with setting SRF:AGC:FB_SoftEngage1BO and SRF:AGC:FB_SoftEngage2BO: $results"
        }
    }
    
    if {[catch {exec resetMPS} results]} {
        return -code error "$results"
    }
}



proc APSUMpSRUpDownDoubleSector {args} {
    global apsNetworkDomain
    set sectorGroups {S40:01 S02:03 S04:05 S06:07 S08:09 S10:11 S12:13 \
                          S14:15 S16:17 S18:19 S20:21 S22:23 S24:25 S26:27 \
                          S28:29 S30:31 S32:33 S34:35 S36:37 S38:39}
    foreach sectorGroup $sectorGroups {
        set $sectorGroup 0
    }
    #Possible states: on, off
    set state on
    set cycles 5
    set filter "*"
    set forcecondition 0
    set stopConditionOnly 0
    set ShortFilename [APSFindSCROperationFile -machine SR -arrayName APSMpSRUpDownDoubleSector]

    set families "H V FH FV SQ QT M MT Q Q7 QD S SM1 SM2 CH CV CM"
    foreach family $families {
        set $family 1
    }
    #set SM1 0
    #set SM2 0
    set excludeRaws 0
    
    APSStrictParseArguments "$sectorGroups state ShortFilename cycles filter H V FH FV SQ QT M MT Q Q7 QD S SM1 SM2 CH CV CM excludeRaws forcecondition stopConditionOnly"

    foreach param "state ShortFilename cycles filter H V FH FV SQ QT M MT Q Q7 QD S SM1 SM2 CH CV CM forcecondition stopConditionOnly" {
        append paramString "$param=\"[set $param]\" "
    }
        
    set sectorPairs {"40 1 " "2 3 " "4 5 " "6 7 " "8 9 " "10 11 " "12 13 " \
                         "14 15 " "16 17 " "18 19 " "20 21 " "22 23 " "24 25 " \
                         "26 27 " "28 29 " "30 31 " "32 33 " "34 35 " "36 37 " "38 39 "}
    set sectors ""
    set sectorsOdd ""
    set sectorPairWithColon ""
    foreach sectorGroup $sectorGroups sectorPair $sectorPairs {
        if {[set $sectorGroup]} {
            append sectors $sectorPair
            lappend sectorsOdd [lindex $sectorPair 1]
            lappend sectorPairWithColon "[lindex $sectorPair 0]:[lindex $sectorPair 1]"
        }
    }
    
    if {![info exists sectors]} {
        APSMpReturn error "APSUMpSRUpDownDoubleSector: No sectors chosen"
    }

    set cycles2 $cycles
    if {$cycles == 0} {
        set cycles2 1
    }
    APSMpStep "log script action..."
    catch {APSLogScriptAction \
               -procedure APSUMpSRUpDownDoubleSector \
               -action initialize \
               -state ok \
               -parameters $paramString}
    
    if {![string length $ShortFilename]} {
        APSMpReturn error "APSUMpSRUpDownDoubleSector: SCR file was not choosed!"
    }
    if {$ShortFilename == [file tail $ShortFilename]} {
        set ShortFilename [file join /home/helios/oagData/SCR/snapshots/SR/ $ShortFilename]
    }
    if {[catch {exec sdds2stream $ShortFilename -parameter=SnapshotDescription -page=1 -noquotes} results]} {
        APSMpReturn error "APSUMpSRDownDoubleSector: Invalid SCR file"
    }    
    if {[string first "Limited save:" $results] != -1} {
        APSMpReturn error "APSUMpSRDownDoubleSector: LIMITED SAVE SCR files cannot be used for this procedure."
    }
    
    set f ""
    foreach family $families {
        if {[set $family]} {
            lappend f $family
        }
    }
    set families $f

    if {0} {
        if {$CM} {
            if {[catch {exec sdds2stream /home/helios/oagData/sr/IDs/devices.sdds -col=DeviceName} deviceNames]} {
                APSMpReturn error "APSUMpSRDownDoubleSector: $deviceNames"
            }
            if {[catch {APScavget -list=[join $deviceNames ,] -list=:GapM -pend=10} gaps]} {
                APSMpReturn error "APSUMpSRDownDoubleSector: $gaps"
            }
            set pass 1
            foreach gap $gaps {
                if {$gap < 70} {
                    set pass 0
                }
            }
            if {$pass == 0} {
                APSMpStep "Opening gaps"
                catch {APScavput -list=ID:OpenDevice=1 -blunderAhead -pend=5}
                set gapsWereOpened 1
            } else {
                set gapsWereOpened 0
            }
        }
    }

    APSMpStep "Stopping Conditioning of Power Supplies"
    if {[catch {APSUSrDcpsAction \
                    -families $families \
                    -action stopcond \
                    -filter $filter \
                    -sectors $sectors} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem stopping conditioning of Power Supplies\n$results"] == 1} {
            APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
        }
    }

    if {$stopConditionOnly} {
        APSMpReturn ok
    }

    if {$state == "off"} {
        APSMpStep "Turning off Power Supplies after ramping to 0"
        if {[catch {APSUSrDcpsAction \
                        -families $families \
                        -action off \
                        -filter $filter \
                        -sectors $sectors} results]} {
            if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem turning off Power Supplies\n$results"] == 1} {
                APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
            }
        }

        foreach family "H V FH FV SQ QT M MT Q Q7 QD S CH CV CM" {
            if {![set $family]} {
                set excludeRaws 1
            }
        }
        if {$filter != "*"} {
            set excludeRaws 1
        }
        if {$excludeRaws == 0} {
            #Turn off corresponding raw power supplies.
            APSMpStep "Turning off corresponding raw power supplies" -desc "(Off) Turn off corresponding raw power supplies"
            if {[catch {APSSrRpsAction \
                            -action off \
                            -group R \
                            -sectors $sectorsOdd} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem occurred while turning raw power supplies off \n$results"] == 1} {
                    APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
                }
            }
            
            #Wait for corresponding raw power supplies to turn off by checking the status of the LED.
            #Check status every few seconds until completed or timed out.
            APSMpStep "Waiting for raw power supplies to turn off" -desc "(Off) Waiting for raw power supplies to turn off"
            if {[catch {WaitForTaskToFinish \
                            -cavget "APScavget -list=S -list=[join $sectorPairWithColon ,] -list=:R -list=1,2,3,4 -list=:StatusCALC -pend=30 -label" \
                            -waitLimit 3 \
                            -updateInterval 5 \
                            -checkExpression {($value != 1)}} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem occurred while waiting for raw power supplies to turn off \n$results"] == 1} {
                    APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
                }
            }
        }
        APSMpReturn ok
    }

    APSMpStep "Configuring Power Supplies"        
    if {[catch {APSUSrDcpsAction \
                  -families $families \
                  -action configure \
                  -sectors $sectors \
                  -filter $filter \
                  -SCRFile $ShortFilename} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem configuring Power Supplies\n$results"] == 1} {
            APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
        }
    }

    APSMpStep "Configuring cycles for Power Supplies"
    if {[catch {APSUSrDcpsAction \
                  -families $families \
                  -action setcycles \
                  -value $cycles \
                  -filter $filter \
                  -sectors $sectors} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem configuring cycles for Power Supplies\n$results"] == 1} {
            APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
        }
    }

    APSMpStep "Checking for open shutters" -desc "Checking for open shutters"
    if {[catch {APScavget -list=NoOfShuttersOpenA -pend=30} results]} {
        APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
    }
    if {$results != "0"} {
        if {[APSPEMTKDialog .warningDialog -text "$results open shutters found. Please rectify the problem."] == 1} {
            APSMpReturn error "APSUMpSRUpDownDoubleSector: $results open shutters found. User aborted."
        }
    }
    
    APSMpStep "Checking for SR Current" -desc "Checking for SR Current"
    if {[catch {APScavget -list=S-DCCT:CurrentM -pend=30} results]} {
        APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
    }
    if { $results > .5 } {
        set answer [APSPEMTKDialog .warningDialog -text "SR current found. You can manually fix this or use the old APS MPS dump button." -strings {"Run MPS Dump" "I fixed this manually" "Abort Procedure"}]
        if {$answer == 0} {
            APSMpStep "Dumping beam" -desc "Dump beam"
            if {[catch {APSMpSRDumpBeam} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: \n$results"] == 1} {
                    APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
                }
            }
            if {[catch {APSMpSRResetMPS} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: \n$results"] == 1} {
                    APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
                }
            }
        } elseif {$answer == 2} {
            APSMpReturn error "APSUMpSRUpDownDoubleSector: Aborted by user when SR current was found."
        }
    }

    if {[llength $sectors]} {
        APSMpStep "Checking state of raw power supplies" -desc "Check the state of the raw power supplies"
        
        if {[catch {APScavget -list=S -list=[join $sectorPairWithColon ,] -list=:R -list=1,2,3,4 -list=:StatusCALC -pend=5 -label} results]} {
            APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
        }
        set nameAndValue ""
        set resetCabNameAndValue ""
        set resetFlowNameAndValue ""
        foreach "name value" $results {
            if {$value != 0} {
                regsub -all {:StatusCALC} $name {} name
                lappend nameAndValue ${name}:ResetSEQ=1
                #lappend nameAndValue ${name}:ONSEQ=1
                lappend resetCabNameAndValue [string range $name 0 end-2]MagIntlkResetBO=1
                lappend resetFlowNameAndValue [string range $name 0 end-2]PSIntlkResetBO=1
            }
        }

        if {[llength $nameAndValue]} {
            #Reset MPEOBs for raw power supplies.
            APSMpStep "Reset MPEOBs for corresponding raw power supplies" -desc "(On) Reset MPEOBs for corresponding raw power supplies"

            if {[catch {APScavput -list=[join $resetCabNameAndValue ,] -blunderAhead -pend=30} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem occurred while resetting BPEOBs for raw power supplies \n$results"] == 1} {
                    APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
                }
            }
            #Turn on corresponding raw power supplies.
            APSMpStep "Turning on corresponding raw power supplies" -desc "(On) Turn on corresponding raw power supplies"

            if {[catch {APScavput -list=[join $nameAndValue ,] -blunderAhead -pend=30} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem occurred while turning on raw power supplies \n$results"] == 1} {
                    APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
                }
            } 
            #Wait for corresponding raw power supplies to turn on by checking the status of the LED.
            #Check status every few seconds until completed or timed out.
            while {1} {
                APSMpStep "Waiting for raw power supplies to turn on" -desc "(On) Waiting for raw power supplies to turn on"
                if {[catch {WaitForTaskToFinish \
                              -cavget "APScavget -list=S -list=[join $sectorPairWithColon ,] -list=:R -list=1,2,3,4 -list=:StatusCALC -pend=30 -label" \
                              -waitLimit 5 \
                              -updateInterval 5 \
                              -checkExpression {($value != 0)}} results]} {
                    
                    set answer [APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem occurred while waiting for raw power supplies to turn on\n$results" -strings {Continue Recheck "Abort Procedure"}]
                    if {$answer == 1} {
                        continue
                    } elseif {$answer == 2} {
                        APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
                    }
                    break
                } else {
                    break
                }
            }
        }
    }
           
    foreach sectorPair $sectorPairWithColon {
        APSMpStep "Resetting PS and magnet interlocks"
        #No longer setting S${sectorPair}:PSIntlkResetBO=1 because it doesn't exist
        if {[catch {APScavput -list=S${sectorPair}:MagIntlkResetBO=1 -blunderAhead -pend=5} results]} {
            if {[APSPEMTKDialog .warningDialog -text "APSMpSRUpDownDoubleSector: Problem occurred while reseting PS and magnet interlocks\n$results"] == 1} {
                APSMpReturn error "APSMpSRUpDownDoubleSector: $results"
            }
        }
    }
    
    APSMpStep "Setting Power Supplies to 0 Amps if they are off"
    if {[catch {APSUSrDcpsAction \
                    -families $families \
                    -action setIfOff \
                    -filter $filter \
                    -value 0 \
                    -sectors $sectors} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem setting Power Supplies to 0 Amps if they are off\n$results"] == 1} {
            APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
        }
    }

    
    while {1} {
        APSMpStep "Turning on Power Supplies"
        if {[catch {APSUSrDcpsAction \
                      -families $families \
                      -filter $filter \
                      -action on \
                      -sectors $sectors} results]} {
            set answer [APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem turning on Power Supplies\n$results" -strings {Continue Retry "Abort Procedure"}]
            if {$answer == 1} {
                continue
            } elseif {$answer == 2} {
                APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
            }
        }
        break
    }

    if {0} {
        if {$CM} {
            set tries 1
            while {1} {
                if {[catch {APScavget -list=[join $deviceNames ,] -list=:GapM -pend=10} gaps]} {
                    APSMpReturn error "APSUMpSRDownDoubleSector: $gaps"
                }
                set pass 1
                foreach gap $gaps {
                    if {$gap < 70} {
                        set pass 0
                    }
                }
                if {$pass} {
                    break
                }
                if {$tries == 18} {
                    set answer [APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem with gaps not opening" -strings {Continue Recheck "Abort Procedure"}]
                    if {$answer == 1} {
                        continue
                    } elseif {$answer == 2} {
                        APSMpReturn error "APSUMpSRUpDownDoubleSector: Problem with gaps not opening"
                    }
                    break
                }
                APSWaitWithUpdate -waitSeconds 10
                incr tries
            }
        }
    }

    if {$forcecondition} {
        APSMpStep "Aborting Orbit Controllaws" -desc "Abort Orbit Controllaws"
        if {[catch {exec cavput -list=S:RC:OrbitControlLawXC.ABRT=1,S:RC:OrbitControlLawYC.ABRT=1} results]} {
            if {[APSPEMTKDialog .warningDialog -text "APSMpSRUpDownDoubleSector: Problem occurred while aborting Orbit Controllaws \n$results"] == 1} {
                APSMpReturn error "APSMpSRUpDownDoubleSector: $results"
            }                
        }

        set familiesToSetToZero ""
        if {$SM1} {
            APSMpStep "Delaying the Quads and Dipoles conditioning until after S:M1 is finished"

            set familiesMod2 ""
            if {$Q} {
                lappend familiesMod2 Q
                lappend familiesToSetToZero Q
            }
            if {$Q7} {
                lappend familiesMod2 Q7
                lappend familiesToSetToZero Q7
            }
            if {$QD} {
                lappend familiesMod2 QD
                lappend familiesMod2 QT
                lappend familiesToSetToZero QD
            }
            if {$CM} {
                lappend familiesMod2 CM
                lappend familiesToSetToZero CM
            }
            if {$M} {
                lappend familiesMod2 M
                lappend familiesMod2 MT
                lappend familiesToSetToZero M
            }

            set Q 0
            set Q7 0
            if {$QD} {
                set QT 0
            }
            set QD 0
            if {$M} {
                set MT 0
            }
            set M 0
            set CM 0

            set f ""
            foreach family $families {
                if {[set $family]} {
                    if {$family == "H"} {
                        lappend f Hmod
                        lappend familiesToSetToZero Hmod
                    } elseif {$family == "V"} {
                        lappend f Vmod
                        lappend familiesToSetToZero Vmod
                    } else {
                        lappend f $family
                        lappend familiesToSetToZero $family
                    }
                }
            }
            set familiesMod1 $f
        } else {
            set familiesMod1 $families
            set familiesMod2 ""
            set familiesToSetToZero $families
        }


        if {[llength $familiesToSetToZero]} {
            APSMpStep "Setting Power Supplies to 0 Amps before conditioning"
            if {[catch {APSUSrDcpsAction \
                          -families $familiesToSetToZero \
                          -action setAndWait \
                          -filter $filter \
                          -value 0 \
                          -sectors $sectors} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem setting Power Supplies to 0 Amps\n$results"] == 1} {
                    APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
                }
            }
        }


        APSMpStep "Conditioning Power Supplies"
        if {[catch {APSUSrDcpsAction \
                        -families $familiesMod1 \
                        -filter $filter \
                        -action forcecondition \
                        -sectors $sectors} results]} {
            if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem conditioning Power Supplies\n$results"] == 1} {
                APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
            }
        }

        if {$SM1 && ([llength $familiesMod2])} {

            if {0} {
                APSMpStep "Waiting for S:M1 conditioning to finish"
                APSWaitWithUpdate -waitSeconds 5
                if {[catch {APSUSrDcpsAction \
                              -families "SM1" \
                              -action listcond \
                              -sectors $sectors} results]} {
                    if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem waiting for S:M1 conditioning to finish\n$results"] == 1} {
                        APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
                    }
                }
                set count [llength $results]
                while {$count > 0} {
                    APSMpStep "S:M1 Power Supply still conditioning"
                    if {[catch {APSUSrDcpsAction \
                                  -families "SM1" \
                                  -action listcond \
                                  -sectors $sectors} results]} {
                        if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem waiting for S:M1 conditioning to finish\n$results"] == 1} {
                            APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
                        }
                    }
                    set count [llength $results]
                    APSWaitWithUpdate -waitSeconds 5
                }
            } else {
                APSMpStep "Waiting 20 minutes to let S:M1 condition enough before starting conditioning on selected quad and dipoles."
                set timeLoop 0
                while {$timeLoop < 20} {
                    APSMpStep "Waited $timeLoop minutes out of 20 so far."
                    APSWaitWithUpdate -waitSeconds 60
                    incr timeLoop
                }
            }

            APSMpStep "Conditioning Quads and Dipoles after S:M1 finished"
            if {[catch {APSUSrDcpsAction \
                          -families $familiesMod2 \
                          -filter $filter \
                          -action forcecondition \
                          -sectors $sectors} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem conditioning Power Supplies\n$results"] == 1} {
                    APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
                }
            }
        }
        if {[lsearch -exact $familiesMod2 Q7] >= 0} {
            set Q7 1
        }
        if {[lsearch -exact $familiesMod2 CM] >= 0} {
            set CM 1
        }

        if {($H == 0) && (($S == 1) || ($Q7 == 1))} {
            set H 1
            set V 1
            append families " H V"
        }

#Leave out the filter option here because we may miss some sequential conditioning supplies
        APSMpStep "Waiting for conditioning to finish"
        APSWaitWithUpdate -waitSeconds 5
        if {[catch {APSUSrDcpsAction \
                        -families $families \
                        -action listcond \
                        -sectors $sectors} results]} {
            if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem waiting for conditioning to finish\n$results"] == 1} {
                APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
            }
        }
        set count [llength $results]
        while {$count > 0} {
            APSMpStep "$count Power Supplies conditioning"
            if {[catch {APSUSrDcpsAction \
                            -families $families \
                            -action listcond \
                            -sectors $sectors} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem waiting for conditioning to finish\n$results"] == 1} {
                    APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
                }
            }
            set count [llength $results]
            APSWaitWithUpdate -waitSeconds 5
        }
    }

    #Note the degaussed PS are ramped when using the setFromSCR action.
    APSMpStep "Setting final setpoints for Power Supplies"
    
    if {[catch {APSUSrDcpsAction \
                    -families $families \
                    -action setFromSCR \
                    -filter $filter \
                    -sectors $sectors \
                    -SCRFile $ShortFilename} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSUMpSRUpDownDoubleSector: Problem setting final setpoints for Power Supplies\n$results"] == 1} {
            APSMpReturn error "APSUMpSRUpDownDoubleSector: $results"
        }
    }

    if {0} {
        if {$CM} {
            if {$gapsWereOpened} {
                APSAlertBox .alert -type warning -errorMessage "The ID Gaps were opened to facilitate conditioning the canted dipoles. Please ensure you restore the ID gaps to teh desired settings."
                #catch {APScavput -list=ID:CloseDevice=1 -blunderAhead -pend=5}
            }
        }
    }

    APSMpReturn ok
}
