# $Log: not supported by cvs2svn $
# Revision 1.21  2010/04/19 16:30:55  shang
# replaced public/default by default since now uses default as direct link.
#
# Revision 1.20  2008/02/06 18:12:38  soliday
# Removed calls to setfacl because it is no longer needed.
#
# Revision 1.19  2006/02/21 17:27:13  soliday
# Added code to change the background of the cycles entry box in the initial
# dialog if the number of cycles is excessive.
#
# Revision 1.18  2005/10/18 22:23:30  emery
# Removed dialog about scraper. Added dialog about bpm cogging.
# Removed dialog on restoring rf settings.
#
# Revision 1.17  2003/11/19 05:25:00  emery
# Corrected the filename argument to the booster tab dialog box.
# Added directory rfOrbitControllaw/lattices to the list of directories
# that depend on the lattice selection.
#
# Revision 1.16  2003/09/24 15:12:29  soliday
# It does not stop anymore if logDaemon is not running.
#
# Revision 1.15  2002/12/11 17:29:46  shang
# added RTFB/FFwaveforms/lattices link
#
# Revision 1.14  2002/10/08 18:32:40  emery
# Added pause argument to APSRampToSnapshot command.
#
# Revision 1.13  2002/10/07 10:51:58  emery
# Forgot to set variable SRSteeringFile
#
# Revision 1.12  2002/10/06 06:00:46  emery
# Removed the step where the RTFB correctors are released.
# By default all correctors should be in operation mode.
#
# Revision 1.11  2002/10/04 01:12:58  emery
# Added ramping of the SR steering PS.
# Removed extraneous quotes in sdds command arguments.
#
# Revision 1.10  2002/08/27 22:57:05  emery
# Changed using SBPMs reference file to prefered file.
#
# Revision 1.9  2002/08/13 11:31:58  emery
# Filtered out protected PV in SBPMs file before attempting to
# run burtwb.
#
# Revision 1.8  2002/08/06 20:05:01  emery
# Fixed missing SBPMs file for burtwb.
#
# Revision 1.7  2002/06/11 20:30:05  soliday
# Added some extra log messages.
#
# Revision 1.6  2002/04/16 20:21:33  emery
# Added SBPMs restore.
#
# Revision 1.5  2002/02/26 12:13:28  emery
# Modified linking command to follow new linking structure of
# default directories.
#
# Revision 1.4  2002/02/06 11:49:32  shang
# added comments, fixed some little bugs.
#
# Revision 1.3  2002/02/06 11:14:46  shang
# expanded dialog box
#
# Revision 1.2  2001/03/02 15:06:55  emery
# Added initial dialog box.
# Fixed SCR files for burtwb commands.
# Added RTFB reseting.
#
# Revision 1.1  2001/02/20 05:19:29  emery
# First installation. Contains only step-by-step info windows for
# manual procedures.
#

proc APSMpSRSetupInfo {} {
    return "This procedure sets up the SR for User operations after it has been run for other purposes such as machine studies. This involves mostly setting the correct setpoints, checking the configurations of systems. All power supplies, RF systems systems, and other systems are assumed to be turned on and working."
}

proc APSMpSRSetupInitDialog {frame} {
    global status APSMpSRSetup APSMpSRSetupB

    set status "Select number of cycles"
    
    
    pack [frame $frame.f1]
    APSLabeledEntry .cycles -parent $frame.f1 \
      -textVariable APSMpSRSetup(cycles) -width 12 \
      -label "Cycles for standardization:   " \
      -contextHelp \
      "Set the number of cycles for standardization. 3 is standard 0 is fastedst but less accurate."

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

    pack [checkbutton $frame.configure -text "Configure Power Supplies" \
            -variable APSMpSRSetup(configure) -padx 4 -pady 4 -relief ridge] -padx 5
    pack [checkbutton $frame.launch -text "Restore Booster" \
            -variable APSMpSRSetup(restoreBooster) -padx 4 -pady 4 -relief ridge] -padx 5
    
    #specifying lattice type
    set latticeList [APSSRFindLattices]
    APSRadioButtonFrame .latticeChoiceFrame -parent $frame \
      -orientation  vertical -limitPerRow 4 \
      -packOption {-side top -fill x} \
      -label "Lattice Choice" \
      -variable APSMpSRSetup(lattice) \
      -buttonList $latticeList \
      -valueList $latticeList \
      -contextHelp "This radio button is used to select a lattice used in data analysis and plotting of beta functions."
    set tabFrameWidgetList [APSTabFrame .main -parent $frame -label "" \
                              -labelList {SR Booster} \
                              -width 1000 -height 500 -packOption "-expand true"]
    set srFrame [lindex $tabFrameWidgetList 0]
    set boosterFrame [lindex $tabFrameWidgetList 1]

    APSAddSCRDialog .scr -parent $srFrame -system SR -arrayName APSMpSRSetup \
      -defaultFile $APSMpSRSetup(ShortFilename)

    APSAddSCRDialog .scr1 -parent $boosterFrame -system Booster -arrayName APSMpSRSetupB \
      -defaultFile $APSMpSRSetup(ShortFilename)

    APSMpReturn ok
}

