#!/bin/sh  
# \
exec oagtclsh "$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

proc CollectData {args} {
    global InjectionState injectValue dataDir
    
    if {[string compare $InjectionState $injectValue]==0} {
        #collecting data
        set filename $dataDir/topUp/[APSOffsetDateInfo -today 1 -dateFormat Y-M-D]_[lindex [exec date] 3]
        puts "collecting data to $filename..."
        if [catch {exec BRampWaveformMon -filename $filename} result] {
            return -code error "Error reading booster ramp waveforms: $result"
        }
    }
}

#if [catch {exec cavget -list=Mt:TopUpAutoEnableC.VAL -printErrors -pend=10} topup] {
#    puts stderr "Error reading topup state: $topup"
#    exit 1
#}

#if [string compare $topup "Disable"]==0 {
#    puts "ignore (do not collect BRamp) for non-topup."
#    exit 0
#}

set dataDir /home/helios/oagData/booster/rampLogFiles/archivedData
if ![file exist $dataDir/topUp] {
    exec mkdir $dataDir/topUp
}
set RCPV OAG139RC
set RCtimeout 300

if [catch {exec cavget -list=$RCPV.RUN -pend=20 } running] {
    puts stderr error "error checking OAG139RC runcontrol: $running"
    exit 1
}
if $running {
    #it is already running, exit
    exit 0
}

catch {APScavput -list=$RCPV.CLR=1}

if [catch {APSRunControlInit -pv $RCPV \
             -description "BBPM Waveform Collection" \
             -timeout [expr $RCtimeout * 1000]} result] {
    puts stderr $result
  #  exit 1
}

if [catch {APSRunControlPing} result] {
    puts stderr "collectBRampWaveform1: APSRunControlPing \#1, Run control denied: $result"
   # exit 1
}

set injectPV  Mt:TopUpWarning2InjectorM.VAL
set injectValue InjectWarn

if [pv linkw InjectionState $injectPV 30] {
    puts stderr "Error setup link for $injectPV: $errorCode"
}

pv umon InjectionState CollectData

while {1} {
    if [catch {APSRunControlPing} result] {
        puts stderr  "exit collectBRampWaveform because of  $result"
        exit 1
    }
    APSWaitWithUpdate -waitSeconds 5 -updateInterval 1
}


exit 0


