# $Log: not supported by cvs2svn $
# Revison 1.17 2012/07/17 shang
# removed restore blades and offsets after xray bpm compare since it is not needed.
#
# Revision 1.15  2011/11/14 15:46:01  sajaev
# Added calibratedModels/lattices to the list of directories when
# switching the "default" link.
#
# Revision 1.14  2011/03/15 19:19:36  shang
# added update UBOP link after installing SR UBOP with/without P0 feedback reference, since now SR UBOP is a link to
# UBOP with/without P0 feedback.
#
# Revision 1.13  2010/12/01 17:43:57  shang
# added rfOrbitControllaw/lattices to the change default lattice list.
#
# Revision 1.12  2010/11/16 19:50:52  shang
# fixed a typo where the newFilePattern should be newFillPattern.
#
# Revision 1.11  2010/06/28 21:43:35  shang
# added missing argument (group) to APSMpIDRestoreXbpmRefGaps due to the recent update
#
# Revision 1.10  2010/04/20 14:58:38  shang
# modified to not return errors but display the error message of logMessage so that the pem can continue when logMessage has errors.
#
# Revision 1.9  2010/04/19 16:24:04  shang
# modified to use default as directory link for default lattice instead of public/default which is unnecessary now.
#
# Revision 1.8  2010/04/14 15:20:15  shang
# fixed typo in logMessage where "Houst" tag should be "Host" tag, and added "Directory" tag to defaultLatticeAudit log message.
#
# Revision 1.7  2010/04/07 14:30:50  shang
# fixed a typo in logMessage where the -sourceID should be -sourceId
#
# Revision 1.6  2010/04/05 19:21:03  shang
# added logMessage for each major step.
#
# Revision 1.5  2010/04/01 20:30:10  shang
# added log message for changing default lattice.
#
# Revision 1.4  2010/03/29 21:00:19  shang
# added steps to change lattice for pasting save-set into controllaw setpoint reference file field, suspending DP controllaw, opening RTFB loop, and asking user to inject
# to <newLattice>, <newFilePattern>, and then do orbit correction of DP and RTFB.
#
# Revision 1.3  2010/03/17 13:24:34  shang
# added option of open gaps to 180mm at the end of sanity check.
#
# Revision 1.2  2010/03/04 20:14:34  shang
# fixed a typo in the last step of standardization in FinalAdjustment and added option of restoring steering, pulsed magnets in proper position.
#
# Revision 1.1  2009/11/13 21:10:03  shang
# has been fully tested, first installation.
#

proc APSMpSRSwitchOrbitInitDialog {frame} {
    global APSMpSRSwitchOribt  APSMpSRSwitchOribt1  APSMpSRSwitchOribt2  APSMpSRSwitchOribt3 
    
    set APSMpSRSwitchOrbit(oldLattice) 24
    set APSMpSRSwitchOrbit(newLattice) 324
    APSRadioButtonFrame .old -parent $frame -variable APSMpSRSwitchOrbit(oldLattice) \
      -buttonList {24 324 Hybrid} -valueList {24 324 Hybrid} -orientation horizontal \
      -label "Previous User-operation lattice:"
    APSRadioButtonFrame .new -parent $frame -variable APSMpSRSwitchOrbit(newLattice) \
      -buttonList {24 324 Hybrid} -valueList {24 324 Hybrid} -orientation horizontal \
      -label "Switch-to lattice:             :"
    set frameList [APSTabFrame .tab -parent $frame -labelList {"Old SR SCR" "New SR SCR" "SRXrayBPM SCR" "SR gap SCR"} \
                     -width 900 -height 550]
    set labelList {"Old SR scr file (usually ubop)" "New SR scr file (new fill pattern from last time)" "SRXrayBPM scr file (after gap scans @15mm)" "SR scr file with user gaps with comment \"after switch to studies\""}
    set nameList {oldSRFile newSRFile SRXrayPMFile SRGapFile}
    set systemList {SR SR SRXrayBPM SR}
    set APSMpSRSwitchOrbit(ShortFilename) ""
    set APSMpSRSwitchOrbit1(ShortFilename) ""
    set APSMpSRSwitchOrbit2(ShortFilename) ""
    set APSMpSRSwitchOrbit3(ShortFilename) ""
    set APSMpSRSwitchOrbit(ShortFilename) [file tail [file readlink /home/helios/oagData/SCR/snapshots/SR/SR-UserBeamPreferred.gz]]
    
    for {set i 0} {$i<4} {incr i} {
        set parent [lindex $frameList $i]
        set label [lindex $labelList $i]
        set var [lindex $nameList $i]
        set system [lindex $systemList $i]
        APSLabel .label -parent $parent -text "Please select $label" -fgColor blue
        if $i==0 {
            APSAddSCRDialog .scr -parent $parent -system $system \
              -arrayName APSMpSRSwitchOrbit \
              -defaultFile $APSMpSRSwitchOrbit(ShortFilename)
        } else {
            APSAddSCRDialog .scr -parent $parent -system $system \
              -arrayName APSMpSRSwitchOrbit$i \
              -defaultFile [set APSMpSRSwitchOrbit${i}(ShortFilename)]
        }
    }
    

}

