proc APSMpSRChangeEnergyInfo {} {
    return "Please select SCR files that match the desired energy selected. Also you may need to change G:PW:RF-2:NewWaterSetPointAO to 87 degs for 7Gev and 83 degs for 6Gev. This is a two step process because there is a SET button that needs to be pressed."
}

proc APSMpSRChangeEnergyDialog {frame} {
    global status APSMpSRChangeEnergy

    frame ${frame}.f1
    pack ${frame}.f1 -fill x
    APSButton .launchSRSetDefaultLattice -parent ${frame}.f1 -text "Launch SRSetDefaultLattice" -command "exec SRSetDefaultLattice &"
    APSRadioButtonFrame .rb1 -parent $frame -label "Select Energy To Switch To" -buttonList "6Gev 7Gev" -valueList "6 7" -variable APSMpSRChangeEnergy(energy) -orientation horizontal
    APSRadioButtonFrame .rb2 -parent $frame -label "                Include SR" -buttonList "Yes No" -valueList "1 0" -variable APSMpSRChangeEnergy(includeSR) -orientation horizontal

    APSAddSCRDialog .scr -parent $frame -system SR -arrayName APSMpSRChangeEnergySR \
      -defaultFile $APSMpSRChangeEnergy(SRShortFilename)
    APSAddSCRDialog .scr2 -parent $frame -system Booster -arrayName APSMpSRChangeEnergyBooster \
      -defaultFile $APSMpSRChangeEnergy(BoosterShortFilename)

}

proc APSMpChangeEnergyExcludeSR {args} {

}

