#
# $Log: not supported by cvs2svn $
# Revision 1.57  2011/02/24 22:03:13  shang
# commented out start old bcontrol since it is not in use now.
#
# Revision 1.56  2010/10/27 18:18:04  soliday
# Updated the description of the APSMpBoosterPSSetFullPower machine procedure.
#
# Revision 1.55  2010/10/08 15:22:26  soliday
# Reduced the time between gain setpoints per CY's request.
#
# Revision 1.54  2008/10/29 17:07:28  soliday
# Updated code to check for ? in results from cavget before using the
# results in an if statement.
#
# Revision 1.53  2007/03/14 15:44:47  soliday
# Added a few more APSMpStep commands to log more information that would
# help me diagnose a possible problem.
#
# Revision 1.52  2007/03/01 17:24:27  soliday
# Added missing calls to APSLogScriptAction to store initialization values.
#
# Revision 1.51  2006/12/19 16:46:00  soliday
# Changed the procedure name of loadSafetyRamps to loadSafetyRamps2 because
# it was conflicting with a procedure of the same name in
# BRampControlAutoCorrection.tcl that accepted different arguments.
#
# Revision 1.50  2006/09/28 21:20:49  soliday
# Adjusted how it checks the ACIS PVs per Sereno's request.
#
# Revision 1.49  2006/05/22 21:55:11  soliday
# Added checks for acis inhibit and acis trips.
#
# Revision 1.48  2006/01/27 16:57:04  soliday
# Fixed an issue when running APSMpBoosterPSSetFullPower if BControl is
# off and the slope and zeros are enabled.
#
# Revision 1.47  2005/08/26 21:53:15  soliday
# Changed the way the AFG triggers are reset prior to starting BControl.
#
# Revision 1.46  2005/07/18 20:05:44  soliday
# Temporarily removed today's changes until Nick can explain what is happening.
# It seems that the AFG triggers are being reset twice which I cannot fully
# explain.
#
# Revision 1.45  2005/07/18 19:59:42  soliday
# Readded resetting AFG triggers but this time added a 10 seconds pause after it
# ran.
#
# Revision 1.44  2005/07/18 19:39:00  soliday
# Removed last change until it can be tested further.
#
# Revision 1.43  2005/07/18 18:47:44  soliday
# Updated last change to only modify the AFG triggers of the magnets that were
# selected.
#
# Revision 1.42  2005/07/18 18:23:01  soliday
# Added procedure prior to starting bcontrol that sets the AFG triggers
# based on the difference from the zero reference setpoint and readback.
#
# Revision 1.41  2005/04/07 16:28:39  soliday
# Updated to identify limited save files and not allow the operator to use them.
#
# Revision 1.40  2005/03/02 23:22:27  soliday
# Suspends the auto ramp correction at the beginning and resumes it at the end.
# It is smart enough to resume in using the existing BRampControlAutoCorrection
# script on chaos using sockets. If this fails it trys the localhost. If this
# fails it start BRampControlAutoCorrection on the local host and then uses
# sockets to communicate with it. And if this fails it runs BRampAutoCorr without
# BRampControlAutoCorrection.
#
# Revision 1.39  2004/10/28 15:48:15  soliday
# Updated the descriptions per Sereno's request.
#
# Revision 1.38  2004/10/21 16:36:52  soliday
# Updated the descriptions for the machine procedures to the descriptions given
# to me by Nick Sereno.
#
# Revision 1.37  2004/10/08 15:03:10  soliday
# Updated the description.
#
# Revision 1.36  2004/10/07 20:52:04  soliday
# Updated so that the supplies are checked to see if the related IOC was rebooted.
# If so it brings them back into a valid state before continuing.
#
# Revision 1.35  2004/04/16 20:23:37  soliday
# Added checks for the ramp timing PVs prior to starting the supplies.
#
# Revision 1.34  2004/04/15 20:21:15  soliday
# Added additional safety checks prior to starting the PS.
#
# Revision 1.33  2004/04/14 20:57:56  soliday
# Streamlined code and added a few additional safety checks. Also reduced
# the number of channel access search requests.
#
# Revision 1.32  2003/09/23 20:00:05  soliday
# Fixed problem with sddsprocess command.
#
# Revision 1.31  2003/08/21 14:48:49  soliday
# Cleaned up the code a little.
#
# Revision 1.30  2003/05/30 20:53:22  soliday
# Fixed error message when burtwb does not work.
#
# Revision 1.29  2003/04/18 21:55:18  soliday
# Changed so that it does not restore BTS:[AB]BCurrentAO
#
# Revision 1.28  2003/04/18 21:16:32  soliday
# Fixed bug with recovery from beam loss mode.
#
# Revision 1.27  2003/01/27 20:13:06  soliday
# Modified so that the AFG Gain at full power is retrieved from the SCR file.
#
# Revision 1.26  2002/10/04 14:57:39  soliday
# Added the SCR restore feature to APSMpBoosterPSSetFullPower
#
# Revision 1.25  2002/10/02 21:10:37  soliday
# Modified after PEM tests before the new run.
#
# Revision 1.24  2002/07/12 14:59:19  soliday
# Improved dialog message.
#
# Revision 1.23  2002/07/12 14:52:31  soliday
# Increase a pause time.
#
# Revision 1.22  2002/07/12 14:44:50  soliday
# Fixed a problem when the ramps are still on but the power is off.
#
# Revision 1.21  2002/07/10 14:35:13  soliday
# Another minor change.
#
# Revision 1.20  2002/07/09 17:21:06  soliday
# Another minor change.
#
# Revision 1.19  2002/07/09 15:54:17  soliday
# Made a very minor modification
#
# Revision 1.18  2001/05/29 16:21:40  soliday
# Changed the action variable to action2 because of a conflict.
#
# Revision 1.17  2001/01/26 16:31:34  soliday
# Fixed a problem with the last change.
#
# Revision 1.16  2001/01/26 14:58:52  soliday
# Changed state variable to avoid conflicts.
#
# Revision 1.15  2000/11/29 22:08:28  soliday
# Clarified some APSMpSteps
#
# Revision 1.14  1999/12/13 21:22:38  soliday
# Added description lines.
#
# Revision 1.13  1999/11/24 17:19:38  soliday
# It now checks for DC mode
#
# Revision 1.12  1999/09/21 22:36:11  soliday
# Added a warning if the time or steps are changed.
#
# Revision 1.11  1999/09/21 20:47:30  soliday
# Added a new mode for going to full power from a beam loss.
#
# Revision 1.10  1999/09/21 15:30:46  soliday
# Changed warm startup time to 6 minutes with 6 steps
#
# Revision 1.9  1999/07/09 15:57:01  soliday
# Changed warm startup time to 5 minutes
#
# Revision 1.8  1999/07/09 15:46:03  soliday
# Changed cold startup time to 25 minutes
#
# Revision 1.7  1999/04/30 23:01:51  soliday
# Added log to script
#