proc APSMpSRSwitchOrbitInfo {} {
    return "for switching orbit to change fill pattern."
}
proc APSMpSRSwitchOrbit {args} {
    global APSMpSRSwitchOrbit  APSMpSRSwitchOrbit1  APSMpSRSwitchOrbit2  APSMpSRSwitchOrbit3 env
    set oldLattice 24
    set newLattice 324
    set ShortFilename ""
    APSMpStep init -promptDialog APSMpSRSwitchOrbitInitDialog \
      -vars {oldLattice newLattice ShortFilename}
    
    if ![string length $oldLattice] {
        APSMpReturn error "The previous user-fill lattice was not selected."
    }
    if ![string length $newLattice] {
        APSMpReturn error "The new lattice (switch to) was not selected."
    }
    if {[string compare $oldLattice $newLattice]==0} {
        APSMpReturn error "The old and new lattice are the same, no need to switch orbit."
    }
    set oldSRFile $APSMpSRSwitchOrbit(ShortFilename)
    if ![string length $oldSRFile] {
        APSMpReturn error "The previous user-fill SR SCR file was not selected."
    }
    set newSRFile $APSMpSRSwitchOrbit1(ShortFilename)
    if ![string length $newSRFile] {
        APSMpReturn error "The new SR SCR file was not selected."
    }
    set SRXrayBPMFile $APSMpSRSwitchOrbit2(ShortFilename)
    if ![string length $SRXrayBPMFile] {
        APSMpReturn error "The SRXrayBPM SCR file was not selected."
    }
    set SRGapFile $APSMpSRSwitchOrbit3(ShortFilename)
    if ![string length $SRGapFile] {
        APSMpReturn error "The SR user gaps SCR file was not selected."
    }
    set oldLatticeDir nux36nuy19
    set newLatticeDir nux36nuy19
    
    switch $newLattice {
        24 {
            set newTopup 1
            set newFillPattern 24singlets
            set newCoggingPattern 24singlets
        }
        324 {
            set newTopup 0
            set newFillPattern 324singlets
            set newCoggingPattern 324singlets
        }
        Hybrid {
            set newTopup 1
            set newFillPattern hybrid
            set newCoggingPattern nocog
        }
    }
    switch $oldLattice {
        24 {
            set oldFillPattern 24singlets
            set oldCoggingPattern 24singlets
        }
        324 {
            set oldFillPattern 324singlets
            set oldCoggingPattern 324singlets
        }
        Hybrid {
            set oldFillPattern hybrid
            set oldCoggingPattern nocog
        }
    }
   
    set latticeLabel ${oldLattice}->${newLattice}
    switch $latticeLabel {
        24->324 -
        Hybrid->24 -
        Hybrid->324 {
            set chromChange -1
            set mode decrease
            set latticeChange 0
            set rampQuads 1
        }
        24->Hybrid -
        324->Hybrid -
        324->24 {
            set chromChange 1
            set mode increase
            set latticeChange 0
            set rampQuads 1
        }
        default {
            APSMpReturn error "Invalid old and new lattice combination -- $latticeLabel"
        }
    }
    
    APSMpStep "Initial Sanity Check."
    if [catch {exec logMessage -sourceId=orbitSwitchAudit \
                 -tag=User $env(USER) -tag=Host $env(HOST) \
                 -tag=OldLattice $oldLattice -tag=NewLattice $newLattice \
                 -tag=Action InitialSanityCheck } result] {
        APSMpStep "Error in log message for intial sanity check: $result"
    }
    if [catch {APSMpSRSanityCheck -mode initial -oldSRFile $oldSRFile -newSRFile $newSRFile \
                 -SRXrayBPMFile $SRXrayBPMFile -SRGapFile $SRGapFile -fillPattern $oldFillPattern } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Sanity check failed" -width 80 -type reminder\
                      -question "Sanity check failed -- $result\n Would you like to fix it manually and and then process the continue button to continue or abort?" \
                      -returnList {Continue Abort} -labelList {Fix-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRSwitchOrbit(1 - APSMpSRSanityCheck failed): $result"
        }
    }
    
    APSMpStep "Switch orbit: $latticeLabel"
    
    if $chromChange {
        APSMpStep "Change chromaticity"
        if [catch {exec logMessage -sourceId=orbitSwitchAudit \
                     -tag=User $env(USER) -tag=Host $env(HOST) \
                     -tag=OldLattice $oldLattice -tag=NewLattice $newLattice \
                     -tag=Action ChangeChromaticity } result] {
            APSMpStep "Error in log message for change chromaticity: $result"
        }
        if [catch {APSMpSRChangeChromaticity -mode $mode -rampQuads $rampQuads -presentFillPattern $oldFillPattern \
                     -newFillPattern $newFillPattern -newTopup $newTopup -newCoggingPattern $newCoggingPattern \
                     -newSRFile $newSRFile -SRGapFile $SRGapFile } result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Change chromaticity failed" -width 80 -type reminder\
                          -question "Change chromaticity failed -- $result\n Would you like to fix it manually and then press the continue button to continue or abort? t" \
                          -returnList {Continue Abort} -labelList {Fix-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSwitchOrbit(2 -- APSMpSRChangeChromaticity failed): $result"
            }
        }
    }
    if $latticeChange {
        APSMpStep "Change lattice:"
        if [catch {exec logMessage -sourceId=orbitSwitchAudit \
                     -tag=User $env(USER) -tag=Host $env(HOST) \
                     -tag=OldLattice $oldLattice -tag=NewLattice $newLattice \
                     -tag=Action ChangeLattice } result] {
            APSMpStep "Error in log message for change lattice: $result"
        }
        if [catch {APSMpSRChangeLattice -newSRFile $newSRFile -presentFillPattern $oldFillPattern \
                     -newFillPattern $newFillPattern -oldLatticeDir $oldLatticeDir -newLatticeDir $newLatticeDir } result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Change lattice failed" -width 80 -type reminder\
                          -question "Change lattice failed -- $result\n Would you like to fix it manually and then press the continue button to continue or abort? t" \
                          -returnList {Continue Abort} -labelList {Fix-It-Manually-And-Continue Abort}]
            
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSwitchOrbit(3 -- APSMpSRChangeLattice failed): $result"
            }
        }
    }
    
    APSMpStep "final adjustments"
    if [catch {exec logMessage -sourceId=orbitSwitchAudit \
                 -tag=User $env(USER) -tag=Host $env(HOST) \
                 -tag=OldLattice $oldLattice -tag=NewLattice $newLattice \
                 -tag=Action FinalAdjustments } result] {
        APSMpStep "Error in log message for final adjustments: $result"
    }
    if [catch {APSMpSRSwitchOrbitFinalAdjustment -newFillPattern $newFillPattern} result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Final adjustment failed" -width 80 -type reminder\
                          -question "Final adjustment failed -- $result\n Would you like to fix it manually and then press the continue button to continue or abort? t" \
                          -returnList {Continue Abort} -labelList {Fix-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRSwitchOrbit(4 - APSMpSRSwitchOrbitFinalAdjument failed): $result"
        }
    }
    #final SR SCR returned by APSMpSRSwitchOrbitFinalAdjustment, use this file as newSRFile for final sanity check (10/19/2018)
    set newSRFile $result
    APSMpStep "Final sanity check."
    if [catch {exec logMessage -sourceId=orbitSwitchAudit \
                 -tag=User $env(USER) -tag=Host $env(HOST) \
                 -tag=OldLattice $oldLattice -tag=NewLattice $newLattice \
                 -tag=Action FinalSanityCheck } result] {
        APSMpStep "Error in log message for final sanity check: $result"
    }
    if [catch {APSMpSRSanityCheck -mode final -fillPattern $newFillPattern -oldSRFile $oldSRFile -newSRFile $newSRFile \
                 -SRGapFile $SRGapFile -SRXrayBPMFile $SRXrayBPMFile } result] {
         set answer [APSMultipleChoice .warning -modal 1 -name "Final sanity check failed" -width 80 -type reminder\
                          -question "Final sanity check failed -- $result\n Would you like to fix it manually and then press the continue button to continue or abort? t" \
                          -returnList {Continue Abort} -labelList {Fix-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRSwitchOrbit(5 -- final sanity check faile): $result"
        }
    }
    if [catch {exec logMessage -sourceId=orbitSwitchAudit \
                 -tag=User $env(USER) -tag=Host $env(HOST) \
                 -tag=OldLattice $oldLattice -tag=NewLattice $newLattice \
                 -tag=Action done } result] {
        APSMpStep "Error in log message for orbit switch: $result"
    }
    APSMpReturn ok
}