#This procedure has been placed in the attic
proc APSMpSRChangeEnergy {args} {
#Might need to change G:PW:RF-2:NewWaterSetPointAO to 87 for 7Gev and 83 for 6Gev
    global APSMpSRChangeEnergySR APSMpSRChangeEnergyBooster
    set energy 6
    set ShortFilename ""
    set SRShortFilename ""
    set BoosterShortFilename ""
    set includeSR 1
    APSMpStep init \
      -promptDialog APSMpSRChangeEnergyDialog \
      -vars "energy SRShortFilename BoosterShortFilename includeSR"

    if {$includeSR} {
        #Check SR SCR request file
        set SRShortFilename $APSMpSRChangeEnergySR(ShortFilename)
        if {![string length $SRShortFilename]} {
            APSMpReturn error "APSMpSRChangeEnergy: SCR file not choosen!"
        }
        if {![file exists /home/helios/oagData/SCR/snapshots/SR/$SRShortFilename]} {
            APSMpReturn error "SCR file $SRShortFilename not found"
        }
        if {[catch {exec sdds2stream /home/helios/oagData/SCR/snapshots/SR/$SRShortFilename -parameter=SnapshotDescription -page=1 -noquotes} results]} {
            APSMpReturn error "APSMpSRChangeEnergy: Invalid SCR file"
        }    
        if {[string first "Limited save:" $results] != -1} {
            APSMpReturn error "APSMpSRChangeEnergy: LIMITED SAVE SCR files cannot be used for this procedure."
        }
#        pv linkw "pv1 pv2 pv3 pv4" "SRF:K1:FB1:SP_Ena0BO SRF:K2:FB1:SP_Ena0BO SRF:K3:FB1:SP_Ena0BO SRF:K4:FB1:SP_Ena0BO"
        # RF4 is off line for now 10/25/21. Access is denied during this time.
        pv linkw "pv1 pv2 pv3" "SRF:K1:FB1:SP_Ena0BO SRF:K2:FB1:SP_Ena0BO SRF:K3:FB1:SP_Ena0BO"
        for {set i 1} {$i <= 4} {incr i} {
            if {[catch {exec cavget -list=S${i}:K:FB_OpsManualEnaBI -num} ison]} {
                APSMpReturn error "APSMpSRChangeEnergy: $ison"
            }
            if {$ison == 1} {
                set access [pv info pv$i access]
                if {[lindex [lindex $access 0] 1] == "R"} {
                    APSMpReturn error "APSMpSRChangeEnergy: You do not have write access to SRF:K${i}:FB1:SP_Ena0BO"
                }
            }
        }
    }

    #Check Booster SCR request file
    set BoosterShortFilename $APSMpSRChangeEnergyBooster(ShortFilename)
    if {![string length $BoosterShortFilename]} {
        APSMpReturn error "APSMpSRChangeEnergy: SCR file not choosen!"
    }
    if {![file exists /home/helios/oagData/SCR/snapshots/Booster/$BoosterShortFilename]} {
        APSMpReturn error "SCR file $BoosterShortFilename not found"
    }
    if {[catch {exec sdds2stream /home/helios/oagData/SCR/snapshots/Booster/$BoosterShortFilename -parameter=SnapshotDescription -page=1 -noquotes} results]} {
        APSMpReturn error "APSMpSRChangeEnergy: Invalid SCR file"
    }    
    if {[string first "Limited save:" $results] != -1} {
        APSMpReturn error "APSMpSRChangeEnergy: LIMITED SAVE SCR files cannot be used for this procedure."
    }

    #Abort the BTS Controllaws
    APSMpStep "Aborting the BTS Controllaws"
    if {[catch {exec cavput -list=BTS:ControlLawXRC.ABRT=1} results]} {
        APSMpReturn error "APSMpSRChangeEnergy: $results"
    }
    if {[catch {exec cavput -list=BTS:ControlLawYRC.ABRT=1} results]} {
        APSMpReturn error "APSMpSRChangeEnergy: $results"
    }


    if {$includeSR} {
        #Launch APSMpSRConditionDoubleSector
        set id1 [APSMpParallel \
                   -procedure "APSMpSRConditionDoubleSector -ShortFilename $SRShortFilename -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" \
                   -mode Automatic]
    }

    #Launch APSMpBTSConditionPowerSupplies
    set id2 [APSMpParallel \
               -procedure "APSMpBTSConditionPowerSupplies -allSupplies 1 -SCRFile /home/helios/oagData/SCR/snapshots/Booster/$BoosterShortFilename" \
               -mode Automatic]

    #Wait for both APSMpSRConditionDoubleSector and APSMpBTSConditionPowerSupplies to finish before continuing
    if {$includeSR} {
        if [catch {APSMpJoin $id1} results] {
            APSMpReturn error "APSMpSRChangeEnergy: $results"
        }
    }
    if [catch {APSMpJoin $id2} results] {
	APSMpReturn error "APSMpSRChangeEnergy: $results"
    }

    #Restore Booster/ExtPulsedPS Booster/ExtTiming BTS/SteeringSetpoint
    APSMpStep RestoringSCRValues 
    set SCRFile /home/helios/oagData/SCR/snapshots/Booster/$BoosterShortFilename
    set tmpFile /tmp/[APSTmpString]
    if [catch {exec sddsprocess $SCRFile $tmpFile \
                 -match=column,IsReadOnly=+n  -match=column,IsProtected=+y,! \
                 "-match=column,Beamline=Booster,Beamline=BTS,|" \
                 "-match=column,Category=ExtPulsedPS,Category=ExtTiming,|,Category=SteeringSetpoint,|" \
                 "-match=column,Beamline=Booster,Category=SteeringSetpoint,&,!" \
                 "-match=column,Beamline=BTS,Category=ExtPulsedPS,&,!" \
                 "-match=column,Beamline=BTS,Category=ExtTiming,&,!"} result] {
        catch {APSSendEMail -address soliday \
                 -subject "Problem restoring SCR file."  \
                 -message "Problem restoring SCR file\nAPSMpSRChangeEnergy\n$SCRFile \n$result"} 
        APSMpReturn error "Problem restoring SCR file: APSMpSRChangeEnergy: $SCRFile: $result"
    }
    set logFile [APSTmpDir]/[APSTmpString]
    APSAddToTempFileList $logFile
    set errorInRestore 0
    if [catch {exec sddscasr -restore=verify -logFile=$logFile $tmpFile } result] {
        set errorInRestore 1
    } else {
        set fd [open $logFile "r"]
        while {![eof $fd]} {
            set text [gets $fd]
            if {[string match -nocase "*error*" $text]} {
                set errorInRestore 1
                break
            }
        }
        close $fd
    }
    if $errorInRestore {
        global apsScriptHost
        set logSCRFile [APSTmpDir]/SCR[APSTmpString]
        if {[file exists $logFile]} {
            catch {file copy $logFile $logSCRFile}
            catch {APSSendEMail -address soliday \
                     -subject "Problem restoring SCR file."  \
                     -message "Problem restoring SCR file\nHost=${apsScriptHost}\nSCRfile=${SCRFile}\nLogfile=$logSCRFile"} 
            APSFileDisplayWindow [APSUniqueName .fileDisp] -fileName $logFile \
              -comment "Error output from sddscasr" -deleteOnClose 1 \
              -printCommand "enscript -r"
        } else {
            catch {APSSendEMail -address soliday \
                     -subject "Problem restoring SCR file."  \
                     -message "Problem restoring SCR file\nHost=${apsScriptHost}\nSCRfile=${SCRFile}\nresult=$result"} 
        }
    }
    file delete -force $tmpFile
    
    if {$includeSR} {
        #Restore SR/PulsedPS and Timing
        set SCRFile /home/helios/oagData/SCR/snapshots/SR/$SRShortFilename
        set tmpFile /tmp/[APSTmpString]
        if [catch {exec sddsprocess $SCRFile $tmpFile \
                     -match=column,IsReadOnly=+n  -match=column,IsProtected=+y,! \
                     "-match=column,Beamline=SR" \
                     "-match=column,Category=Diagnostic,Category=PulsedPS,|,Category=BPM,|,Category=Timing,|"} result] {
            catch {APSSendEMail -address soliday \
                     -subject "Problem restoring SCR file."  \
                     -message "Problem restoring SCR file\nAPSMpSRChangeEnergy\n$SCRFile \n$result"} 
            APSMpReturn error "Problem restoring SCR file: APSMpSRChangeEnergy: $SCRFile: $result"
        }
        set logFile [APSTmpDir]/[APSTmpString]
        APSAddToTempFileList $logFile
        set errorInRestore 0
        if [catch {exec sddscasr -restore=verify -logFile=$logFile $tmpFile} result] {
            set errorInRestore 1
        } else {
            set fd [open $logFile "r"]
            while {![eof $fd]} {
                set text [gets $fd]
                if {[string match -nocase "*error*" $text]} {
                    set errorInRestore 1
                    break
                }
            }
            close $fd
        }
        if $errorInRestore {
            global apsScriptHost
            set logSCRFile [APSTmpDir]/SCR[APSTmpString]
            if {[file exists $logFile]} {
                catch {file copy $logFile $logSCRFile}
                catch {APSSendEMail -address soliday \
                         -subject "Problem restoring SCR file."  \
                         -message "Problem restoring SCR file\nHost=${apsScriptHost}\nSCRfile=${SCRFile}\nLogfile=$logSCRFile"} 
                APSFileDisplayWindow [APSUniqueName .fileDisp] -fileName $logFile \
                  -comment "Error output from sddscasr" -deleteOnClose 1 \
                  -printCommand "enscript -r"
            } else {
                catch {APSSendEMail -address soliday \
                         -subject "Problem restoring SCR file."  \
                         -message "Problem restoring SCR file\nHost=${apsScriptHost}\nSCRfile=${SCRFile}\nresult=$result"} 
            }
        }
        file delete -force $tmpFile
    }

    #Restore booster and SR septum feedforward files.
    if {$includeSR} {
        APSMpStep "Restoring SR septum feedforward files"
        cd /home/helios/oagData/feedForwardFiles
        if {[catch [file delete -force SIS1.response] result]} {
            APSMpReturn error "Problem deleting /home/helios/oagData/feedForwardFiles/SIS1.response $result"
        }
        if {$energy == 6} {
            exec ln -s SIS1.6GeV.response SIS1.response
        } else {
            exec ln -s SIS1.7GeV.response SIS1.response
        }
    }

    APSMpStep "Restoring booster feedforward files"
    cd /home/helios/oagData/feedForwardFiles
    if {[catch [file delete -force BES2.response] result]} {
        APSMpReturn error "Problem deleting /home/helios/oagData/feedForwardFiles/BES2.response $result"
    }
    if {$energy == 6} {
        exec ln -s BES2.6GeV.response BES2.response
    } else {
        exec ln -s BES2.7GeV.response BES2.response        
    }

    set id1 [APSMpParallel \
               -procedure "APSMpStopBES2Feedforward" \
               -mode Automatic]
    if [catch {APSMpJoin $id1} results] {
	APSMpReturn error "APSMpSRChangeEnergy: $results"
    }
    set id1 [APSMpParallel \
               -procedure "APSMpStartBES2Feedforward" \
               -mode Automatic]
    if [catch {APSMpJoin $id1} results] {
	APSMpReturn error "APSMpSRChangeEnergy: $results"
    }

    if {$includeSR} {
        set id1 [APSMpParallel \
                   -procedure "APSMpStopSIS1Feedforward" \
                   -mode Automatic]
        if [catch {APSMpJoin $id1} results] {
            APSMpReturn error "APSMpSRChangeEnergy: $results"
        }
        set id1 [APSMpParallel \
                   -procedure "APSMpStartSIS1Feedforward" \
                   -mode Automatic]
        if [catch {APSMpJoin $id1} results] {
            APSMpReturn error "APSMpSRChangeEnergy: $results"
        }
    }

    if {$includeSR} {
        #Restore RTFB FF waveforms for septum leakage fields
        APSMpStep "Restoring RTFB FF waveforms for septum leakage fields"
        cd /home/helios/oagData/sr/RTFB/FFwaveforms/lattices/default
        if {[catch [file delete -force Septum] result]} {
            APSMpReturn error "Problem deleting /home/helios/oagData/sr/RTFB/FFwaveforms/lattices/default/Septum $result"
        }
        if {$energy == 6} {
            exec ln -s Septum.6GeV Septum
        } else {
            exec ln -s Septum.7GeV Septum
        }
        
        #Launch SRFBControl
        APSMpStep "Launch SRFBControl and pause for manual interaction"
        exec SRFBControl &
        set answer [APSPEMTKDialog .warningDialog -text "Press the buttons Disable Feed-forward and Enable Feed-forward in SRFBControl in succession to load the data in the orbit feedback system. If the default lattice has been changed then press Load Response Matrix.. Then press Continue" -strings {Continue "Abort Procedure"}]
        if {$answer == 1} {
            APSMpReturn error "APSMpSRChangeEnergy aborted by user"
        }

        
        #Change the RF Klystron phase settings
        APSMpStep "Change the RF Klystron phase settings"
        for {set i 1} {$i <= 4} {incr i} {
            if {[catch {exec cavget -list=S${i}:K:FB_OpsManualEnaBI -num} ison]} {
                APSMpReturn error "APSMpSRChangeEnergy: $ison"
            }
            if {$ison == 1} {
                if {[catch {exec cavput -list=SRF:K${i}:FB1:SP_Ena0BO=1} results]} {
                    APSMpReturn error "APSMpSRChangeEnergy: $results"
                }
                APSWaitWithUpdate -waitSeconds 5
                if {[catch {exec cavput -list=SRF:K${i}:FB1:Ch0gainGrpMO=0} results]} {
                    APSMpReturn error "APSMpSRChangeEnergy: $results"
                }
                APSWaitWithUpdate -waitSeconds 5
                if {[catch {exec cavput -list=SRF:K${i}:FB1:Grp0_0gainMO=5} results]} {
                    APSMpReturn error "APSMpSRChangeEnergy: $results"
                }
                APSWaitWithUpdate -waitSeconds 5
                if {[catch {exec cavput -list=SRF:K${i}:FB1:SP_Ena0BO=0} results]} {
                    APSMpReturn error "APSMpSRChangeEnergy: $results"
                }
            }
        }

        #Update Synchrotron monitors
        # Could be done in the future using SR category diagnostic. However this is 
        # subject to the intended stored current. So it will be adjusted during most stuides.
        APSMpStep "Update Synchrotron monitors"
        if {$energy == 6} {
            if {[catch {exec cavput -list=S35BM:Filter1MT=1} results]} {
                APSMpReturn error "APSMpSRChangeEnergy: $results"
            }
            APSWaitWithUpdate -waitSeconds 1
            if {[catch {exec cavput -list=S35BM:FilterWheelMT=1} results]} {
                APSMpReturn error "APSMpSRChangeEnergy: $results"
            }
        } else {
            if {[catch {exec cavput -list=S35BM:Filter1MT=3} results]} {
                APSMpReturn error "APSMpSRChangeEnergy: $results"
            }
            APSWaitWithUpdate -waitSeconds 1
            if {[catch {exec cavput -list=S35BM:FilterWheelMT=3} results]} {
                APSMpReturn error "APSMpSRChangeEnergy: $results"
            }
        }
    }

    APSMpReturn ok
}