# Sets selected booster power supplies ramping at full power.  Full
# power mode represents beam acceleration to 7 GeV.  The procedure
# starts the supplies from a cold start or from a warm or standby
# condition.  In the case of a cold start, each selected supply is
# stepped to full power in 6 steps that take a total of 25 minutes.
# In the case of going to full power from standby or any other ramping
# mode (defined as AFG gain = 0.4 and supply ramping), each supply is
# brought to full power in 6 steps in 6 minutes.

# Procedure gives information overview for APSMpBoosterPSSetFullPower.

proc APSMpBoosterPSSetFullPowerInfo {} {

    return "For information about common safeguards and check please refer to OPSDoc_Boo_PEM001 under required reading.

Brings the selected supply(s) to full ramping power from any state.  The operator is asked to choose one of two initial power supply states:  \"Cold Start\"or \"Standby\".  \"Cold Start\" should be chosen if the supply has been off for more than 60 minutes.  This procedure will take 12 minutes to bring the supply to full power in this case.  Typically, \"Cold Start\" is only used after a long shutdown so that the supply is warmed up gradually.  \"Standby\" should be chosen when the supplies have either been in ramping or DC standby or the supply has been off for less than 60 minutes.  The supply will be brought up to full power in 6 minutes when \"Standby\" is chosen. If the supply trips off due to some internal cause, attempts to bring it up should be done slowly using \"Cold Start\" and/or in consultation with the power supply group.  The \"Total starting time\" and \"Number of steps\" defaults for each initial state can be changed from the operator dialog but should only be changed with permission from the PS group.

This machine procedure also requires the operator to select an SCR file which defaults to the Bcontrol parameter selection.  The Bcontrol parameters are required because they determine the booster operational lattice for full power operation.
"

}

# Procedure provides a dialogbox to select booster magnet supplies.