proc APSMpSRSanityCheck {args} {
    set oldSRFile ""
    set newSRFile ""
    set SRXrayBPMFile ""
    set SRGapFile ""
    set mode initital
    set fillPattern ""
    APSParseArguments {oldSRFile newSRFile SRXrayBPMFile SRGapFile mode fillPattern}
    
    if {$mode=="initial"} {
        APSMpStep "Step 1: restore ubop file using standardization."
	if [APSYesNoPopUp "Do you need to standardize SR magnets to old SR SCR -- $oldSRFile?"] {
	    if [catch {APSMpSRConditionDoubleSector -forcecondition 0 -cycles 3 \
			   -S40:01 1 -S02:03 1 -S04:05 1 -S06:07 1 -S08:09 1 -S10:11 1 -S12:13 1\
			   -S14:15 1 -S16:17 1 -S18:19 1 -S20:21 1 -S22:23 1 -S24:25 1 -S26:27 1\
			   -S28:29 1 -S30:31 1 -S32:33 1 -S34:35 1 -S36:37 1 -S38:39 1 \
			   -ShortFilename $oldSRFile \
			   -dipole 0 -degauss 0 } result] {
                set answer [APSMultipleChoice .warning -modal 1 -name "Standardize SR magnets failed" -width 80 -type reminder\
                              -question "Standardize SR magnets failed -- $result\n Would you like to fix it manually and and then process the continue button to continue or abort? t" \
                              -returnList {Continue Abort} -labelList {Fix-It-Manually-And-Continue Abort}]
                if {$answer=="Abort"} {
                    APSMpReturn error "APSMpSRSanityCheck(1 - APSMpSRConditionDoubleSector): $result"
                }
            }
	}
        if [APSYesNoPopUp "Do you need to retore steering, pulse magnets and BPMs to old SR SCR -- $oldSRFile?"] {
            APSMpStep "Step 1a: restore steering, pulse magnets and BPMS from selected lattice."
            if [catch {exec sddsprocess /home/helios/oagData/SCR/snapshots/SR/$oldSRFile -pipe=out \
                        "-match=col,Category=BPM,Category=SteeringPS,|,Category=PulsedPS,|" \
                         | sddscasr -pipe=in -restore -pendIO=60} result] {
                set answer [APSMultipleChoice .warning -modal 1 -name "Restore steering, pulsed magnets and BPMS from $oldSRFile failed"  \
                              -width 80 -type reminder\
                              -question "Restore steering, pulsed magnets and BPMs from $oldSRFile failed -- $result\n Would you like to fix it manually and and then process the continue button to continue or abort? t" \
                              -returnList {Continue Abort} -labelList {Fix-It-Manually-And-Continue Abort}]
                if {$answer=="Abort"} {
                    APSMpReturn error "APSMpSRSanityCheck(1 - APSMpSRConditionDoubleSector): $result"
                }  
            }
        }
	set comment beginning
    } else {
	set comment final
    }
    APSMpStep "Step 2: inject into fill pattern $fillPattern..."
    set answer [APSMultipleChoice .warning -modal 1 -name "Insert fill pattern" -width 80 -type reminder\
		    -question "Manually inject into fill pattern - $fillPattern, press \"continue\" if done or \"Abort\" to abort" \
		    -returnList {Continue Abort} -labelList {Continue Abort}]
    if {$answer=="Abort"} {
	APSMpReturn error "APSMpSRSanityCheck was aborted!"
    }
    if {$fillPattern=="hybrid"} {
	set cog nocog
    } else {
	set cog $fillPattern
    }
    APSMpStep "Step 2a: start cogging..."
    if [catch {APSMpSRBTMSetup -cog $cog}  result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "BTM setup failed" -width 80 -type reminder\
                      -question "BTM setup failed -- $result\n Would you like to fix it manually and and then process the continue button to continue or abort? t" \
                      -returnList {Continue Abort} -labelList {Fix-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRSanityCheck(4a - APSMpSRBPMSetup - $cog): $result"
        }
    }
    APSMpStep "Step 3: Start defaultDP controllaw, rtfb."
    set answer [APSMultipleChoice .warning -modal 1 -name "Start DP controllaw"  -width 80 -type reminder \
		    -question "Start \[hv\].defaultDP controllaw, press \"continue\" if done or \"Abort\" to abort" \
		    -returnList "Continue Abort" -labelList {Continue Abort} ]
    if {$answer=="Abort"} {
	APSMpReturn error "APSMpSRSanityCheck was aborted!"
    }
    while {1} {
        if [catch {exec cavget -list=SRFB:GBL:Hor:CloseLoopBO,SRFB:GBL:Vert:CloseLoopBO -pend=10 -printErrors} rtfb] {
            set answer [APSMultipleChoice .warning -modal 1 -name "channel access error" -width 80 -type reminder\
                          -question "channel access error  -- $rtfb\n Unable to read RTFB status due to channel access problem, would you like to read it again or abort the pem?" \
                          -returnList {Read Abort} -labelList {Read-Again Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSanityCheck(4b - unable to read RTFB status): $rtfb"
            }
        } else {
            break
        }
    }
    set hRTFB [lindex $rtfb 0]
    set vRTFB [lindex $rtfb 1]
    
    if {[string compare $hRTFB "Close"]!=0 || [string compare $vRTFB "Close"]!=0} {
	APSMpStep "Step 0e: realtime feedback is not running, start it now."
	if [APSYesNoPopUp "Do you need to initialize the RTFB system before starting it?"] {
	    APSSetVarAndUpdate status "Initialize RTFB system ..."
	    set paramDir /home/helios/oagData/sr/rtfeedback/parameterFiles
	    set paramFile srfb-default.param
	    if [catch {APSMpInitializeRTFBSystem -statusCallback "APSSetVarAndUpdate status" \
                         -paramDir $paramDir -paramFile $paramFile -xconfigDir h.default \
                         -yconfigDir v.default } result] {
                set answer [APSMultipleChoice .warning -modal 1 -name "Initialize RTFB failed" -width 80 -type reminder\
                              -question "Initialize RTFB failed  -- $result\nWould you like to fix it manually and then continue or abort the pem?" \
                              -returnList {Continue Abort} -labelList {Fix-It-Manually-And-Continue Abort}]
                if {$answer=="Abort"} {
                    APSMpReturn error "APSMpSRSanityCheck(3 - Error in Initializing RTFB system): $result"
                }
	    }
	}
	global apshpFilterCutoffVert apshpFilterCutoffHoriz apshpFilterInitialVert apshpFilterInitialHoriz apshpFilterRampPoints apshpFilterRampInterval
	APSMpSetRTFBGlobalParameters -readonly 1
	if [catch {APSMpRTFBCloseLoops -hpFilterCutoffVert $apshpFilterCutoffVert \
		       -hpFilterCutoffHoriz $apshpFilterCutoffHoriz \
		       -hpFilterInitialVert $apshpFilterInitialVert \
		       -hpFilterInitialHoriz $apshpFilterInitialHoriz \
		       -hpFilterRampPoints $apshpFilterRampPoints \
		       -hpFilterRampInterval $apshpFilterRampInterval } result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "start RTFB failed" -width 80 -type reminder\
                          -question "start RTFB failed  -- $result\nWould you like to start it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Start-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSanityCheck(4 - Error in close RTFB loops): $result"
            }
	}
    }
    
    APSMpStep "Step 4: start topup if needed."
    set answer [APSMultipleChoice .warning -modal 1 -name "Start Topup"  -width 80 -type reminder \
		    -question "If fill pattern ($fillPattern) needs Top Up, please start Top Up, otherwise, click \"continue\" directly." \
		    -returnList "Continue Abort" -labelList {Continue Abort} ]
    if {$answer=="Abort"} {
	APSMpReturn error "APSMpSRSanityCheck was aborted!"
    }
    APSMpStep "Step 5: put gaps at 15 mm"
    while {1} {
        if [catch {exec cavget -list=S:ID:GapFeedForwardRC.RUN -printErrors} IDrunning] {
            set answer [APSMultipleChoice .warning -modal 1 -name "channel access error" -width 80 -type reminder\
                          -question "channel access error  -- $IDrunning\n Unable to read ID feedforward status due to channel access problem, would you like to read it again or abort the pem?" \
                          -returnList {Read Abort} -labelList {Read-Again Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSanityCheck(5): error in reading ID feedforward status: $IDrunning"
            }
        } else {
            break
        }
    }
    if !$IDrunning {
        APSMpStep "Start ID feedforward: "
        if [catch {APSMpIDOffsetFeedforward -action start} result] {
             set answer [APSMultipleChoice .warning -modal 1 -name "Start ID feedforward failed" -width 80 -type reminder\
                           -question "Start ID feedforward failed  -- $result\nWould you like to start it manually and then continue or abort the pem?" \
                           -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSanityCheck(6): unable to start ID feedforward: $result"
            }
        }
    }
    
    if [catch {APSMpIDRestoreXbpmRefGaps -group Both -orbitSwitch 1} result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Restore Xbpm referece gap failed" -width 80 -type reminder\
                      -question "Restore Xbpm reference gap failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRSanityCheck(7): unable to set ID gaps to 15mm: $result"
        }
    }
    #bring up gap feedforward medm status window
    APSMpIDOffsetFeedforwardStatus
    global userComment
    set userComment "15 mm gaps -- $comment of orbit switch."
    APSDialogBox .comm -name "Provide Comments for SCR" -width 100 \
	-cancelCommand "set userComment cancelled" 
    APSLabel .label -parent .comm.userFrame -text "Please wait until the gaps stop moving, and then click OK to do SCR save." -fgColor blue
    APSLabeledEntry .comment -parent .comm.userFrame -label "Comment:" -textVariable userComment -width 80
    tkwait window .comm
    if {$userComment=="cancelled"} {
         APSMpReturn error "APSMpSRSanityCheck(8) was cancelled."
    }
    APSMpStep "Step 6a: load RateP and offsetP from SRXrayBPM reference file $SRXrayBPMFile"
    set snapDir /home/helios/oagData/SCR/snapshots/SRXrayBPM
    set restore 0
    set tmpFile /tmp/[APSTmpString]
    if [catch {exec sddsprocess $snapDir/$SRXrayBPMFile $tmpFile.1 \
		   "-match=col,ControlName=*RateP,ControlName=*OffsetP"  } result] {
	set restore 0
    } else {
	set rows1 [exec sdds2stream -rows=bar $tmpFile.1]
	if {$rows1} {
	    set restore 1
	}
    }
    if $restore {
	APSMpStep "Step 6a: restore old blade offsets and rates."
	if [catch {exec sddscasr -restore $tmpFile.1 } result] {
	    set answer [APSMultipleChoice .warning -modal 1 -name "Restore blades offset and rates failed" -width 80 -type reminder\
			    -question "restore blades offset and rates from $SRXrayBPMFile failed -- $result\nWould like to do it manually and then continue or abort the pem?" \
			    -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSanityCheck(9a): $result"
            }
	}
    }
    
    APSMpStep "Step 6: SRXrayBPM SCR save."
    while {1} {
        if [catch {APSSaveMachine -machine SRXrayBPM \
                     -description $userComment} result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "SRXrayBPM SCR save failed" -width 80 -type reminder\
                          -question "SRXrayBPM SCR save failed  -- $result\nWould you like to do it again (automatically) or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Again Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSanityCheck(9): $result"
            }
        } else {
            break
        }
    }
    set snapshot [lindex $result 0]
   
    APSMpStep "Step 7: SCR compare."
    foreach plane {x y } {
	if [catch {APSSRXrayBPMCustomCompare -machine SRXrayBPM -snapshot1 $snapDir/$SRXrayBPMFile -snapshot2 $snapDir/$snapshot \
		       -snap1Label $SRXrayBPMFile -snap2Label $snapshot \
		       -Value1Label Dataset1 -Value2Label Dataset2 -DifferenceLabel Dtst2-Dtst1 \
                     -bpmType ID -plane $plane -gapcompare 0} result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "SRXrayBPM SCR compare failed" -width 80 -type reminder\
                           -question "SRXrayBPM SCR compare failed -- $result\nWould like to compare manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSanityCheck(9b): $result"
            }
	}   
    }
    #add ID gap compare
    if [catch {APSSRXrayBPMCustomCompare -machine SRXrayBPM -snapshot1 $snapDir/$SRXrayBPMFile -snapshot2 $snapDir/$snapshot \
                 -snap1Label $SRXrayBPMFile -snap2Label $snapshot \
                 -Value1Label Dataset1 -Value2Label Dataset2 -DifferenceLabel Dtst2-Dtst1 \
                 -bpmType ID -gapcompare 1} result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "SRXrayBPM SCR gap compare failed" -width 80 -type reminder\
                      -question "SRXrayBPM SCR compare gap setpoints  failed -- $result\nWould like to compare manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRSanityCheck(9c): $result"
        }
    }
    set answer [APSMultipleChoice .warning -modal 1 -name "SCR Compare" -type reminder -width 80 \
                  -question "Please check the compare results of freshly saved 15mm gap SCR with the reference SRXrayBPM SCR, \n\If changed the orbit through steering, SCR-SR save is required.\nPaste the save file into SROrbitControllaw setpoint refererence field.\npress \"continue\" if the results are ok or \"Abort\" to abort" \
		    -labelList {Continue Abort} -returnList {Continue Abort}]
    if {$answer=="Abort"} {
        APSMpReturn error "APSMpSRSanityCheck(10) was aborted!"
    }
    
    APSMpStep "Step 8: restore user gaps from SCR with comment \"after studies\"."
    if [catch {APSMpIDRestoreGapsFromSCR -ShortFilename $SRGapFile -orbitSwitch 1} result] {
    	set answer [APSMultipleChoice .warning -modal 1 -name "Restore user gaps error" -width 80 -type reminder\
			-question "Error occurred during restoring user gaps,\n$result\nWould you like to continue anyway or abort the pem?" \
			-returnList {Continue Abort} -labelList {Continue-Anyway Abort}]
    	if {$answer=="abort"} {
    	    APSMpReturn error "APSMpSRSanityCheck(11): $result"
    	}
    }
    
    APSMpStep "Step 9: start XRDP controllaw"
    set answer [APSMultipleChoice .warning -modal 1 -name "Start XRDP controllaw" -type reminder -width 80 \
		    -question "Start XRDP controllaw for both planes, press \"continue\" if done or \"Abort\" to abort" \
		    -returnList {Continue Abort} -labelList {Continue Abort}]
    if {$answer=="Abort"} {
        APSMpReturn error "APSMpSRSanityCheck(12) was aborted!"
    }
    #check if XRDP is running before transfer the setpoints
    while {1} {
        if [catch {exec cavget -list=DP:S:OrbitControlLaw -list=X,Y -list=SDDS.RUN -printErrors -pend=30} runList] {
            APSMpReturn error "APSMpSRSanityCheck(13): problem in reading DP controllaw pvs."
        }
        set xrun [lindex $runList 0]
        set yrun [lindex $runList 0]
        if {!$xrun && !$yrun} {
            set message "both plane XRDP orbitcorrection is not running."
        } elseif {!$xrun} {
            set message "x plane data pool orbitcorrection is not running."
        } elseif {!$yrun} {
            set messsage "y plane data pool orbitcorrection is not running."
        } else {
            set message ""
        }
        if [string length $message] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Orbit correction is not running" \
			    -question "$message, press \"re-check\" or \"Abort\" to abort" \
			    -returnList {Re-check Abort} -labelList {Re-check Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSanityCheck was aborted!"
            }
        } else {
            break
        }
    }
    APSMpStep "Step 10: transfer rf+bmx errors into setpoints."
    if [catch {APSSRTransferBPMSetpoint -plane both} result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "transfer BPM setpoint failed" -width 80 -type reminder\
                           -question "transfer BPM setpoint failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                           -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRSanityCheck(14 - transfer BPM setpoint failed): $result"
        }
    }
    global userComment1
    set userComment1 "After user gaps setpoint transfer, $fillPattern."
    APSDialogBox .comm -name "Provide Comments for SR SCR" -width 100 \
      -cancelCommand "set userComment1 cancelled" 
    APSLabeledEntry .comment -parent .comm.userFrame -label "Comment:" -textVariable userComment1 -width 80
    tkwait window .comm
    if {$userComment1=="cancelled"} {
        APSMpReturn error "APSMpSRSanityCheck(15) was cancelled."
    }
    APSMpStep "Step 11: SCR SR save"
    while {1} {
        if [catch {APSSaveMachine -machine SR \
                     -description $userComment1} result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "SR SCR save failed" -width 80 -type reminder\
                          -question "SR SCR save failed  -- $result\nWould you like to do it again or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Again Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSanityCheck(16): $result"
            }
        } else {
            break
        }
    }
    set snapshot [lindex $result 0]
    if {$mode=="initial"} {
	APSAlertBox .ok -type warning -errorMessage "Copy save-set into controllaw setpoint reference file field.(do not forget the .gz extension)." -name warning
    } else {
        APSMpStep "Compare corrector between the new SCR and Old SCR..."
        set compareChoices [list "APSSCRSRCompareConvertors -group H -readback 0" \
                              "APSSCRSRCompareConvertors -group V -readback 0"]
        if [catch {APSCompareMachine -machine SR -snapshot1 /home/helios/oagData/SCR/snapshots/SR/$oldSRFile -partial 0 \
                     -snapshot2 /home/helios/oagData/SCR/snapshots/SR/$snapshot -absoluteTolerance 0 \
                     -percentTolerance 0 \
                     -showSimilarities 0 \
                     -customComparisonList $compareChoices} result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "compare corrector failed" -type reminder\
                          -question "Compare Corrector failed  -- $result\nWould you like to do it manually and continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {do-it-manually-and-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSanityCheck(19 error compare correctors): $result"
            }
        }
        if [APSYesNoPopUp "Install UBOP?"] {
	    if [catch {APSSCRInstallPreferredFile -system SR -choice "User beam operator preferred" \
			   -filename $snapshot } result] {
                set answer [APSMultipleChoice .warning -modal 1 -name "Install SR UBOP failed" -width 80 -type reminder\
				-question "Install SR UBOP failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
				-returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
                if {$answer=="Abort"} {
                    APSMpReturn error "APSMpSRSanityCheck(17 - unable to install SR preference): $result"  
                }
	    }
	}
        #added install BPM offset reference -- 
        if [APSYesNoPopUp "Install BPM offset reference?"] {
            if [catch {APSSCRInstallPreferredFile -system SR -choice "BPM offset reference" \
                         -filename $snapshot } result] {
                set answer [APSMultipleChoice .warning -modal 1 -name "Install SR BPM offset reference failed" -width 80 -type reminder\
                              -question "Install SR BPM offset reference failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                              -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
                if {$answer=="Abort"} { 
                    APSMpReturn error "APSMpSRSanityCheck(17a - unable to install SR preference): $result"   
                }
            }
        }
        if [APSYesNoPopUp "Do you want to open the gaps at the end?"] {
            if [catch {APSMpIDRestoreGaps -gapfile SetGapTo180mm -closeInterval 0.1 -orbitSwitch 1} result] {
                set answer [APSMultipleChoice .warning -modal 1 -name "Open gaps failed" -width 80 -type reminder\
                              -question "Open gaps failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                              -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
                if {$answer=="Abort"} {
                    APSMpReturn error "APSMpSRSanityCheck(18 - unable to open gaps): $result"  
                }
            }
        }
    }
    APSMpReturn ok
}

proc APSMpSRChangeChromaticity {args} {
    set presentFillPattern ""
    set newFillPattern ""
    set newCoggingPattern ""
    set newTopup 1
    set newSRFile ""
    set mode increase
    set newSRFile ""
    set rampQuads 1
    set SRGapFile ""
    APSParseArguments {mode rampQuads presentFillPattern newFillPattern newCoggingPattern newTopup newSRFile SRGapFile}
    
    if {$mode=="increase"} {
	APSMpStep "Step1a: move gaps to 60mm."
	if [catch {APSMpIDRestoreGaps -gapfile  SetGapTo60mm -wait 1 -orbitSwitch 1} result] {
	    set answer [APSMultipleChoice .warning -modal 1 -name "Set 60mm gap failed" -width 80 -type reminder\
			    -question "set 180mm gap failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
			    -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
	    if {$answer=="Abort"} {
		APSMpReturn error "APSMpSRChangeChromaticity(1a -- open ID gaps to 180mm): $result"
	    }
	}
        APSMpStep "Step1: Ramp sextupoles (and quads if rampQuads=1) to new values ($newSRFile)"
	
        if [catch {APSSCRRampSRMagnets -doQuads $rampQuads -doSextoples 1 -SCRFile $newSRFile -machine SR } result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Ramp sextupoles failed" -width 80 -type reminder\
                          -question "Ramp sextupoles failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRChangeChromaticity(1 -- error in ramping sextupoles to new values): $result"
            }
        }
	set answer [APSMultipleChoice .warning -modal 1 -name "Continue or Abort?" -width 80 -type reminder\
			-question "You just ramped the sextoples, Would you like to continue or abort the pem (if beam was dumped)?" \
			-returnList {Continue Abort} -labelList {Continue Abort}]
	if {$answer=="abort"} {
	    APSMpReturn error "APSMpSRChangeChromaticity(1c): aborted"
	}
	
	APSMpStep "Step1c: restore gaps to user gaps."
	if [catch {APSMpIDRestoreGapsFromSCR -ShortFilename $SRGapFile -orbitSwitch 1} result] {
	    set answer [APSMultipleChoice .warning -modal 1 -name "Restore user gaps error" -width 80 -type reminder\
			    -question "Error occurred during restoring user gaps,\n$result\nWould you like to continue anyway or abort the pem?" \
			    -returnList {Continue Abort} -labelList {Continue-Anyway Abort}]
	    if {$answer=="abort"} {
		APSMpReturn error "APSMpSRChangeChromaticity(1d): $result"
	    }
	}
        APSMpStep "Step2: rf+bmx setpoint transfer"
        if [catch {APSSRTransferBPMSetpoint -plane both} result] {
             set answer [APSMultipleChoice .warning -modal 1 -name "transfer BPM setpoint failed" -width 80 -type reminder\
                          -question "Transfer BPM setpoint failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRChangeChromaticity(2 - transfer BPM setpoint failed): $result"
            }
        }
        set comments "User gaps $presentFillPattern, after ramping main power  supplies to $newFillPattern values"
        APSMpStep "Step3: SR SCR save, $comments"
        if [catch {APSSaveMachine -machine SR \
                     -description $comments} result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "SR SCR save failed" -width 80 -type reminder\
                          -question "SR SCR save (comments: $comments) failed  -- $result\nWould you like to do it again (automatically) or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Again Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRChangeChromaticity(3): $result"   
            }
        }
        APSMpStep "Step4: paste into controllaw setpoint reference file field. Don't forget the .gz extension."
        APSAlertBox .ok -type warning -errorMessage "Copy save-set into controllaw setpoint reference file [lindex $result 0] field (do not forget the .gz extension)." -name warning
    }
    APSMpStep "Step5: Open gaps to 180mm."
    if [catch {APSMpIDSetGapTo180mm } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Set 180mm gap failed" -width 80 -type reminder\
                      -question "set 180mm gap failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRChangeChromaticity(4 -- open ID gaps to 180mm): $result"
        }
    }
    APSInfoWindow .[APSTmpString] -infoMessage "Wait for the gaps move to 180mm" -modal 1
    set comments "Open gaps, orbit corrected, $presentFillPattern"
    APSMpStep "Step6: SR SCR save -- $comments"
    if [catch {APSSaveMachine -machine SR \
                     -description $comments} result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "SR SCR save failed" -width 80 -type reminder\
                          -question "SR SCR save failed (comments: $comments)  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRChangeChromaticity(5): $result"   
        }
    }
    APSMpStep "Step7: Stop RTFB and datapool orbit correction to avoid glitches during dump or injection."
    global apshpFilterCutoffVert apshpFilterCutoffHoriz apshpFilterInitialVert apshpFilterInitialHoriz apshpFilterRampPoints apshpFilterRampInterval
    APSMpSetRTFBGlobalParameters  -readonly 1
    if [catch {APSMpRTFBResetOpenLoops -hpFilterInitialVert $apshpFilterInitialVert \
                 -hpFilterInitialHoriz $apshpFilterInitialHoriz \
                 -runHloop 1 -runVloop 1 } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Stop RTFB failed" -width 80 -type reminder\
                      -question "Stop RTFB failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRChangeChromaticity(6 -- unable to stop RTFB): $result"
        }
    }
    #suspend datapool orbit correction
    foreach pl {X Y} {
        if [catch {APSSuspendSRControllaw -runControlPV DP:S:OrbitControlLaw${pl}SDDS } result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Suspend datapool orbit correction failed" -width 80 -type reminder\
                      -question "Suspend datapool orbit correction failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRChangeChromaticity(7 - suspendSRcontrollaw): $result"
            }
        }
    }
    APSMpStep "Step8: suspend RF frequency controllaw."
    if [catch  {exec cavput -list=S:rfFreqControlLawRC.SUSP=1 } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Suspend  RF frequency controllaw failed" -width 80 -type reminder\
                      -question "Suspend  RF frequency controllaw failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRChangeChromaticity(8): Unable to suspend rf frequency controllaw: $result"
        }
    }
    if [catch {exec cavget -list=Mt:TopUpAutoEnableC.VAL -num -printErrors } topupRunning] {
         set answer [APSMultipleChoice .warning -modal 1 -name "Reading topup indicator failed: $topupRunning" -width 80 -type reminder\
                      -question "Reading topup indicator failed  -- $topupRunning\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRChangeChromaticity(8): Unable to suspend rf frequency controllaw: $result"
        }
    }
    if $topupRunning {
        APSMpStep "Step9a: Stop topup..."
        set answer [APSMultipleChoice .warning -modal 1 -name "Abort Topup"  -width 80 -type reminder \
                      -question "Topup is ruuning, before dump the beam, please stop topup using \"ABORT\" button in SR injection control GUI (SRBunchTrain). Press Continue to continue after stopping topup or Abort to terminate the pem." \
                      -returnList "Continue Abort" -labelList {Continue Abort} ]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRChangeChromaticity(9a) was aborted!"
        }
    }
    APSMpStep "Step9: Dump beam."
    while {1} {
        if [catch {APSShutterPermitGiven} permit] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Check shutters permit failed" -width 80 -type reminder\
                      -question "check shutters permit failed  -- $result\nWould you like to continue anyway or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Continue-Anyway Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRChangeChromaticity(9 -DumpBeam:) $result"
            } else {
                break
            }
        }
        if $permit {
            set answer [APSMultipleChoice .warning -modal 1 -name "Check shutters" -width 80 -type reminder\
                          -question "Shutters are open. Shutters should be closed before dumping beam. Do you want to check again or continue anyway or  about?" \
                          -returnList {Check Continue Abort} -labelList {Check-Again Continue-Anyway Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRChangeChromaticity was aborted!"
            } elseif {$answer=="Continue"} {
                break
            }
        } else {
            break
        }
    }
    APSAlertBox .ok -type warning -errorMessage "Ready to dump beam now. Press ok to continue" -name warning
    if [catch {exec cavput -list=S:MPS:dumpBeamSQ=1 } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Dump beam failed" -width 80 -type reminder\
                      -question "Dump beam failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} { 
            APSMpReturn error "APSMpSRChangeChromaticity(9a -DumpBeam:) $result"
        }
    }
    APSMpStep "Step10: stop cogging and leave it stopped."
    if [catch {APSMpSRBTMSetup -cog nocog } result] {
         set answer [APSMultipleChoice .warning -modal 1 -name "Stop BPM cogging failed" -width 80 -type reminder\
                      -question "Stop BPM cogging failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                       -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} { 
            APSMpReturn error "APSMpSRChangeChromaticity(10 -stop cogging) $result"
        }
    }
    APSMpStep "Step11a: restore pulsed magent from new lattice."
    if [APSYesNoPopUp "Do you want to restore pulsed magent from new lattice?"] {
        if [catch {exec sddsprocess /home/helios/oagData/SCR/snapshots/SR/$newSRFile -pipe=out \
                     "-match=col,Category=PulsedPS" \
                     | sddscasr -pipe=in -restore -pend=60 } result] {
            return -code error $result
        }
    }
    APSMpStep "Step11: Inject new fill patter ($newFillPattern)"
    set answer [APSMultipleChoice .warning -modal 1 -name "Insert fill pattern" -width 80 -type reminder\
                  -question "Manually inject into fill pattern - $newFillPattern, press \"continue\" if done or \"Abort\" to abort" \
                  -returnList {Continue Abort} -labelList {Continue Abort}]
    if {$answer=="Abort"} {
        APSMpReturn error "APSMpSRChangeChromaticity(11) was aborted!"
    }
    APSMpStep "Step12: start cogging appropriately ($newCoggingPattern)"
    if [catch {APSMpSRBTMSetup -cog $newCoggingPattern} result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Start BPM cogging failed" -width 80 -type reminder\
                      -question "Start BPM cogging with new cogging pattern ($newCoggingPattern) failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} { 
            APSMpReturn error "APSMpSRChangeChromaticity(12): Unable to start new cogging - $newCoggingPattern: $result"
        }
    }
    
    if $newTopup {
        APSMpStep "Step13: Start topup."
        APSInfoWindow .[APSTmpString] -infoMessage "Press the START button in SRBunchTrain to start topup, and press OK after topup starts" -modal 1
    }
    APSMpStep "Step14: skip start RTFB."
    if {0} {
        APSMpStep "Step14: run RTFB."
        if [catch {APSMpRTFBCloseLoops -hpFilterCutoffVert $apshpFilterCutoffVert \
                     -hpFilterCutoffHoriz $apshpFilterCutoffHoriz \
                     -hpFilterInitialVert $apshpFilterInitialVert \
                     -hpFilterInitialHoriz $apshpFilterInitialHoriz \
                     -hpFilterRampPoints $apshpFilterRampPoints \
                     -hpFilterRampInterval $apshpFilterRampInterval } result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Start RTFB failed" -width 80 -type reminder\
                          -question "Start RTFB failed -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} { 
                APSMpReturn error "APSMpSRChangeChromaticity(14 - Error in close RTFB loops): $result"
            }
        }
    }
    APSMpStep "Step15: start \[hv\].tenSingularValues by pressing \"QUICK START\" button. Use the \"launch bpm adt\" button before starting any given configuration to prevent surprises  when controllaw wakes up."
    set answer [APSMultipleChoice .warning -modal 1 -name "Start \[hv\].tenSingularValues controllaw" -type reminder -width 80 \
                  -question " start \[hv\].tenSingularValues by pressing \"QUICK START\" button. Use the \"launch bpm adt\" button before starting any given configuration to prevent surprises  when controllaw wakes up. \n\nOptional Paste latest SR SCR file with good setpoints into controllaw setpoint reference file field.(do not forget the .gz extension) and do a full start. You may need to recalculated RT-DC overlap compensation if tenSingularValues is out of sync with rtfb.\n\nIf a bad orbit persists, try \[hv\].glennsSquareMatrix." \
                  -returnList {Continue Abort} -labelList {Continue Abort}]
    if {$answer=="Abort"} {
        APSMpReturn error "APSMpSRChangeChromaticity(15) was aborted!"
    }
    
    APSMpStep "Step18: rf+bmx _offset += errorcc transfer (keeping the setpoint the same) --transfer several times, and waiting each time for RTFB to forget to fight." -name warning
    set steps 1
    while {1} {
        APSMpStep "Transfer offset for the $steps time."
        if [catch {APSSRTransferOrbit -plane both -readFrom ErrorCC -xferTo OffsetAO -rfBpm 1 -bmBpm 0 -idBpm 0} result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "transfer orbit failed" -width 80 -type reminder\
                          -question "Transfer orbit  failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} { 
                APSMpReturn error "APSMpSRChangeChromaticity(18 -- transfer offset): $result"
            }
        }
        if ![APSYesNoPopUp "Do you want to transfer the offset again?"] {
            break
        }
        incr steps
    }
    APSMpStep "Step18a: start RTFB." 
    if [catch {APSMpRTFBCloseLoops -hpFilterCutoffVert $apshpFilterCutoffVert \
                 -hpFilterCutoffHoriz $apshpFilterCutoffHoriz \
                 -hpFilterInitialVert $apshpFilterInitialVert \
                 -hpFilterInitialHoriz $apshpFilterInitialHoriz \
                 -hpFilterRampPoints $apshpFilterRampPoints \
                 -hpFilterRampInterval $apshpFilterRampInterval } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Start RTFB failed" -width 80 -type reminder\
                      -question "Start RTFB failed -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} { 
            APSMpReturn error "APSMpSRChangeChromaticity(18a - Error in close RTFB loops): $result"
        }
    }
    APSMpStep "Step19: rf bpm \"x RF setpoint transfer\" (rf frequency controllaw)"
    if [catch {APSSRTransferOrbit -readFrom RfErrorM -xferTo RfSetpointP -rfBpm 1 -bmBpm 0 -idBpm 0 -plane x} result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "transfer x RT setpoint failed" -width 80 -type reminder\
                          -question "Transfer x RF setpoint  failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} { 
            APSMpReturn error "APSMpSRChangeChromaticity(19 -- x RF setpoint transfer): $result"
        }
    }
    
    APSMpStep "Step20: resume rf frequency controllaw."
    if [catch  {exec cavput -list=S:rfFreqControlLawRC.SUSP=0 } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Resume rf frequncey controllaw failed" -width 80 -type reminder\
                          -question "Resume rf frequncey controllaw failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} { 
            APSMpReturn error "APSMpSRChangeChromaticity(20): Unable to resume rf frequency controllaw: $result"
        }
    }
    
    set comments "After orbit correction with $newFillPattern"
    APSMpStep "Step 21: SR SCR save with comment \"$comments\"  and install as offset reference."
    while {1} {
        if [catch {APSSaveMachine -machine SR \
                     -description $comments} result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "SR SCR save failed" -width 80 -type reminder\
                          -question "SR SCR save failed  -- $result\nWould you like to do it again or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Again Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRChangeChromaticity(21): $result"   
            }
        } else {
            break
        }
    }
    #install as offset reference
    set snapshot [lindex $result 0]
    if [APSYesNoPopUp "Install BPM offset reference? If no, paste the saved file $snapshot into the offset reference field in SROrbitControllaw (do not recommend)"] {
        if [catch {APSSCRInstallPreferredFile -system SR -choice "BPM offset reference" \
                     -filename $snapshot } result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Install SR BPM offset reference failed" -width 80 -type reminder\
                          -question "Install SR BPM offset reference failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} { 
                APSMpReturn error "APSMpSRChangeChromaticity(21a - unable to install SR preference): $result"   
            }
        }
    }
    set snapshot [lindex $result 0]
    APSMpStep "Step22: start \[hv\].defaultDP with increased corrector range error limit, 50amps (to leave room for quad ramp)."
    set answer [APSMultipleChoice .warning -modal 1 -name "Start DP controllaw"  -width 80 -type reminder \
		    -question "Start \[hv\].defaultDP controllaw with increased corrector range error limit, 50amps (to leave room for quad ramp)" \
		    -returnList "Continue Abort" -labelList {Continue Abort} ]
    if {$answer=="Abort"} {
	 APSMpReturn error "APSMpSRChangeChromaticity(22) was aborted!"
    }
   
    if {$mode=="decrease"} {
        APSMpStep "Step23: ramp setupoles (and quadrupoles if rampQuads=1) to new values ($newSRFile)."
        if [catch {APSSCRRampSRMagnets -doQuads $rampQuads -doSextoples 1 -SCRFile $newSRFile -machine SR } result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Ramp sextupoles failed" -width 80 -type reminder\
                          -question "Ramp sextupoles failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRChangeChromaticity(23 -- error in ramping sextupoles to new values): $result"
            }
        }
        set comments "After ramping main power  supplies to $newFillPattern values"
        APSMpStep "Step24: SR SCR save, $comments"
        if [catch {APSSaveMachine -machine SR \
                     -description $comments} result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "SR SCR save failed" -width 80 -type reminder\
                          -question "SR SCR save ($comments) failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRChangeChromaticity(24): $result"   
            }
        }
    }
}

