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



set dataDir /home/helios/oagData/controlFiles/SR

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)]
set CVSRevisionAuthor "\$Revision: 1.7 $ \$Author: borland $"

APSApplication . -name SRVertSweep -version $CVSRevisionAuthor \
  -overview {This application assists vacuum scrubbing by sweeping the beam vertically using a number of corrector magnets. You have to store beam first, then activate the sweeping with the START button.}

set mainStatus "Ready."
APSScrolledStatus .status -parent .userFrame -textVariable mainStatus \
  -width 60 -height 3

set CurrentSetpointList [exec cavget -list=S20A,S20B -list=:V1:CurrentAO "-delim= " -label]
array set current0 $CurrentSetpointList
        
set corrPVList {S20A:V1:StandardizeSUB.PROC S20B:V1:StandardizeSUB.PROC}

proc SetMainStatus {text} {
    global mainStatus
    set mainStatus $text
    update
}

set tcl_precision 4

set Amplitude 55
set Delay 13
set Threshold 1
APSLabeledEntry .amplitude -parent .userFrame -textVariable Amplitude \
  -label "Amplitude (Amps): " -width 10 -packOption "-side top -expand 1" \
  -contextHelp "Enter the peak-to-peak amplitude of the corrector oscillations."
APSLabeledEntry .delay -parent .userFrame -textVariable Delay \
  -label "Delay (secs):     " -width 10 -packOption "-side top -expand 1" \
  -contextHelp "Enter the delay between the first corrector and the second.  Should be close to 13s to get a traveling wave."
APSLabeledEntry .thres -parent .userFrame -textVariable Threshold \
  -label "Threshold (ma):   " -width 10 -packOption "-side top -expand 1" \
  -contextHelp "Enter the threshold current below which sweeping is automatically disabled."


set SweepingOn 0

proc CheckAgainstThreshold {} {
    global Threshold SweepingOn
    if !$SweepingOn {
        return
    }

    set current [exec cavget -list=S-DCCT:CurrentM]
    set current [expr abs($current)]

    if {$current<$Threshold} {
        SetMainStatus "Below threshold--stopping."
        bell
        StopVertSweeping 0
    }

}


proc StartVertSweeping {args} {
    global Amplitude errorCode dataDir Delay SweepingOn
    set tmpFile /tmp/[APSTmpString]

    if $SweepingOn {
        SetMainStatus "Already sweeping."
        return
    }       
    SetMainStatus "Starting..."

    if {[catch {exec sddsprocess $dataDir/VSweepDegauss.sdds $tmpFile \
                  "-define=column,MaxCurrent,[expr $Amplitude/2]"} result]} {
        SetMainStatus "$result"
        return
    }
    catch {exec degauss -configure $tmpFile} result
    if {[catch {exec rm $tmpFile} result]} {
        SetMainStatus "$result"
        return
    }
# kludge to set the degauss decay time to a value more
# than 60 minutes, which the program degauss won't allow.
# Here is it set to 20 hours.
    if {[catch {exec cavput -list=S20 -list=A,B -list=:V1:StandardizeSUB.B=1200 \
              } result]} {
        SetMainStatus "$result"
        return
    }
    if {[catch {exec cavput -list=S20A  \
                  -list=:V1:StandardizeSUB.PROC=1 } result]} {
        SetMainStatus "$result"
        return
    }
    SetMainStatus "First corrector started [exec date +%H:%M:%S]"
    
    set Delay [expr int($Delay)]
    for {set t 0} {$t<$Delay} {incr t} {
        after 1000
        update
    }

    if {[catch {exec cavput -list=S20B  \
                  -list=:V1:StandardizeSUB.PROC=1 } result]} {
        SetMainStatus "$result"
        return
    }
    set SweepingOn 1
    SetMainStatus "Sweeping started [exec date +%H:%M:%S]"

    # after 10 minutes of sweeping, stop and re-start
#    APSExec -unixCommand "sleep 600" -callback "StopVertSweeping 1; after 2000; StartVertSweeping"
}

proc StopVertSweeping {force} {
    global current0 SweepingOn

    if {!$SweepingOn && !$force} {
        return
    }
    SetMainStatus "Stopping..."

    if {[catch {exec cavput -list=S20A,S20B  \
                  -list=:V1:StandardizeSUB.PROC=0 } result]} {
        SetMainStatus "$result"
        return
    }
    
    SetMainStatus "Sweeping stopped [exec date +%H:%M:%S]"
    foreach elem [array names current0] {
        set value $current0($elem)
        if {[catch {exec cavput -list=$elem=$value} result]} {
            SetMainStatus "$result"
            return
        }
    }
    SetMainStatus "Magnets restored [exec date +%H:%M:%S]"
    set SweepingOn 0
}


APSButton .start -parent .userFrame -text START \
  -command StartVertSweeping \
  -contextHelp "Starts two vertical correctors sweeping."

APSButton .stop -parent .userFrame -text STOP \
  -command "StopVertSweeping 1" \
  -contextHelp "Stops two vertical correctors from sweeping."

while {1} { 
    update
    update idletasks
    CheckAgainstThreshold
    update idletasks
    after 500
}