proc APSMpSRSetup {} {
    global APSMpSRSetup
    set cycles 3
    set configure 1
    set ShortFilename ""
    set lattice nuy19.3
    set restoreBooster 0
    set BoosterFilename Booster-Preferred325.gz
    set SCRpath /home/helios/oagData/SCR/snapshots
    #set BoosterFilename ""
    APSMpStep init -promptDialog APSMpSRSetupInitDialog \
      -vars {cycles configure ShortFilename lattice restoreBooster BoosterFilename}

    foreach param "cycles configure ShortFilename lattice restoreBooster BoosterFilename" {
        append paramString "$param=\"[set $param]\" "
    }
    if {[catch {APSLogScriptAction \
                  -procedure APSMpSRSetup \
                  -action initialize \
                  -state ok \
                  -parameters $paramString} results]} {
#        APSMpReturn error "APSMpSRSetup: $results"
    }

    if {![string length $ShortFilename]} {
        APSMpReturn error "SCR file is not choosen"
    }
    if {![file exists $SCRpath/SR/$ShortFilename]} {
        APSMpReturn error "SCR file $ShortFilename not found"
    }
    
    if {$restoreBooster} {
        global APSMpSRSetupB 
        set BoosterFilename $APSMpSRSetupB(ShortFilename)
        if {![string length $BoosterFilename] } {
            APSMpReturn error "booster file name is not given for restoring booster settings."
        }
        set boosterfile /tmp/Booster[APSTmpString]
        if [catch {eval exec sddsprocess $SCRpath/Booster/$BoosterFilename \
                     -match=column,ValueString=,! $boosterfile \
                     -match=column,Beamline=Booster,Category=ExtTiming,&,Beamline=BTS,| } result] {
            APSMpReturn error "$result"
        }
        APSAddToTmpFileList -ID 1 -fileList $boosterfile
    }
    append sectorArgs "-ShortFilename $ShortFilename "
    
    #create tmp files that will be used for burtwb to restore values
    APSMpStep "CreatingFiles" -desc "Creating snapshot files."
    set SRfile /tmp/SR[APSTmpString]
    set SRSteeringFile /tmp/SR[APSTmpString]
    set SBPMfile /tmp/SBPM[APSTmpString]
    set RFBrief /tmp/SR[APSTmpString]
    set match "-match=col,Category=BPM,Category=Diagnostic,|,Category=MainPS,|,Category=PulsedPS,|"
    append match ",Category=Timing,|"
    if [catch {eval exec sddsprocess $SCRpath/SR/$ShortFilename -match=column,ValueString=,! \
                 $match $SRfile -noWarn} result] {
        APSMpReturn error "APSMpSRSetup1: $result"
    }
    set match "-match=col,Category=SteeringPS"
    if [catch {eval exec sddsprocess $SCRpath/SR/$ShortFilename -match=column,ValueString=,! \
                 $match $SRSteeringFile -noWarn} result] {
        APSMpReturn error "APSMpSRSetup1: $result"
    }
    APSAddToTmpFileList -ID 1 -fileList "$SRfile $SRSteeringFile"
    
    if [catch {eval exec sddsprocess $SCRpath/SBPMs/SBPMs-Preferred.gz \
                 -match=column,ValueString=,! \
                 -match=column,IsProtected=n \
                 $SBPMfile -noWarn} result] {
        APSMpReturn error "APSMpSRSetup1a: $result"
    }
    APSAddToTmpFileList -ID 1 -fileList $SBPMfile

    if [catch {eval exec sddsprocess $SCRpath/SR/$ShortFilename -match=column,ValueString=,! \
                 -match=col,Category=RFbrief $RFBrief -noWarn } result] {
        APSMpReturn error "APSMpSRSetup2: $result"
    }
    APSAddToTmpFileList -ID 1 -fileList $RFBrief

    APSMpStep "ChangeDefaultLattice" -desc "ChangeDefaultLattice"
    APSMpSRChangeDefault $lattice
    
    
    APSMpStep SetFFcurrentAO
    if [catch {exec cavput -pend=20 -list=S -range=beg=1,end=40 \
                 -list=A:H,B:H -range=begin=1,end=4 \
                 -list=:FFCurrentAO=0} result] {
        APSMpReturn error "APSMpSRSetup: Problem setting corrector FFcurrentAO"
    }
    
    APSMpStep AbortRFcontrollaw
    if [catch {exec cavput -list=S:RF -list=1:3840,2:3637 \
                 -list=GVControlLawRC.ABRT=1} result] {
        APSMpReturn error "APSMpSRSetup: Problem aborting RF Gap controllaw"
    }
    
    APSMpStep StandardizeAll
    set sectorGroups {S40:01 S02:03 S04:05 S06:07 S08:09 S10:11 S12:13 \
                        S14:15 S16:17 S18:19 S20:21 S22:23 S24:25 S26:27 \
                        S28:29 S30:31 S32:33 S34:35 S36:37 S38:39}
    foreach sectorGroup $sectorGroups {
        append sectorArgs "-$sectorGroup 1 "
    }   
    set skipStandardization 0
    #for test purpose, skip this step right now
    
    if {!$skipStandardization} {
        if [catch {eval APSMpSRConditionDoubleSector $sectorArgs \
                     -cycles $cycles \
                     -configure $configure \
                     -degauss 1 \
                 } result] {
            APSMpReturn error "APSMpSRSetup: Problem executing APSMpSRConditionDoubleSector"
        }
    }

    APSMpStep CheckIDgaps
    APSInfoWindow .info -infoMessage "Check ID device gaps (should be 180 mm or more) and open if necessary.\n\n Press ok when finished" -modal 1 
    
    APSMpStep RestoreStorageRing -desc "Restore Storage Ring BPM, diagnostics and non-steering PS"
    if [catch {exec sddscasr -restore $SRfile} result] {
        if {[tk_dialog2 .warningDialog "Warning Message" \
               "$result\n\nProblem with restoring $SRfile setting\n\nNote that the restoration of configuration may be incomplete." \
               warning -1 Continue Abort] == 1} {
            APSMpReturn error "APSMpSRSetup: $result"
        }
    }
    APSMpStep RampingSRSteering -desc "Ramping SR steering PS"
    if [catch {APSRampToSnapshot -initDialog 0 -fileName $SRSteeringFile -steps 20 -pause 1} result] {
        if {[tk_dialog2 .warningDialog "Warning Message" \
               "$result\n\nProblem with restoring $SRSteeringFile setting\n\nNote that the restoration of configuration may be incomplete." \
               warning -1 Continue Abort] == 1} {
            APSMpReturn error "APSMpSRSetup: $result"
        }
    }
    APSMpStep RestoreStorageRingSBPMs $SBPMfile -desc "Restore Storage Ring BPM triggering"
    
    if [catch {exec sddscasr -restore $SBPMfile} result] {
        if {[tk_dialog2 .warningDialog "Warning Message" \
               "$result\n\nProblem with restoring $SBPMfile setting\n\nNote that the restoration of configuration may be incomplete." \
               warning -1 Continue Abort] == 1} {
            APSMpReturn error "APSMpSRSetup: $result"
        }
    }

    if {0} {
        if {[APSYesNoPopUp "Restore RFBrief settings?"]} {
            if [catch {exec sddscasr -restore $RFBrief} result] {
                if {[tk_dialog2 .warningDialog "Warning Message" \
                       "$result\n\nProblem with restoring $RFBrief setting\n\nNote that the restoration of configuration may be incomplete." \
                       warning -1 Continue Abort] == 1} {
                    APSMpReturn error "APSMpSRSetup: $result"
                }
            }
        }
    }
    
    if $restoreBooster {
        APSMpStep RestoreBoosterBPMs
        if [catch {exec sddscasr -restore $boosterfile} result] {
            if {[tk_dialog2 .warningDialog "Warning Message" \
                   "$result\n\nProblem with restoring $boosterfile setting\n\nNote that the restoration of configuration may be incomplete." \
                   warning -1 Continue Abort] == 1} {
                APSMpReturn error "APSMpSRSetup: $result"
            }
        }
    }
    
    APSMpStep CheckRFgapsPhases
    APSInfoWindow .info -infoMessage "Check and set RF gap voltage, A/B phase and B/S phase.\n\n Press ok when finished" -modal 1

    APSMpStep CheckBPLDStatus
    APSInfoWindow .info -infoMessage "Check BPLD status screen for any fault, correct if necessary.\n\n Press ok when finished" -modal 1

    APSMpStep OpenRTFBLoops
    if [catch {APSMpSRFBresetOpen} result] {
        if {[tk_dialog2 .warningDialog "Error Message" \
               "APSMpSRFBresetOpen:\n\n$result." \
               warning -1 Continue Abort] == 1} {
            APSMpReturn error "APSMpSRSetup: $result"
        }
    }

    APSMpStep CheckCogging
    APSInfoWindow .info -infoMessage "Check that BPM trigger cogging is set up correctly for the bunch pattern of the next fill." -modal 1 
    
    APSMpStep VerifyRadiationPVMonitor
    APSInfoWindow .info -infoMessage "Verify that Radiation PV monitor is running and enabled.\n\n Press ok when finished" -modal 1

    APSMpReturn ok

}