proc APSMpBoosterPSSetFullPowerDialog {frame} {
    global status
    set forig $frame
    pack [frame $frame.top]
    set frame $frame.top

    APSMpStep "Select booster power supplies..."
    APSCheckButtonFrame .magnetSelectButton -parent $frame -label "Select magnet\npower supplies" \
        -variableList {APSMpBoosterPSSetFullPower(BM)    \
                           APSMpBoosterPSSetFullPower(QF)  \
                           APSMpBoosterPSSetFullPower(QD)  \
                           APSMpBoosterPSSetFullPower(SF-U)  \
                           APSMpBoosterPSSetFullPower(SD)} \
        -buttonList {BM QF QD SF-U SD/SDU} \
        -allNone 1 \
        -gridPack "-column 0 -row 0 -columnspan 2 -padx .05i"

    APSRadioButtonFrame .bindTime -parent $frame -label "Present state of\npower supplies" \
	-variable APSMpBoosterPSSetFullPower(coldStart) \
	-buttonList {"Cold Start" "Standby"} \
	-valueList {1 0} \
	-contextHelp "Choose the current state." \
	-gridPack "-column 2 -row 0 -columnspan 2 -sticky n -padx .05i"

    bind $frame.bindTime.frame.button1 <Button-1> {set APSMpBoosterPSSetFullPower(startupTime) 12.0}
    bind $frame.bindTime.frame.button2 <Button-1> {set APSMpBoosterPSSetFullPower(startupTime) 6.0}

    APSLabeledOutput .timeSelectEntry -parent $frame -label "Total starting time (m):" \
	-textVariable APSMpBoosterPSSetFullPower(startupTime) -width 9 \
	-gridPack "-column 0 -row 1 -columnspan 3"

    APSLabeledOutput .stepsSelectEntry -parent $frame -label "        Number of Steps:" \
	-textVariable APSMpBoosterPSSetFullPower(startupSteps) -width 9 \
	-gridPack "-column 0 -row 2 -columnspan 3"

    APSButton .changeDefaultTime -parent $frame -text "Change" \
	-gridPack "-column 3 -row 1" -command "if {\[tk_messageBox -message {This value should only be changed when permission has been attained} -type okcancel\] == {ok}} \"$frame.timeSelectEntry.entry configure -state normal -relief sunken\" "

    APSButton .changeDefaultSteps -parent $frame -text "Change" \
	-gridPack "-column 3 -row 2" -command "if {\[tk_messageBox -message {This value should only be changed when permission has been attained} -type okcancel\] == {ok}} \"$frame.stepsSelectEntry.entry configure -state normal -relief sunken\" "

    pack [frame $forig.bottom]
    set frame $forig.bottom

    APSCheckButtonFrame .categorys -parent $frame -label "Select SCR categories\nto restore" \
	-variableList {APSMpBoosterPSSetFullPower(SCRAFG)    \
			   APSMpBoosterPSSetFullPower(SCRBPM)  \
			   APSMpBoosterPSSetFullPower(SCRBcontrol)  \
                           APSMpBoosterPSSetFullPower(SCRRampTiming)  \
			   APSMpBoosterPSSetFullPower(SCRDiag)  \
			   APSMpBoosterPSSetFullPower(SCRExtPulsedPS) \
			   APSMpBoosterPSSetFullPower(SCRExtTiming) \
			   APSMpBoosterPSSetFullPower(SCRGlobalParameter) \
			   APSMpBoosterPSSetFullPower(SCRInjPulsedPS) \
			   APSMpBoosterPSSetFullPower(SCRInjTiming) \
			   APSMpBoosterPSSetFullPower(SCRMainPS) \
			   APSMpBoosterPSSetFullPower(SCRReadback) \
			   APSMpBoosterPSSetFullPower(SCRScrapers) \
			   APSMpBoosterPSSetFullPower(SCRSetpoint) \
			   APSMpBoosterPSSetFullPower(SCRStatus) \
			   APSMpBoosterPSSetFullPower(SCRSteeringPS) \
			   APSMpBoosterPSSetFullPower(SCRSteeringSetpoint) \
			   APSMpBoosterPSSetFullPower(SCRTiming) \
			   APSMpBoosterPSSetFullPower(SCRTuneMeas)} \
	-buttonList {AFG BPM Bcontrol RampTiming Diag ExtPulsedPS ExtTiming GlobalParameter InjPulsedPS InjTiming MainPS Readback Scrapers Setpoint Status SteeringPS SteeringSetpoint Timing TuneMeas} \
        -limitPerRow 7 -orientation horizontal -allNone 1

    APSCheckButtonFrame .beamlines -parent $frame -label "Select SCR beamline\nto restore" \
	-variableList {APSMpBoosterPSSetFullPower(SCRBTS)    \
			   APSMpBoosterPSSetFullPower(SCRBooster)  \
			   APSMpBoosterPSSetFullPower(SCRPTB)  \
			   APSMpBoosterPSSetFullPower(SCRPTB1)  \
			   APSMpBoosterPSSetFullPower(SCRPTB2) \
			   APSMpBoosterPSSetFullPower(SCRPTB3)} \
	-buttonList {BTS Booster PTB PTB1 PTB2 PTB3} \
        -limitPerRow 7 -orientation horizontal -allNone 1

    return
}

# Sets selected booster power supplies ramping at full power.