proc APSMpSRChangeLattice {args} {
    set newSRFile ""
    set newLatticeDir ""
    set oldLatticeDir ""
    set presentFillPattern ""
    set newFillPattern ""
    APSParseArguments {newSRFile newLatticeDir oldLatticeDir presentFillPattern newFillPattern}
    
    APSMpStep "Step1: stop RTFB to prevent it from going unstable in the new latticce."
    global apshpFilterCutoffVert apshpFilterCutoffHoriz apshpFilterInitialVert apshpFilterInitialHoriz apshpFilterRampPoints apshpFilterRampInterval
    APSMpSetRTFBGlobalParameters  -readonly 1
    if [catch {APSMpRTFBResetOpenLoops -hpFilterInitialVert $apshpFilterInitialVert \
                 -hpFilterInitialHoriz $apshpFilterInitialHoriz \
                 -runHloop 1 -runVloop 1 } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Stop RTFB failed" -width 80 -type reminder\
                      -question "Stop RTFB failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRChangeLattice(1 -- unable to stop RTFB): $result"
        }
    }
    
    APSMpStep "Step2: ramp quads to values from last approriate file ($newSRFile)"
    if [catch {APSSCRRampSRMagnets -doQuads 1 -doSextoples 0 -SCRFile $newSRFile -machine SR } result] {
         set answer [APSMultipleChoice .warning -modal 1 -name "Ramp quads failed" -width 80 -type reminder\
                          -question "Ramp quads to $newSRFile failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                       -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRChangeLattice(2 -- error in ramping sextupoles to new values): $result"
        }
    }
    
    APSMpStep "Step3: change all the soft links to $newLatticeDir."
    
    if [catch {APSSRSetDefaultLattice -newLattice $newLatticeDir -application SwitchOrbitPEM } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Set default lattice failed" -width 80 -type reminder\
                          -question "Set default lattice to $newLatticeDir failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRChangeLattice(3 - APSSRSetDefaultLattice): $result"
        }
    }
    
    APSMpStep "Step4: run the script CreateSRConfigForNewLattice to copy all the orbit correction configurations over to the new lattice subdirectories."
    if [catch {exec CreateSRConfigForNewLattice -newLattice $newLatticeDir -refLattice $oldLatticeDir } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Create SR config for new lattice failed" -width 80 -type reminder\
                          -question "Create SR config for new lattice failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRChangeLattice(4 -- error in creating configurations for new lattice): $result"
        }
    }
    
    APSMpStep "Step5: load RTFB response matrix, start RTFB"
    if [catch { APSMpRTFBLoadResponseMatrix } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Load RTFB response matrix failed" -width 80 -type reminder\
                          -question "Load RTFB response matrix failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRChangeLattice(5 -- load RTFB response matrix): $result"
        }
    }
    
    if [APSYesNoPopUp "Do you need to initialize the RTFB system before starting it?"] {
	APSSetVarAndUpdate status "Initialize RTFB system ..."
	set paramDir /home/helios/oagData/sr/rtfeedback/parameterFiles
	set paramFile srfb-default.param
	if [catch {APSMpInitializeRTFBSystem -statusCallback "APSSetVarAndUpdate status" \
                     -paramDir $paramDir -paramFile $paramFile -xconfigDir h.default \
                     -yconfigDir v.default } result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Initialize RTFB failed" -width 80 -type reminder\
                           -question "Initialize RTFB failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSanityCheck(3 - Error in Initializing RTFB system): $result"
            }
	}
    }
    global apshpFilterCutoffVert apshpFilterCutoffHoriz apshpFilterInitialVert apshpFilterInitialHoriz apshpFilterRampPoints apshpFilterRampInterval
    APSMpSetRTFBGlobalParameters -readonly 1
    if [catch {APSMpRTFBCloseLoops -hpFilterCutoffVert $apshpFilterCutoffVert \
		   -hpFilterCutoffHoriz $apshpFilterCutoffHoriz \
		   -hpFilterInitialVert $apshpFilterInitialVert \
		   -hpFilterInitialHoriz $apshpFilterInitialHoriz \
		   -hpFilterRampPoints $apshpFilterRampPoints \
		   -hpFilterRampInterval $apshpFilterRampInterval } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Start RTFB failed" -width 80 -type reminder\
                           -question "Start RTFB failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSanityCheck(4 - Error in close RTFB loops): $result"
            }
    }
    APSMpStep "Step6: do local steering."
    set answer [APSMultipleChoice .warning -modal 1 -name "Local Sterring" -type reminder -width 80 \
                  -question "Do local steering to recover source steering at affected sectors.\n\na) grab S33A:V4 and put it in maintenance mode.\nb) knob it until 33BM steering is restored.\nc) press \"init corr vector\" button in orbit controllaw GUI\nd) press \"enable vector mode\" button\ne) put S33A:V4 back in operation mode\n\nPress Continue when done or abort to abort the pem." \
		    -labelList {Continue Abort} -returnList {Continue Abort}]
    if {$answer=="Abort"} {
        APSMpReturn error "APSMpSRChangeLattice(6) was aborted!"
    }

    set comments "After ramping quads from $presentFillPattern to $newFillPattern"
    APSMpStep "Step7: SR SCR save - $comments"
    while {1} {
        if [catch {APSSaveMachine -machine SR \
                     -description $comments} result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "SR SCR save failed" -width 80 -type reminder\
                          -question "SR SCR save failed  -- $result\nWould you like to do it again or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Again Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRChangeLattice(7): $result"   
            }
        } else {
            break
        }
    }
    set snapshot [lindex $result 0]
    APSMpStep "Step7a: paste save-set into controllaw setpoint reference file field."
    APSAlertBox .ok -type warning -errorMessage "Copy save-set into controllaw setpoint reference file field.(do not forget the .gz extension)." -name warning
    APSMpStep "Step8: suspend DP and open RTFB loop."
    foreach pl {X Y} {
        if [catch {APSSuspendSRControllaw -runControlPV DP:S:OrbitControlLaw${pl}SDDS } result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Suspend datapool orbit correction failed" -width 80 -type reminder\
                          -question "Suspend datapool orbit correction failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRChangeLattice(8 - suspendSRcontrollaw): $result"
            }
        }
    }
    if [catch {APSMpRTFBResetOpenLoops -hpFilterInitialVert $apshpFilterInitialVert \
                 -hpFilterInitialHoriz $apshpFilterInitialHoriz \
                 -runHloop 1 -runVloop 1 } result] {
        set answer [APSMultipleChoice .warning -modal 1 -name "Stop RTFB failed" -width 80 -type reminder\
                      -question "Stop RTFB failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                      -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
        if {$answer=="Abort"} {
            APSMpReturn error "APSMpSRChangeLattice(9 -- unable to stop RTFB): $result"
        }
    }
    
    if [APSYesNoPopUp "Would you like to standardize magnets to the file saved in Step 7?"] {
        APSMpStep "Step9: standardize magnets to the file saved in Step 7."
        if [catch {APSMpSRConditionDoubleSector -forcecondition 0 -cycles 3 \
                     -S40:01 1 -S02:03 1 -S04:05 1 -S06:07 1 -S08:09 1 -S10:11 1 -S12:13 1\
                     -S14:15 1 -S16:17 1 -S18:19 1 -S20:21 1 -S22:23 1 -S24:25 1 -S26:27 1\
                     -S28:29 1 -S30:31 1 -S32:33 1 -S34:35 1 -S36:37 1 -S38:39 1 \
                     -ShortFilename $snapshot \
                     -dipole 0 -degauss 0 -standardizeQ 1 -standardizeS 1} result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Standardize magnets failed" -width 80 -type reminder\
                          -question "Standardize magnets to $snapshot failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRChangeLattice(10 - APSMpSRConditionDoubleSector): $result"
            }
        }
    }
    APSMpStep "Step 10:  inject to <newlattice> <newFillPattern>. Then do orbit correction (DP and RTFB)."
    APSAlertBox .ok -type warning -errorMessage "inject to $newLatticeDir $newFillPattern. Then do orbit correction (DP and RTFB)." -name warning
}

