#!/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)]

#version 1.0 1/29/2013 shang
#first version, for updating bunch cleaning rms pvs.

set timeout 600
set args $argv
APSParseArguments {timeout}

APSStandardSetup

set tmpRoot /tmp/[APSTmpString]parBunch

if {[catch {exec cavget -noquote -list=S:ActualMode,S:DesiredMode -num -pend=10 -printErrors} results]} {
    exit
}
set actualMode [lindex $results 0]
set desiredMode [lindex $results 1]
#if the SR state is unknown, then exit
#if {$actualMode == 0} { exit }

#check for topup shot
set timeout [expr [clock seconds]+$timeout]
while {[clock seconds]<$timeout} {
    if [catch {APScavget -list=Mt:TopUpAutoEnableC.VAL,Mt:TopUpTime2Inject,Mt:TopUpWarnTime2CalcP -pend=10 -printErrors -num} valList] {
        puts stderr "Error reading topup state: $valList"
        exit 1
    }
    set topup [lindex $valList 0]
    set injTime [lindex $valList 1]
    set count [lindex $valList 2]
    if !$topup {
        #non topup
        break
    }
    #in topup mode, check injtime, wait for injTime > count+16
    if {$injTime<[expr $count+16]} {
        after 1000
        continue
    } else {
        #take measurement when it is greater than count+16
        break
    }
}

foreach type {TO BO TI BI} {
    if [catch {exec cavput -list=P:BnchCln:Mux11mbbo=$type -pend=20} result] {
        if {($actualMode == 5) || ($desiredMode == 6)} { exit }
        puts stderr "updatePARBunchCleaning1: unable switch P:BnchCln:Mux11mbbo to $type: $result"
        exit 1
    }
    after 2000
    if [catch {exec sddswget -pv=PAR:awg:rms:gtr:waveform0 -pend=10 $tmpRoot.$type
        exec sddsprocess $tmpRoot.$type -pipe=out \
                 -process=Waveform,ave,Ave \
                 "-redefine=col,Waveform,Waveform Ave -" \
                 "-redefine=col,Waveform,Waveform 7 > ? Waveform : 0 $ " \
                 -proc=Waveform,sum,SUM \
                 | sdds2stream -pipe -par=SUM} sum] {
        puts stderr "updatePARBunchCleaning2: error in getting bunch cleaning waveform sum: $sum"
        exit 1
    }
    puts "$type $sum"
    if [catch {exec cavput -list=PAR:BunchClean:SUM:$type=$sum -pend=20} result] {
        puts stderr "updatePARBunchCleaning3: error in setting PAR:BunchClean:SUM:$type to $sum: $result"
        exit 1
    }
}
set fileList [glob -nocomplain ${tmpRoot}*]
if [llength $fileList] {
    eval file delete -force $fileList
}

exit 0