proc APSMpBoosterPSSetFullPower {args} {
    global status

    set BM 0
    set QF 0
    set QD 0
    set SF-U 0
    set SF 0
    set SD 0
    set startupTime 12.0
    set startupSteps 6
    set coldStart 1
    set SCRFile ""
    set doRestore 1
    APSStrictParseArguments {BM QF QD SF-U SF SD startupTime startupSteps coldStart SCRFile doRestore}

    global execMode


    foreach n {SCRAFG SCRBPM SCRBcontrol SCRDiag SCRExtPulsedPS SCRExtTiming SCRGlobalParameter SCRInjPulsedPS SCRInjTiming SCRMainPS SCRReadback SCRScrapers SCRSetpoint SCRStatus SCRSteeringPS SCRSteeringSetpoint SCRTiming SCRTuneMeas} {
        set $n 0
    }
    if $SF {
        set SF-U 1
    }
    set SF 0
    set SCRBcontrol 1
    set SCRRampTiming 1
    foreach n {SCRBTS SCRBooster SCRPTB SCRPTB1 SCRPTB2 SCRPTB3} {
        set $n 0
    }
    set SCRBooster 1

    set arrayName APSBPSControlPS
    global $arrayName
    APSMpGenericPSArraySetup -arrayName $arrayName \
	-SCRFile $SCRFile -system booster

    APSMpStep init -promptDialog "APSMpGenericPSDialog -packProc APSMpBoosterPSSetFullPowerDialog -chooseSCR 1 -arrayName $arrayName -system Booster -frame " -vars {BM QF QD SF-U SD startupTime startupSteps coldStart SCRAFG SCRBPM SCRBcontrol SCRRampTiming SCRDiag SCRExtPulsedPS SCRExtTiming SCRGlobalParameter SCRInjPulsedPS SCRInjTiming SCRMainPS SCRReadback SCRScrapers SCRSetpoint SCRStatus SCRSteeringPS SCRSteeringSetpoint SCRTiming SCRTuneMeas SCRBTS SCRBooster SCRPTB SCRPTB1 SCRPTB2 SCRPTB3}
    #    APSMpStep init -promptDialog APSMpBoosterPSSetFullPowerDialog -vars {BM QF QD SF SD startupTime startupSteps coldStart}

    if {$execMode != "Automatic"} {
        if {[catch {APScavget -list=BOO-ACIS:MCR:ExtInhibitLedM,BOO-ACIS:BooMode:BpM -num -printErrors -pend=10} acisState]} {
            APSMpReturn error "APSMpBoosterPSSetFullPower: $acisState"
        }
        if {[lindex $acisState 1] != 1} {
            APSMpReturn error "APSMpBoosterPSSetFullPower: Booster is not in beam permit mode."
        }
        if {$BM} {
            if {[lindex $acisState 0] != 0} {
                set BM 0
                if {[APSPEMTKDialog .warningDialog -text "Booster is in an acis inhibit state. BM has been unselected"] == 1} {
                    APSMpReturn error "APSMpBoosterPSSetFullPower: Booster is in an acis inhibit state. BM has been unselected"
                }
            }
        }
    }

    set SCRFile $APSBPSControlPS(Filename)
    if {![file exists $SCRFile]} {
        APSMpReturn error "APSMpBoosterPSSetFullPower: No SCR file selected"
    }

    set paramString ""
    foreach param {BM QF QD SF-U SD startupTime startupSteps coldStart SCRAFG SCRBPM SCRBcontrol SCRRampTiming SCRDiag SCRExtPulsedPS SCRExtTiming SCRGlobalParameter SCRInjPulsedPS SCRInjTiming SCRMainPS SCRReadback SCRScrapers SCRSetpoint SCRStatus SCRSteeringPS SCRSteeringSetpoint SCRTiming SCRTuneMeas SCRBTS SCRBooster SCRPTB SCRPTB1 SCRPTB2 SCRPTB3 SCRFile} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction \
             -procedure APSMpBoosterPSSetFullPower \
             -action initialize \
             -state ok \
             -parameters $paramString}

    if {[catch {exec sdds2stream $SCRFile -parameter=SnapshotDescription -page=1 -noquotes} results]} {
        APSMpReturn error "APSMpBoosterPSSetFullPower:: Invalid SCR file"
    }    
    if {[string first "Limited save:" $results] != -1} {
        APSMpReturn error "APSMpBoosterPSSetFullPower:: LIMITED SAVE SCR files cannot be used for this procedure."
    }
    set SD-U 0
    if $SD {
        if [catch {exec cavget -list=B:SD-U:PoweredM -pend=10 -printErrors} SDstatus] {
            APSMpReturn error "APSMpBoosterPSSetFullPower: Error reading SD status: $SDstatus"
        }
        if {$SDstatus=="B:SD-U"} {
            set SD 0
            set SD-U 1
            APSMpStep "Set SD-U full power..."
           # if [catch {APSMpBoosterSDUSetFullPower -SCRFile $SCRFile -magnet SD-U} result] {
           #     APSMpReturn error "APSMpBoosterPSSetFullPower: error setting SD-U full power: $result"
           # }
            set idSD-U [APSMpParallel -procedure "APSMpBoosterSDUSetFullPower -SCRFile $SCRFile -magnet SD-U" \
                          -mode Automatic]
        }
    }
    if ${SF-U} {
        APSMpStep "Set SF-U full power..."
       # if [catch {APSMpBoosterSDUSetFullPower -SCRFile $SCRFile -magnet SF-U} result] {
       #     APSMpReturn error "APSMpBoosterPSSetFullPower: error setting SF-U full power: $result"
       # }
        set idSF-U [APSMpParallel -procedure "APSMpBoosterSDUSetFullPower -SCRFile $SCRFile -magnet SF-U" \
                      -mode Automatic]
    }
    
    if ${SD-U} {
        if [catch {APSMpJoin ${idSD-U}} results] {
            APSMpReturn error "Problem occurred while ramping SD-U to full power: $results"
        }
    }
    if ${SF-U} {
        if [catch {APSMpJoin ${idSF-U}} results] {
            APSMpReturn error "Problem occurred while ramping SF-U to full power: $results"
        }
    }
    set magnetlist {BM QF QD SD}
    set magnets ""
    foreach magnet $magnetlist {
        if [set $magnet] {
            lappend magnets $magnet
        }
    }
    if ![llength $magnets] {
        APSMpReturn ok
    }
    set standbyGainLevel 0.4
    foreach magnet $magnetlist {
        set ${magnet}gain $standbyGainLevel
    }
    set ItBsStartRamp2BsIpRngC ""
    if {[catch {exec sddsselect $SCRFile /home/helios/oagData/pem/booster/SCRFilterFile -match=ControlName -pipe=out | sdds2stream -column=ControlName,ValueString -pipe=in} results]} {
	APSMpReturn error "APSMpBoosterPSSetFullPower: Invalid SCR file"
    }
    foreach {controlName valueString} $results {
	if {$controlName == "B:BM:VoltageRT.GAIN"} {
	    set BMgain [format "%.5f" $valueString]
	} elseif {$controlName == "B:QF:VoltageRT.GAIN"} {
	    set QFgain [format "%.5f" $valueString]
	} elseif {$controlName == "B:QD:VoltageRT.GAIN"} {
	    set QDgain [format "%.5f" $valueString]
	} elseif {$controlName == "B:SF:VoltageRT.GAIN"} {
	    set SFgain [format "%.5f" $valueString]
	} elseif {$controlName == "B:SD:VoltageRT.GAIN"} {
	    set SDgain [format "%.5f" $valueString]
	} elseif {$controlName == "It:Bs:StartRamp2BsIpRngC"} {
	    set ItBsStartRamp2BsIpRngC $valueString
	}	
    }

    set magnets ""
    foreach m "BM QF QD SD" {
        if {[set $m]} {
            append magnets "$m "
        }
    }
    if {![llength $magnets]} {
        APSMpReturn ok
    }

    #Check for IOC reboot and reset if necessary
    APSMpStep "Check for IOC reboot and reset if necessary" -proc APSMpBoosterResetAfterIOCReboot
    if {[catch {APSMpBoosterResetAfterIOCReboot -BM $BM -QF $QF -QD $QD -SF 0 -SD $SD} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while checking for IOC reboot\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
        }
    }

    #Suspend Auto Ramp Correction Control
    APSMpStep "Suspend auto ramp correction control"
    foreach magnet $magnets {
	if {[catch {APScavput -list=B:${magnet}:AutoCorrectionControlRC.SUSP=Suspend} results]} {
	    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while suspending $magnet auto ramp correction\n$results"] == 1} {
		APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
	    }
	}
    }

    #Suspend bcontrol controllaws
    APSMpStep "Suspend bcontrol controllaws"
    foreach magnet $magnets {
	if {[catch {APScavput -list=B:${magnet}bcontrollawRC.SUSP=Suspend} results]} {
	    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while suspending $magnet bcontrol controllaw\n$results"] == 1} {
		APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
	    }
	}
    }

    #    set fullPowerAFGGainList {0.975 0.929 0.909 0.579 0.973}
    set fullPowerAFGGainList "$BMgain $QFgain $QDgain $SFgain $SDgain"
    
    set onStateList ""
    set rampStateList ""
    set BcontrolList ""
    set presentPowerAFGGainList ""
    set timeList ""
    set stepsList ""
    
    set listIndex 0
    foreach magnet $magnetlist {
	if {[catch {APScavget -list=B:${magnet}:StatusCALC -numerical -pendIoTime=20} powerOff]} {
	    APSMpReturn error "APSMpBoosterPSSetFullPower: $powerOff"
	}
	if {[catch {APScavget -list=It:Ddg4chan${listIndex}.GATE -numerical -pendIoTime=20} rampEnabled]} {
	    APSMpReturn error "APSMpBoosterPSSetFullPower: $rampEnabled"
	}
	if {$powerOff  == "?"} {
	    APSMpReturn error "APSMpBoosterPSSetFullPower: unable to read B:${magnet}:StatusCALC"
	}
	if {$rampEnabled == "?"} {
	    APSMpReturn error "APSMpBoosterPSSetFullPower: unable to read It:Ddg4chan${listIndex}.GATE"
	}
	
        if {$powerOff && !$rampEnabled && [set $magnet]} {
            lappend onStateList -${magnet} 1
            lappend rampStateList -${magnet} 1
	    lappend stepsList $startupSteps
	    lappend timeList $startupTime
	} elseif {$powerOff && $rampEnabled && [set $magnet]} {
            lappend onStateList -${magnet} 1
            lappend rampStateList -${magnet} 1
	    lappend stepsList $startupSteps
	    lappend timeList $startupTime
        } elseif {!$powerOff && !$rampEnabled && [set $magnet]} {
	    lappend onStateList -${magnet} 0
	    lappend rampStateList -${magnet} 1
	    lappend stepsList $startupSteps
	    lappend timeList $startupTime
	} else {
            lappend onStateList -${magnet} 0 
            lappend rampStateList -${magnet} 0
	    lappend stepsList $startupSteps
	    lappend timeList $startupTime
        }
	if {[set $magnet]} {
	    lappend BcontrolList -${magnet} 1
	} else {
	    lappend BcontrolList -${magnet} 0
	}
        incr listIndex
    }


    #Checking for valid ramp state
    set invalidmagnets ""
    set dcmodemagnetsfound 0
    foreach magnet "BM QF QD SD" {
        set invalidmag($magnet) 0
        set dcmodemag($magnet) 0
        if {[set $magnet]} {
            if {[catch {APScavget -list=B:${magnet}:StatusCALC -pendIoTime=20} onState]} {
                APSMpReturn error "APSMpBoosterPSSetFullPower: $onState"
            }
            set state [APSMpBoosterPSCheckForValidRampControlState -magnet $magnet]
            if {$state == 0} {
                lappend invalidmagnets $magnet
                set invalidmag($magnet) 1
            } elseif {($state == 2) && ($onState)} {
                #DC ramp control state and power supply is off
                set dcmodemagnetsfound 1
                set dcmodemag($magnet) 1
            }
            if {[catch {APSMpBoosterPSCheckRampTiming -magnet $magnet} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while checking for valid ramp timing values for $magnet \n$results"] == 1} {
                    APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
                }
                set results 0
            }
            #Ignore the ramp timing per CY's request
            #I do this by forcing results=1
            set results 1
            if {($results == 0) && ($onState)} {
                #invalid ramp timing and power supply is off
                if {[catch {APSMpBoosterPSResetRampTiming -magnet $magnet} results]} {
                    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem resetting the ramp timing for $magnet \n$results"] == 1} {
                        APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
                    }
                }
            } elseif {$results == 0} {
                #invalid ramp timing and power supply is on
                if {$invalidmag($magnet) != 1} {
                    lappend invalidmagnets $magnet
                    set invalidmag($magnet) 1
                }
            }
        }
    }
    if {$dcmodemagnetsfound} {
        #Loading safety ramps
        APSMpStep "Loading safety ramps" -proc loadSafetyRamps2
        if {[catch {loadSafetyRamps2 -BM $dcmodemag(BM) -QF $dcmodemag(QF) -QD $dcmodemag(QD) -SF 0 -SD $dcmodemag(SD)} results]} {
            if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while loading safety ramp for $magnet \n$results"] == 1} {
                APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
            }
        }
        #Set FreeWheel PVs to non-DC mode
        APSMpStep "Set FreeWheel PVs to non-DC mode" -proc APSMpBoosterPSSetFreeWheelPVs
        if {[catch {APSMpBoosterPSSetFreeWheelPVs -BM $dcmodemag(BM) -QF $dcmodemag(QF) -QD $dcmodemag(QD) -SF $dcmodemag(SF) -SD $dcmodemag(SD) -DC 0} results]} {
            if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while setting FreeWheel PVs to non-DC mode\n$results"] == 1} {
                APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
            }
        }
    }

    if {[string length $invalidmagnets] > 0} {
        if {[catch {APSMpBoosterPSSetNoPower -BM $invalidmag(BM) -QD $invalidmag(QD) -QF $invalidmag(QF) -SD $invalidmag(SD) -SF 0 } results]} {
            APSMpReturn error "The magnets: $invalidmagnets are not in a valid ramp state. Problem occured while turning off the magnets and load safety ramps. \n $results"
        }
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: The magnets: $invalidmagnets are not in a valid ramp states. They have been turned off and safety ramp have been loaded. You must now abort this procedure."] == 1} {
        }
        APSMpReturn error "APSMpBoosterPSSetFullPower: The magnets: $invalidmagnets are not in a valid ramp states."
        
    }

    if 0 {
#COMMENTED OUT AFTER THIS CAUSED PROBLEMS COMING OUT OF DC STANDBY MODE
        #Resume bcontrol controllaws
        APSMpStep "Resume bcontrol controllaws"
        foreach magnet $magnets {
            if {[catch {APScavput -list=B:${magnet}bcontrollawRC.SUSP=Resume} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while resuming $magnet bcontrol controllaw\n$results"] == 1} {
                    APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
                }
            }
        }
    }
    update

    #Turning on supplies
    APSMpStep "Turning on supplies that are not already on for the cold start condition." -proc APSMpBoosterPSOnOff
    if {[catch {eval APSMpBoosterPSOnOff $onStateList -state1 on} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while turning power supplies on\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
        }
    }

    #Enabling ramps
    APSMpStep "Enabling ramping at standby level for supplies that do not have ramping enabled." -proc APSMpBoosterPSEnableDisableRamps
    if {[catch {eval APSMpBoosterPSEnableDisableRamps $rampStateList -state1 enable -coldStart $coldStart} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while enabling ramps\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
        }
    }

    #Check if in DC mode
    APSMpStep "Check if magnets are in DC Standby mode" -proc APSMpBoosterPSCheckIfDCStandbyPower
    set DCRampList ""
    foreach magnet $magnetlist {    
	if {[set $magnet]} {
	    if {[catch {APSMpBoosterPSCheckIfDCStandbyPower -magnet $magnet} result]} {
                if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while checking if $magnet is in DC standby mode. Continuing will result in the PEM assuming that it is in DC mode and will attempt to bring it out of DC mode.\n$result"] == 1} {
                    APSMpReturn error "APSMpBoosterPSSetFullPower: $result"
                } else {
                    set result 1
                }
	    }
	    if {$result == 1} {
		append DCRampList "-${magnet} 1 "
	    }
	}
    }

    #Exit if in DC mode
    if {[llength $DCRampList]} {
	APSMpStep "Exit DC Standby Mode" -desc "Exit DC Standby Mode if needed" -proc APSMpBoosterPSExitDCStandbyPower
	if {[catch {eval APSMpBoosterPSExitDCStandbyPower $DCRampList -setStandby 0} results]} {
            APSMpReturn error "APSMpBoosterPSSetFullPower: Problem occurred while exiting DC standby mode\n$results"
	}
    }

    #Check to ensure VoltageRT.MODE PVs are in AUTO mode
    APSMpStep "Check to ensure VoltageRT.MODE PVs are in AUTO mode"
    set notInAutoList ""
    foreach magnet "BM QF QD SD" {
        if {[set $magnet]} {
            if {[catch {APScavget -list=B:${magnet}:VoltageRT.MODE} autoState]} {
                APSMpReturn error "APSMpBoosterPSSetFullPower: $autoState"
            }
            if {$autoState!="AUTO"} {
                lappend notInAutoList $magnet
            }
        }
    }
    if {$notInAutoList!=""} {
        APSMpReturn error "APSMpBoosterPSSetFullPower: Auto mode NOT activated for $notInAutoList."
    }

    #Ramp to full power
    set listIndex 0
    foreach magnet $magnetlist {
	if {[set $magnet]} {
	    if {[catch {APScavget -list=B:${magnet}:VoltageRT.GAIN -pendIoTime=20} presentPowerAFGGain]} {
		APSMpReturn error "APSMpBoosterPSSetFullPower: $presentPowerAFGGain"
	    }
#	    set timeSec [expr ( ( 60000.0 * [lindex $timeList $listIndex] ) / [lindex $stepsList $listIndex] ) - 6000 ]
	    set timeSec [expr (20000.0 * [lindex $timeList $listIndex])]
	    APSMpStep "Increase $magnet gain to [lindex $fullPowerAFGGainList $listIndex] ([expr {$timeSec / (1000.0 * [lindex $stepsList $listIndex]) }] seconds per step)" -desc "Increase magnet gain"
	    set id$magnet [APSMpParallel -procedure \
			       "APSMpBoosterPSSetFullPowerNormal -presentGain \
                               $presentPowerAFGGain -fullGain \
                               [lindex $fullPowerAFGGainList $listIndex] \
                               -magnet $magnet -time $timeSec \
                               -steps [lindex $stepsList $listIndex]" -mode Automatic]
	}
	incr listIndex
    }
    #    APSMpAbort all -onError 1
    foreach magnet $magnetlist {
	if {[set $magnet]} {
	    if {[catch {APSMpJoin [set id$magnet]} results]} {
                if {$results != "No Message"} {
                    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while ramping $magnet to full power\nPressing the Continue button will result in continuing without this supply \n$results"] == 1} {
                        APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
                    }
                }
                set $magnet 0
	    }
	}
    }

    #Restore slope and zero values
    APSMpStep "Restore Slope and Zero values"
    if {[catch {exec sddsprocess $SCRFile -pipe=out -match=column,ControlName=B:*RefAO \
                    | sdds2stream -pipe=in -columns=ControlName,ValueString} results]} {
        APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
    }
    set options ""
    set results [lsort [split $results \n]]
    if {[llength $results] != 10} {
        APSMpReturn error "APSMpBoosterPSSetFullPower: The SCR file is different then expected"
    }
    set index 0
    set index2 1
    foreach magnet "BM QD QF SD" {
        if {[set $magnet]} {
            set rampZeroRef($magnet) [lindex [lindex $results $index2] 1]
            lappend options [join [lindex $results $index] =]
            lappend options [join [lindex $results $index2] =]
        }
        incr index 2
        incr index2 2
    }
    if {[string length $options]} {
        if {[catch {APScavput -list=[join $options ,] -pendIoTime=25} results]} {
            if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Channel access problem while restoring slope and zero reference values\n$results"] == 1} {
                APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
            }
        }
    } else {
        APSMpStep "No power supplies selected"
        APSMpReturn error "APSMpBoosterPSSetFullPower: No power supplies selected"
    }
    APSWaitWithUpdate -waitSeconds 4

    #Check for Bcontrol locked state
    if 0 {
        set smallMagnetList {Bm Qf Qd Sf Sd}
        set listIndex 0
        foreach magnet $magnetlist {
            if {[set $magnet]} {
                if {[APScavget -list=B:${magnet}:BconLockedMBBO -pendIoTime=20 -numerical]} {
                    if {[catch {APScavget -list=It:Bs:[lindex $smallMagnetList $listIndex]VafgTrigAO.VAL -pendIoTime=20} trigger]} {
                        APSMpReturn error "APSMpBoosterPSSetFullPower: $trigger"
                    }
                    if {[catch {expr [APScavget -list=B:${magnet}:RampZeroAI -pendIoTime=20] - $rampZeroRef($magnet)} triggerDelta]} {
                        APSMpReturn error "APSMpBoosterPSSetFullPower: $triggerDelta"
                    }
                    if {[catch {APScavput -list=It:Bs:[lindex $smallMagnetList $listIndex]VafgTrigAO.VAL=[expr $trigger + $triggerDelta] -pendIoTime=25} results]} {
                        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Channel access problem while setting It:Bs:[lindex $smallMagnetList $listIndex]VafgTrigAO.VAL to [expr $trigger + $triggerDelta] \n$results"] == 1} {
                            APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
                        }
                    }
                }
            }
            incr listIndex
        }
    }
    #7/20/2015 comment out reset AFG trigger which works for V-Ramp mode, however, we are running I-Ramp mode now.
    #Reset AFG Triggers
    #APSMpStep "Reset AFG Triggers" -proc APSMpBoosterPSResetAFGTriggers
    #APSMpBoosterPSResetAFGTriggers -BM $BM -QF $QF -QD $QD -SF $SF -SD $SD
   
    APSWaitWithUpdate -waitSeconds 10

    #Resume bcontrol controllaws
    APSMpStep "Resume bcontrol controllaws"
    foreach magnet $magnets {
	if {[catch {APScavput -list=B:${magnet}bcontrollawRC.SUSP=Resume} results]} {
	    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while resuming $magnet bcontrol controllaw\n$results"] == 1} {
		APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
	    }
	}
    }
    update
    #load It:Bs:StartRamp2BsIpRngC  mode before restore SCR
    if {[llength $ItBsStartRamp2BsIpRngC] > 0} {
        APSMpStep "Restore 60Hz extended mode PV"
        if {[catch {APScavput -list=It:Bs:StartRamp2BsIpRngC=$ItBsStartRamp2BsIpRngC } results]} {
            if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while restoring It:Bs:StartRamp2BsIpRngC\n$results"] == 1} {
                APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
            }
        }
    }

    #Restore SCR values
    if ($doRestore) {
        set options ""
        set noptions 0
        set SCRBcontrol 1
        set SCRRampTiming 1
        foreach n {SCRAFG SCRBPM SCRBcontrol SCRRampTiming SCRDiag SCRExtPulsedPS SCRExtTiming SCRGlobalParameter SCRInjPulsedPS SCRInjTiming SCRMainPS SCRReadback SCRScrapers SCRSetpoint SCRStatus SCRSteeringPS SCRSteeringSetpoint SCRTiming SCRTuneMeas} m {AFG BPM Bcontrol RampTiming Diag ExtPulsedPS ExtTiming GlobalParameter InjPulsedPS InjTiming MainPS Readback Scrapers Setpoint Status SteeringPS SteeringSetpoint Timing TuneMeas} {
            if {[set $n]} {
                if {$noptions == 0} {
                    set options "-match=column,Category=$m"
                    incr noptions
                } else {
                    append options ",Category=${m},|"
                }
            }
        }
        
        set options2 ""
        set noptions 0
        foreach n {SCRBTS SCRBooster SCRPTB SCRPTB1 SCRPTB2 SCRPTB3} m {BTS Booster PTB PTB1 PTB2 PTB3} {
            if {[set $n]} {
                if {$noptions == 0} {
                    set options2 "-match=column,Beamline=$m"
                    incr noptions
                } else {
                    append options2 ",Beamline=${m},|"
                }
            }
        }
        
        if {([string length $SCRFile]) && ([llength $options]) && ([llength $options2])} {
            APSMpStep "Booster: Restore SCR Data"
            set tmpFile /tmp/[APSTmpString]
            if {[catch {eval exec sddsprocess $SCRFile $tmpFile "-match=column,IsReadOnly=+y,!" "-match=column,IsProtected=+y,!" $options2 $options} result]} {
                APSMpReturn error "Error preparing data from $SCRFile for Booster: $result"
            }
            if {[catch {exec sddscasr -restore $tmpFile} result]} {
                APSPEMTKDialog .warningDialog -strings Continue -default 0 -text "APSMpBoosterPSSetFullPower: Problem restoring SCR file\n$result"
                catch {APSSendEMail -address soliday \
                           -subject "Problem restoring SCR file."  \
                           -message "Problem restoring SCR file\nAPSMpBoosterPSSetFullPower\n${SCRFile}\n$result"} 	    
            }
            file delete $tmpFile
        }   
    }

    #Resume Auto Ramp Correction Control
    APSMpStep "Resume auto ramp correction control"
    foreach magnet $magnets {
	if {[catch {APScavput -list=B:${magnet}:AutoCorrectionControlRC.SUSP=Resume} results]} {
	    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while resuming $magnet auto ramp correction\n$results"] == 1} {
		APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
	    }
	}
    }

    #Resume bcontrol controllaws
    APSMpStep "Resume bcontrol controllaws"
    foreach magnet $magnets {
	if {[catch {APScavput -list=B:${magnet}bcontrollawRC.SUSP=Resume} results]} {
	    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while resuming $magnet bcontrol controllaw\n$results"] == 1} {
		APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
	    }
	}
    }

    APSWaitWithUpdate -waitSeconds 2
    foreach magnet $magnets {
	if {[catch {APScavget -list=B:${magnet}:AutoCorrectionControlRC.RUN} results]} {
	    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while resuming $magnet auto ramp correction\n$results"] == 1} {
		APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
	    }
	    set results 1
	}
	if {$results != 1} {
            if {$magnet == "BM"} {
                set port 4583
            } elseif {$magnet == "QF"} {
                set port 4584
            } elseif {$magnet == "QD"} {
                set port 4585
            } elseif {$magnet == "SF"} {
                set port 4586
            } elseif {$magnet == "SD"} {
                set port 4587
            }
            #try to start it on chaos, if that does not work try to start
            #it on the localhost, if that does not work, physically start
            #BRampControlAutoCorrection on the localhost and then use the
            #socket to connect to it. If all else fails run BRampAutoCorr
            #without BRampControlAutoCorrection.
            if {![catch {socket chaos $port} sid]} {
                APSWaitWithUpdate -waitSeconds 5
            } elseif {![catch {socket localhost $port} sid]} {
                APSWaitWithUpdate -waitSeconds 5
            } else {
                catch {exec BRampControlAutoCorrection &}
                APSWaitWithUpdate -waitSeconds 5
                if {![catch {socket localhost $port} sid]} {
                    APSWaitWithUpdate -waitSeconds 5
                }
            }
            if {[catch {APScavget -list=B:${magnet}:AutoCorrectionControlRC.RUN} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while resuming $magnet auto ramp correction\n$results"] == 1} {
                    APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
                }
                set results 1
            }
            if {$results != 1} {                
                if {[catch {exec BRampAutoCorr -supply $magnet -triggerType rms &} result]} {
                    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetFullPower: Problem occurred while resuming $magnet auto ramp correction\n$results"] == 1} {
                        APSMpReturn error "APSMpBoosterPSSetFullPower: $results"
                    }
                }
            }
	}
    }
    APSMpStep "APSMpBoosterPSSetFullPower Done"
    
    APSMpReturn ok
}

