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

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

APSApplication . -name SRPSCheckOperation 

set status Ready.
APSScrolledStatus .status -parent .userFrame -textVariable status -width 60 -height 8


set tmpRoot /tmp/[APSTmpString]
set threshold(0) 0.1
set threshold(1) 1.0
set average 1
set interval 1

proc RunCheck {args}  {
    global tmpRoot threshold average interval
    set once 0
    APSStrictParseArguments {once}

    if $once {
        setStatusText "Working..."
        set averageHere 1
    } else {
        set averageHere $average
    }
    exec sddssnapshot -average=$averageHere,$interval $tmpRoot.setpointsReq $tmpRoot.setpoints -nameOfData=Setpoint
    exec sddssnapshot -average=$averageHere,$interval $tmpRoot.dcctsReq -pipe=out -nameOfData=ExtDCCT \
      | sddsxref $tmpRoot.setpoints -pipe -match=MagnetName -take=Setpoint,IsMain \
      | sddsprocess -pipe -match=col,MagnetName=*C:*,! "-define=col,AbsDelta,Setpoint ExtDCCT - abs" \
        "-define=col,OutOfSpec,IsMain 1 == ? $threshold(1) : $threshold(0) $ AbsDelta < ? 1 : 0 $ ,type=short" \
        -filter=col,OutOfSpec,1,1 -nowarning \
      | sddssort -pipe -column=AbsDelta,decr \
      | tee $tmpRoot.delta \
      | sddsprintout -pipe=in $tmpRoot.txt -column=MagnetName -column=Setpoint,format=%10.3f  -column=ExtDCCT,format=%10.3f \
      -column=AbsDelta,format=%10.3f
    if $once {
        catch {destroy .display}
        APSFileDisplayWindow .display -fileName $tmpRoot.txt
        setStatusText "Done checking once."
    }
}

set abortRequested 0

proc Monitor {} {
    global tmpRoot threshold abortRequested
    setStatusText "Monitoring..."
    APSEnableButton .userFrame.stop.button
    APSDisableButton .userFrame.monitor.button
    update
    while {!$abortRequested} {
        RunCheck
        if [catch {exec sdds2stream -rows=bare $tmpRoot.delta} count] {
            setStatusText "$count"
        } else {
            if $count!=0 {
                setStatusText "[clock format [clock seconds]]: $count problems detected."
                bell
            } else {
                setStatusText "[clock format [clock seconds]]: no problems detected."
            }
        }
        APSWaitWithUpdate -waitSeconds 5 -updateInterval 1
    }
    setStatusText "Monitoring aborted."
    APSEnableButton .userFrame.monitor.button
    APSDisableButton .userFrame.stop.button
}


proc PrepareInputFiles {} {
    global tmpRoot
    setStatusText "Preparing input files..."
    exec sddsprocess /home/helios/oagData/SCR/requestFiles/SR.req $tmpRoot.setpointsReq -match=col,ControlName=*:PS:SetCurrentC \
         -edit=col,MagnetName,ControlName,%/:PS:SetCurrentC// \
        "-define=col,IsMain,MagnetName \"*\[HVT\]*\" strmatch ? 0 : 1 $,type=short" 
    exec sddsprocess /home/helios/oagData/SCR/requestFiles/SR.req $tmpRoot.dcctsReq -match=col,ControlName=*:DCCT:CurrentM \
         -edit=col,MagnetName,ControlName,%/:DCCT:CurrentM//
    setStatusText "Ready."
}

APSLabeledEntry .threshold0 -parent .userFrame -textVariable threshold(0) -label "Threshold for bipolar supplies: " -type real
APSLabeledEntry .threshold1 -parent .userFrame -textVariable threshold(1) -label "Threshold for unipolar supplies: " -type real

APSLabeledEntry .average    -parent .userFrame -textVariable average      -label "Average" \
                -contextHelp "Use average of 10, say, while offsets are measured"

APSButton .run -parent .userFrame -command "RunCheck -once 1" -text "Check"

APSButton .monitor -parent .userFrame -command "set abortRequested 0; Monitor" -text "Monitor"
APSButton .stop -parent .userFrame -text "Stop monitoring" -command "set abortRequested 1; setStatusText \"Aborting... wait for cycle to complete.\""
APSDisableButton .userFrame.stop.button

PrepareInputFiles