proc APSSRSetDefaultLattice {args} {
    set newLattice ""
    set application ""
    APSParseArguments {newLattice application}

    if ![string length $newLattice] {
        return -code error "the new lattice name is not provided."
    }
    global env
    set dataDir /home/helios/oagData/sr
    set directoryList {lattices localSteering/lattices \
                         orbitControllaw/lattices \
                         rfOrbitControllaw/lattices \
                         rtfeedback/lattices \
                         latticeFunctionCorrection/beta/lattices \
                         latticeFunctionCorrection/etay/lattices \
                         latticeFunctionCorrection/etax/lattices \
                         RTFB/FFwaveforms/lattices \
                         knobFiles \
			 calibratedModels/lattices}
    set errors 0
    foreach dir $directoryList {
        cd $dataDir/$dir
        set oldLattice [file tail [file readlink default]]
        if [catch {exec logMessage -sourceId=defaultLatticeAudit -tag=Directory $dataDir/$dir \
                     -tag=OldLattice $oldLattice \
                     -tag=NewLattice $newLattice -tag=Application $application \
                     -tag=Host $env(HOST) -tag=Action Start \
                     -tag=User $env(USER) } result] {
            APSMpStep "Error in logging default lattice changes start: $result"
        }
        if {[catch {exec rm default 
            exec ln -s $newLattice default} result]} {
            return -code error "Couldn't make link to $newLattice in directory $dir\n$result"
        }
        if [catch {exec logMessage -sourceId=defaultLatticeAudit -tag=Directory $dataDir/$dir \
                     -tag=OldLattice $oldLattice \
                     -tag=NewLattice $newLattice -tag=Application $application \
                     -tag=Host $env(HOST) -tag=Action Finish \
                     -tag=User $env(USER) } result] {
            APSMpStep "Error in logging default lattice changes finish: $result"
        }
        cd $dataDir/$dir
        if ![file exists $newLattice] {
            exec mkdir -p $newLattice
            file attributes $newLattice -permissions 0755
            set aclDirFile /home/helios/oagData/sr/lattices/dirs.acl  
        }
    }
}

