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


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
set CVSRevisionAuthor "\$Revision: 1.3 $ \$Author: emery $"

APSApplication . -name "SROptimizeInjectionPhase" -version $CVSRevisionAuthor \
  -overview "SROptimizeInjectionPhase adjusts the booster/sr RF phase for minimum energy oscillation on a bpm history."

proc MakeActionWidget {widget args} {
    set parent ""
    APSParseArguments {parent}
    
    APSFrame $widget -parent $parent -label "" \
      -contextHelp "Control widgets"
    set w $parent$widget.frame

    APSFrame .setup -parent $parent$widget.frame -label "" \
      -contextHelp "Setup quantities"
    set w $parent$widget.frame.setup.frame

    APSLabeledEntry .logDir -parent $w -width 60 \
      -textVariable logDir \
      -label "Log directory:" \
      -contextHelp "Directory for log file of minimization."

   APSButton .daily -parent $w.logDir -packOption "-anchor e" \
      -text "daily" -size small \
      -command {set logDir [APSGoToDailyDirectory -subDirectory .]}

    APSLabeledEntry .ik1 -parent $w \
      -label "IK1 fixed setpoint:" -textVariable IK1 \
      -contextHelp "Enter a setpoint for IK1. IK1 is the reference amplitude for the other kickers to match to."

    APSLabeledEntry .bpm -parent $w \
      -label "BPM history:" -textVariable bpm \
      -contextHelp "Enter a bpm name, for which the history will be minimized."

    APSFrame .optimize -parent $parent$widget.frame -label "" \
      -contextHelp "Optimize frame"
    set w $parent$widget.frame.optimize.frame

    APSButton .setup  -parent $w -text "Setup pulsing and BPM" \
      -command {Setup -IK1 $IK1 -bpm $bpm} \
      -contextHelp "Sets up IK1 and bpm before starting the optimization for minimizing the coupling."

    APSButton .minimize  -parent $w -text "Minimize Oscillations" \
      -command {runOptimize -logDir $logDir -bpm $bpm} \
      -contextHelp "Starts sddsoptimize for minimizing the energy oscillations."

    APSButton .plotProg  -parent $w -text "Plot Progress" \
      -command {plotProgress -logDir $logDir} \
      -contextHelp "Plots the knob values and emittance."

}

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

proc Setup {args} {
    set IK1 12.0
    set bpm S5B:P5
    APSParseArguments {IK1 bpm}

    if [catch {exec cavput -list=S:IK1:VoltageSetSendAO=$IK1 \
                 -pen=5 \
             } result ] {
        return -code error $result
    }

    # disable trigger inhibit
    regexp {S(.*)[AB]} $bpm {} sector
    if [catch {exec cavput -pend=5 -list=S${sector}BpmTime:disableInitBO=0 \
            } result] {
        return -code error "Setup: $result"
    }
    

    set bpmList $bpm
    # FIFO reset, FIFO mode "Stop on Full"
    # reset Resync received, reset lost P0, reset lost clock, all for sector
    if {[catch {exec cavput -pend=5 -list=[join $bpmList ,] \
                    "-list=:bh.FIM0=Stop on Full,:bh.FIR0=Enable"} result] || \
          [catch {exec cavput -pend=5 -list=[join $bpmList ,] \
                    "-list=:bh.BRDE=Enable,:bh.BRDM=Continuous,:bh:wfDisable_bo=Enable"} \
             result]} {
        return -code error "Setup: $result"
    }

    if {[catch {exec cavput -pend=5 -list=[join $bpmList ,] \
                  -list=:bh.FRST=1} result]} {
        return -code error "Setup: $result"
    }

    #fire SR septum and kickers
    if [catch {exec cavput -pend=5 -list=Mt:Ddg \
                 -list=3chan4,3chan0,3chan1 \
                 -list=.GATE=Enabled \
             } result]  {
        return -code error "Setup: $result"
    }
    
    SetStatus "Setup done."
}

proc runOptimize {args} {
    set logDir .
    set bpm S5B:P5
    APSParseArguments {logDir bpm}
    set scriptDir /home/helios/oagData/sr/optimizeScripts/injectionPhase
    
    APSExecLog .minimizeCoupling \
      -lineLimit 2048 -width 90 \
      -name "SR injection Phase Optimization" \
      -unixCommand "sddsoptimize \"-measScript=/home/helios/SR/bin/findHistorySpread -average 2 -bpm $bpm -start 100 -end 512 \" \
            -varFile=$scriptDir/var  -tolerance=1 \
            -simplex=restarts=1,cycles=1,evaluations=50,no1dscan \
            -testValues=file=$scriptDir/tests,limit=30 \
            -target=0.0 -verbose \
            -logFile=$logDir/injectionPhase.optLog"
}

set IK1 12.0
set bpm S5B:P5
set logDir .
set status "Working."
APSScrolledStatus .status -parent .userFrame -textVariable status -width 90
MakeActionWidget .action -parent .userFrame
set status "Ready."
