#!/bin/sh  
# \
exec oagwish "$0" "$@"


set CVSRevisionAuthor "\$Revision: 1.10 $ \$Author: shang $"
set auto_path [linsert $auto_path 0  /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]
APSStandardSetup

proc SetStatus {text} {
    global status
    set status $text
    update
}

proc Start {args} {
    global optDir gun outputDir optimizerDone
    
    if ![string length $gun] {
        SetStatus "Please select gun first!"
        return
    }
    SetStatus "suspend steering controllaw ..."
    if [catch {exec cavput -list=Linac:ControlLaw -list=X,Y -list=RC.SUSP=1 -pend=30} result] {
        return -code error "Error in suspending steering controllaw: $result"
    }
    SetStatus "Step1: Check steering at the gun $gun front end upstream of L1:CM2 to maximum the charge measured
at L1:CM2."
    set optimizerDone 0
    set varFile $optDir/$gun/${gun}steer.sdds
    set measFile $optDir/L1CM2.meas
    set logFile $outputDir/${gun}-optLog1.sdds
    
    APSExecLog  .opt -width 120 -height 16 -lineLimit 1000 \
      -contextHelp "$gun tune up." \
      -unixCommand "sddsoptimize -measFile=$measFile -varFile=$varFile -maximize -simplex=no1dscan,divisions=12,cycles=1,evaluations=50 -verbose -logFile=$logFile" \
      -callback "set optimizerDone 1" \
      -abortCallback "set optimizerDone 2" \
      -cancelCallback "set optimizerDone 2" 
    if !$optimizerDone {
        tkwait variable optimizerDone
    }
    switch $optimizerDone {
        1 {
            SetStatus "Optimizer step 1 has completed"
        }
        default {
            SetStatus "Optimizer aborted."
            return
        }
    }
    set optimizerDone 0
    SetStatus "Step2: Optimizing $gun and L1 quadrupoles upstream of L1:CM2 to maximize the charge measured at L1:CM2."
    set optimizerDone 0
    set varFile $optDir/$gun/${gun}quads.sdds
    set measFile $optDir/L1CM2.meas
    set logFile $outputDir/${gun}-optLog2.sdds
    APSExecLog  .opt -width 120 -height 16 -lineLimit 1000 \
      -contextHelp "$gun tune up." \
      -unixCommand "sddsoptimize -measFile=$measFile -varFile=$varFile -maximize -simplex=no1dscan,divisions=12,cycles=1,evaluations=50 -verbose -logFile=$logFile" \
      -callback "set optimizerDone 1" \
      -abortCallback "set optimizerDone 2" \
      -cancelCallback "set optimizerDone 2" 
    if !$optimizerDone {
        tkwait variable optimizerDone
    }
    switch $optimizerDone {
        1 {
            SetStatus "Optimizer step 2 has completed"
        }
        default {
            SetStatus "Optimizer aborted."
            return
        }
    }

    set optimizerDone 0
    SetStatus "Step3: Optimizing all $gun and L1 steering magnets and  quadrupoles to maximize charge measured at L3:CM1."
    set varFile $optDir/$gun/${gun}L1quadsteer.sdds
    set measFile $optDir/L3CM1.meas
    set logFile $outputDir/${gun}-optLog3.sdds
    APSExecLog  .opt -width 120 -height 16 -lineLimit 1000 \
      -contextHelp "$gun tune up." \
      -unixCommand "sddsoptimize -measFile=$measFile -varFile=$varFile -maximize -simplex=no1dscan,divisions=12,cycles=2,evaluations=100 -verbose -logFile=$logFile" \
      -callback "set optimizerDone 1" \
      -abortCallback "set optimizerDone 2" \
      -cancelCallback "set optimizerDone 2" 
    if !$optimizerDone {
        tkwait variable optimizerDone
    }
    switch $optimizerDone {
        1 {
            SetStatus "Optimizer step 3 has completed"
        }
        default {
            SetStatus "Optimizer aborted."
            return
        }
    }
    set desc "Step 4: check and adjust linac phase for minimum energy spread in the middle of the chicane (L3:FS1) and at the end of the linac (FS10)."
    SetStatus "$desc"
    
    set answer [APSMultipleChoice .info -name "Check and adjust linac phase" \
        -question "${desc}, pless Ok to continue or abort to quit." -labelList {Ok Abort} \
        -returnList {Ok Abort} ]
    
    if {$answer=="Abort"} {
        SetStatus "$gun tune up was aborted."
        return
    }
    
    set desc "Step 5: Beam matching using the \"BC High Re4s 3-screen emittance measurement\" tool, condition and install new\n L3:QM3, L3:QM4, L3:QM5, and L3:QM6 set points. It might be nessary to manually steer the beam so that the rms beam size can be measured on the screens L3:FS3, L3:FS4 and L3:FS5"
    
    SetStatus "$desc"
    set answer [APSMultipleChoice .info -name "Beam matching" \
                  -question "${desc}, pless Ok to continue or abort to quit." -labelList {Ok Abort} \
                  -returnList {Ok Abort} ]
    if {$answer=="Abort"} {
        SetStatus "$gun tune up was aborted."
        return
    }

    set desc "Step 6: Check and adjust L4 and L5 phase for minimum energy spread at the end of linac (FS10)."
    SetStatus "$desc"
    
    set answer [APSMultipleChoice .info -name "Check and adjust L4 and L5 phase" \
                  -question "${desc}, pless Ok to continue or abort to quit." -labelList {Ok Abort} \
                  -returnList {Ok Abort} ]
    if {$answer=="Abort"} {
        SetStatus "$gun tune up was aborted."
        return
    }
    
    set desc "Step 7: Transfer the \"Linac Phase Controllaw Feedback Setpoints\" under OAGapps and resume linac phase controllaw."
    SetStatus "$desc"
    set answer [APSMultipleChoice .info -name "Transfer linac phase controllaw feedback setpoints" \
                  -question "${desc}, pless Ok to continue or abort to quit." -labelList {Ok Abort} \
                  -returnList {Ok Abort} ]
    if {$answer=="Abort"} {
        SetStatus "$gun tune up was aborted."
        return
    }
    
    set desc "Step 8: Tranfer Linac BPM feedback setpoints, resume linac trajectory controllaw."
    SetStatus "$desc"
    set answer [APSMultipleChoice .info -name "Transfer linac BPM feedback setpoints" \
                  -question "${desc}, pless Ok to continue or abort to quit." -labelList {Ok Abort} \
                  -returnList {Ok Abort} ]
    if {$answer=="Abort"} {
        SetStatus "$gun tune up was aborted."
        return
    }
    
    set desc "Step 9: Check beam injection into PAR, verify that the PAR trajectory controllaw is running. Charge transportation throught the PAR should be close to 100%."
    SetStatus "$desc"
    set answer [APSMultipleChoice .info -name "Check beam injection into PAR" \
                  -question "${desc}, pless Ok to continue or abort to quit." -labelList {Ok Abort} \
                  -returnList {Ok Abort} ]
    if {$answer=="Abort"} {
        SetStatus "$gun tune up was aborted."
        return
    }
    
    set desc "Step 10: Save LTP configuration file and condition linac to this file."
    set answer [APSMultipleChoice .info -name "save LTP and condition linac" \
                  -question "${desc}, pless Ok to continue or abort to quit." -labelList {Ok Abort} \
                  -returnList {Ok Abort} ]
    if {$answer=="Abort"} {
        SetStatus "$gun tune up was aborted."
        return
    }
    set desc "Step 11: verify charge from PAR to booster is still satisfactory."
    APSInfoWindow .info -name "verify charge from PAR to booster" -modal 1 \
        -infoMessage "$desc"
    SetStatus "done."
}

set status ""
APSApplication . -name LinacRGGunTuneUp -version $CVSRevisionAuthor \
    -overview {This utility is for tuning up RG gun through steering the magnets}
APSScrolledStatus .status  -parent .userFrame  -textVariable status -width 100 \
  -height 4 -withButtons 1 -packOption "-fill x"

set optDir /home/helios/LINAC/GunOptmize
set outputDir [APSGoToDailyDirectory  -subdirectory RGGunTuneUp]

set gun ""
APSLabeledEntry .outdir -parent .userFrame -label "Output directory:" -textVariable outputDir -width 80
APSRadioButtonFrame .sel -parent .userFrame -label "Select Gun:" -buttonList {RG1 RG2} \
    -valueList {RG1 RG2} -variable gun -orientation horizontal 
    

APSButton .acq1 -parent .userFrame -text "Start" -command "Start"