proc APSMpSRSwitchOrbitFinalAdjustment {args} {
    set newFillPattern ""
    APSParseArguments {newFillPattern}

    set answer [APSMultipleChoice .warning -modal 1 -name "Adjust coupling and tunes" -width 80 -type reminder\
		    -question "Adjust coupling and tunes, press \"continue\" if done or \"Abort\" to abort" \
		    -returnList {Continue Abort} -labelList {Continue Abort}]
    if {$answer=="Abort"} {
	APSMpReturn error "APSMpSRSwitchOrbitFinalAdjustment was aborted!"
    }
    
    APSMpStep "Step2: make SR SCR save."
    while {1} {
        if [catch {APSSaveMachine -machine SR \
                     -description "Final save of $newFillPattern" } result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "SR SCR save failed" -width 80 -type reminder\
                          -question "SR SCR save failed  -- $result\nWould you like to do it again or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Again Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSwitchOrbitFinalAdjustment(1): $result"
            }
        } else {
            break
        }
    }
    
    set finalSRscr [lindex $result 0]
    if [APSYesNoPopUp "Do you need to standardize magnets to the SCR file save in previous step?"] {
        set snapshot [lindex $result 0]
        APSMpStep "Standardize magnets to $snapshot."
        if [catch {APSMpSRConditionDoubleSector -forcecondition 0 -cycles 3 \
                     -S40:01 1 -S02:03 1 -S04:05 1 -S06:07 1 -S08:09 1 -S10:11 1 -S12:13 1\
                     -S14:15 1 -S16:17 1 -S18:19 1 -S20:21 1 -S22:23 1 -S24:25 1 -S26:27 1\
                     -S28:29 1 -S30:31 1 -S32:33 1 -S34:35 1 -S36:37 1 -S38:39 1 \
                     -ShortFilename $snapshot \
                     -dipole 1 -degauss 0 -standardizeQ 1 -standardizeS 1} result] {
            set answer [APSMultipleChoice .warning -modal 1 -name "Standardize magnets failed" -width 80 -type reminder\
                          -question "Standardize magnets to $snapshot failed  -- $result\nWould you like to do it manually and then continue or abort the pem?" \
                          -returnList {Continue Abort} -labelList {Do-It-Manually-And-Continue Abort}]
            if {$answer=="Abort"} {
                APSMpReturn error "APSMpSRSwitchOrbitFinalAdjustment(2 - APSMpSRConditionDoubleSector): $result"
            }
        }
    }
    APSMpReturn $finalSRscr
}