proc APSMpSRFBresetOpen {} {
    if [catch {exec cavput -pend=15 -list=SRFB:GBL:Hor:CloseLoopBO=0,SRFB:GBL:Vert:CloseLoopBO=0
        exec cavput -pend=10 -list=SRFB:GBLM:Hor:CloseLoopBO=1,SRFB:GBLM:Vert:CloseLoopBO=1
        exec cavput -pend=10 -list=SRFB:GBLM:Hor:CloseLoopBO=1,SRFB:GBLM:Vert:CloseLoopBO=1
        exec cavput -pend=10 -list=SRFB:MPS:resetBO=1
        exec cavput -pend=10 -list=SRFB:GBLM:DSPLoadParamsBO=1
        exec cavput -pend=10 -list=SRFB:GBL:Hor:CloseLoopBO=0,SRFB:GBL:Vert:CloseLoopBO=0 \
             } result] {
        APSMpReturn error "APSMpSRFBresetOpen $result"
    }
    set hpFilterInitialVert 10
    set hpFilterInitialHoriz 10
    if [catch {exec cavput -pend=15 -list=SRFB:fhAO=$hpFilterInitialVert,SRFB:fhSlAO=$hpFilterInitialHoriz
        exec cavput -pend=15 -list=SRFB:GBL:loadBO=1 \
             } result] {
        APSMpReturn error "APSMpSRFBresetOpen $result"
    }
    APSMpReturn ok
}