proc APSMpBoosterPSSetFullPowerNormal {args} {
    set presentGain 0
    set fullGain 0
    set magnet ""
    set steps 6
    set time 174000
    APSStrictParseArguments {presentGain fullGain magnet steps time}
    if {$time < 2000} {
	set time 2000
    }
    set interval [expr ( $fullGain - $presentGain ) / $steps]

    for {set step 0} {$step<$steps} {incr step} {
	if {[expr ( $presentGain / $fullGain )]>=0.9} {
	    set presentGain $fullGain
	    set step $steps
	    set time 2000
	} else {
	    set presentGain [expr $presentGain + $interval]
	}
        APSMpStep "Ensure $magnet has not tripped" -desc "Ensure magnet has not tripped"
        if {[catch {APScavget -list=B:${magnet}:StatusCALC -pendIoTime=20} onState]} {
            APSMpReturn error "APSMpBoosterPSSetFullPowerNormal: $onState"
        }
        if {$onState} {
            if {[APSPEMTKDialog .warningDialog -text "Problem occurred while ramping $magnet to full power.\n$magnet appears to have tripped off. \nPressing the Continue button will result in continuing without this supply."] == 1} {
                APSMpReturn error "APSMpBoosterPSSetFullPower: Problem occurred while ramping $magnet to full power. $magnet appears to have tripped off."
            }
            APSMpReturn error "No Message"
        }
	APSMpStep "Increasing $magnet gain to $presentGain" -desc "Increase magnet gain"
        if {[catch {APSMpBoosterPSSetGain -value $presentGain -magnet $magnet} results]} {
            APSMpReturn error "APSMpBoosterPSSetFullPowerNormale: $results"
        }
        APSWaitWithUpdate -waitSeconds [expr round($time / (1000.0 * $steps))]
    }
    APSMpStep "Ensure $magnet has not tripped" -desc "Ensure magnet has not tripped"
    if {[catch {APScavget -list=B:${magnet}:StatusCALC -pendIoTime=20} onState]} {
        APSMpReturn error "APSMpBoosterPSSetFullPowerNormal: $onState"
    }
    if {$onState} {
        if {[APSPEMTKDialog .warningDialog -text "Problem occurred while ramping $magnet to full power.\n$magnet appears to have tripped off. \nPressing the Continue button will result in continuing without this supply."] == 1} {
            APSMpReturn error "APSMpBoosterPSSetFullPower: Problem occurred while ramping $magnet to full power. $magnet appears to have tripped off."
        }
        APSMpReturn error "No Message"
    }
    APSMpReturn ok
}