proc APSSRTransferOrbit {args} {
    set plane ""
    set readFrom ""
    set xferTo ""
    set rfBpm 1
    set bmBpm 0
    set idBpm 0
    APSParseArguments {plane readFrom xferTo rfBpm bmBpm idBpm}
    
    if {$rfBpm==0 && $bmBPM==0 && $idBpm==0} {
        return -code error "APSSRTransferOrbit(1a): np bpms selected."
    }
    
    switch $plane {
        x -
        y {
        }
        both {
            set plane [list x y]
        }
        default {
            return -code error "APSSRTransferOrbit(1): Invalid plane - $plane."
        }
    }
  
    set matchOpt ""
    if !$bmBpm {
        append matchOpt " -match=col,DeviceName=*BM*,!"
    }
    if !$idBpm {
        append matchOpt " -match=col,DeviceName=*ID*,!"
    }
   
    if !$rfBpm {
	append matchOpt " -match=col,DeviceName=S*\\\[ABC\\\]:P?,!"
    }
    if [regexp {Rf} $xferTo] {
	append matchOpt " -match=col,DeviceName=S*C:P?,!"
    }
    if [catch {eval exec sddsprocess /home/helios/oagData/sr/BPMStatus/config.sdds -pipe=out \
                 -filter=column,NonexistentH,0,0 -filter=col,NonexistentV,0,0 $matchOpt \
                 | sdds2stream -pipe -column=DeviceName} bpmList] {
        return -code error "APSSRTransferOrbit(2): $bpmList"
    }
   
    set cavputList ""
    foreach pl $plane {
        if [catch {exec cavget -list=[join $bpmList ,] -list=:ms:${pl}:$readFrom } valList] {
            return -code error "APSSRTransferOrbit(3): $valList"
        }
        foreach bpm $bpmList val $valList {
            lappend cavputList ${bpm}:ms:${pl}:${xferTo}=$val
        }
    }
    if [catch {exec cavput -list=[join $cavputList ,] -deltaMode} result] {
        return -code error "APSSRTransferOrbit(3): $result"
    }
}