proc APSMpSRFBreleaseCorrs {} {
    if [catch {exec cavput -pend=15 -list=SRFB:accessControlMBBO.VAL=0
        exec cavput -pend=10 -blunder -list=S -range=beg=1,end=40 \
                 -list=A:H3,A:V3 -list=:ControlSrcBO=0
        exec cavput -pend=10 -blunder -list=SRFB:GBLM:DSPCtrlBO=Maintenance
        exec cavput -pend=10 -blunder -list=SRFB:accessControlMBBO.VAL=3 \
             } result] {
        APSMpReturn error "APSMpSRFBreleaseCorrs $result"
    }
    # Setting corrector alarm limit to +/-${pscuTolerance}A
    set pscuTolerance 0.25
    if [catch {exec cavput -pend=10 -blunder -list=S -range=beg=1,end=40 \
                 -list=A:H3,A:V3 -list=:ToleranceCALC.C=$pscuTolerance} error ] {
        APSMpReturn error "APSMpSRFBreleaseCorrs: Failed to set alarm limits properly: $result"
    }
    APSMpReturn ok
}

proc APSMpSRChangeDefault {newLattice} {
    global env
    set dataDir /home/helios/oagData/sr
    set directoryList [list lattices localSteering/lattices \
                         orbitControllaw/lattices \
                         rfOrbitControllaw/lattices \
                         rtfeedback/lattices \
                         magnetConditioning/lattices \
                         latticeFunctionCorrection/beta/lattices \
                         latticeFunctionCorrection/etay/lattices \
                         latticeFunctionCorrection/etax/lattices \
                         RTFB/FFwaveforms/lattices \
                         knobFiles]
    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 APSMpSRSetup \
                     -tag=Host $env(HOST) -tag=Action Start \
                     -tag=User $env(USER) } result] {
            APSMpStep "Error with logMessage in logging default lattice change start: $result"
        }
        if {[catch {exec rm default 
            exec ln -s $newLattice default} result]} {
            APSMpReturn error "Couldn't make link to $newLattice in directory $dir\n$result"
        }
        if ![file exists $newLattice] {
            exec mkdir -p $newLattice
            file attributes $newLattice -permissions 0755
            #set aclDirFile /home/helios/oagData/sr/lattices/dirs.acl
            #exec setfacl -f $aclDirFile $dataDir/$dir/$newLattice
        }
        if [catch {exec logMessage -sourceId=defaultLatticeAudit \
                     -tag=Directory $dataDir/$dir \
                     -tag=OldLattice $oldLattice \
                     -tag=NewLattice $newLattice -tag=Application APSMpSRSetup \
                     -tag=Host $env(HOST) -tag=Action Finish \
                     -tag=User $env(USER) } result] {
            APSMpStep "Error with logMessage in logging default lattice change finish: $result"
        }
    }
    
    APSSetVarAndUpdate status "Re-links of default lattice directories to $newLattice successful." 
    APSMpReturn ok
}
