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

set CVSRevisionAuthor "\$Revision: 1.4 $ \$Author: emery $"

APSDebugPath
APSStandardSetup
set comment ""
proc SetStatus {text} {     
    global mainStatus
     
    set mainStatus "[clock format [clock seconds] -format %H:%M:%S] $text"
    
    update      
}   

proc CollectData {args} {
    global rootname directory comment OAGGlobal
    
    if [catch {APSSRCheckCorrectorMode -plane h} hCorrMode] {
        APSAlertBox .alert -errorMessage "$hCorrMode"
        return
    }
    if [catch {APSSRCheckCorrectorMode -plane v} vCorrMode] {
        APSAlertBox .alert -errorMessage "$vCorrMode"
        return
    }
    if [string compare $hCorrMode $vCorrMode]!=0 {
        APSAlertBox .alert -errorMessage "The corrector modes in x and y plane are not consistent!"
        return
    }
    if [string compare $hCorrMode vector]!=0 {
        SetStatus "The corrector is not in vector mode now, quite collecting DP corr history!"
        return
    }
    if [catch {exec cavget -list=DP:S:OrbitControlLawXSDDS.RUN -pend=30} running] {
        SetStatus "$running"
        return
    }
    if !$running {
        SetStatus "Horizontal datapool oc is not running - quite collecting data."
        return
    }
    if [catch {exec cavget -list=DP:S:OrbitControlLawYSDDS.RUN -pend=30} running] {
        SetStatus "$running"
        return
    }
    if !$running {
        SetStatus "Vertical datapool oc is not running - quite collecting data."
        return
    }
    
    if [catch {exec cavget -list=S-DCCT:CurrentM -pend=30} current] {
        SetStatus "$current"
        return
    }
    if {$current<3.0} {
        SetStatus "There is not stored beam now. (SR current=$current mA)"
        return
    }
    set filename $directory/${rootname}[clock format [clock seconds] -format "%Y-%j-%m%d-%H%M%S"]
    if [catch {APSCollectDPCorrectorHistory -filename  $filename} result] {
        SetStatus "Collecting DP corr history failed: $result"
        return
    }
    set tmpRoot /tmp/[APSTmpString]
    if [catch {exec sddsprocess $filename \
                   -pipe=out -process=S*\[HV\]*,spread,%sSpread \
                   -process=S*\[HV\]*,qrange,%sQrange \
                   -process=S*\[HV\]*,drange,%sDrange \
                   -process=S*\[HV\]*,standardDeviation,%sStdDev \
                   | sddscollapse -pipe \
                   | sddsconvert -pipe -retain=col,S*\[HV\]* \
                   | sddscollect -pipe=in $tmpRoot.1 \
                   -collect=suffix=Spread -collect=suffix=Qrange \
                   -collect=suffix=Drange -collect=suffix=StdDev } result] {
        return -code error $result
    }
    set corrPositionFile $OAGGlobal(SRLatticesDirectory)/scripts/SRCorrPosition.xref
    if [catch {exec sddsprocess $tmpRoot.1 -match=col,Rootname=*H* $tmpRoot.h
        exec sddsprocess $tmpRoot.1 -match=col,Rootname=*V* $tmpRoot.v
        exec sddscombine $tmpRoot.h $tmpRoot.v -pipe=out\
                 | sddsxref -pipe $corrPositionFile -take=s -match=Rootname=CorrName \
                 -nowarnings -reuse=page \
                 | sddsprocess -pipe \
                 "-print=para,Comment,[APSMakeSafeQualifierString [APSMakeSafeQualifierString $comment]]" \
                 | sddssort -pipe=in $filename -col=s } result] {
        return -code error $result
    }
    catch {exec gzip $filename}
    SetStatus "Data collected and processed in $filename.gz"
    PlotData -filename $filename.gz
}

proc ViewData {args} {
    global directory rootname 
    set filename [APSFileSelectDialog .openDialog -listDir $directory \
                      -pattern ${rootname}*.gz -width 100]
    if ![string length $filename] {
        SetStatus "No file was chosen."
        return
    }
    PlotData -filename $filename
}

proc PlotData {args} {
    set filename ""
    APSParseArguments {filename}
    if ![string length $filename] {
        return
    }
    if ![file exist $filename] {
        SetStatus "$filename does not exist!"
        return
    }
    
    global Spread Qrange Drange StdDev 
    if [catch {exec sdds2stream -para=Comment $filename} result] {
        set title ""
    } else {
        set title [lindex $result 0]
    }
    if {!$Spread && !$Qrange && !$Drange && !$StdDev} {
        SetStatus "No quantity is selected for plotting."
        return
    }
    set plotCmd "-split=page -sep=page -grap=line,vary -legend -topline=[file tail $filename] -enumeratedScales=interval=10 "
    lappend plotCmd \"-title=[APSMakeSafeQualifierStringForEvalSddsplot $title]\"

    if $Spread {
        lappend plotCmd "-col=Rootname,Spread"
        # exec sddsplot -split=page -sep -col=Rootname,Spread -enumeratedScales=interval=10 $filename &
    }
    if $Qrange {
        lappend plotCmd "-col=Rootname,Qrange"
        #exec sddsplot -split=page -sep -col=Rootname,Qrange -enumeratedScales=interval=10 $filename &
    }
    if $Drange {
        lappend plotCmd "-col=Rootname,Drange"
        #exec sddsplot -split=page -sep -col=Rootname,Drange -enumeratedScales=interval=10 $filename &
    }
    if $StdDev {
        lappend plotCmd "-col=Rootname,StdDev"
        #exec sddsplot -split=page -sep -col=Rootname,StdDev -enumeratedScales=interval=10 $filename &
    }
    eval exec sddsplot [join $plotCmd] $filename &
}

APSApplication . -name DPCorrectorWaveformStats -version $CVSRevisionAuthor \
    -overview {This application collects dp corrector waveform history during datapool orbit correction and process the data to obtain the various ranges (qrange, drange, spread) and standarddeviatition and display it.}

set mainStatus ""
APSScrolledStatus .status -parent .userFrame -textVariable mainStatus -width 100 \
    -withButtons 1

set rootname "DPCorrHistory"
set comment ""
APSLabeledEntry .root -parent .userFrame -label "Rootname:" \
    -textVariable rootname -width 70
set directory [APSGoToDailyDirectory]
APSLabeledEntry .dir -parent .userFrame -label "Output directory:" \
    -textVariable directory -width 70
APSButton .sel -parent .userFrame.dir -text "Select" -size small \
    -command {set directory [APSFileSelectDialog .choosedirectory -listDir $directory \
                                 -title "Choose a directory for output files" -selectDir 1]}
APSLabeledEntry .com -parent .userFrame -label "Comment:" \
    -textVariable comment -width 70
foreach var {Spread Qrange Drange StdDev} {
    set $var 1
}
APSCheckButtonFrame .check -parent .userFrame -buttonList {spread qrange drange stdDev} \
    -variableList {Spread Qrange Drange StdDev} -label "Select quantity for plotting:" \
    -orientation horizontal -allNone 1
APSButton .collect -parent .userFrame -text "CollectData" \
    -command "CollectData"
APSButton .plot -parent .userFrame -text "View" \
    -command "ViewData"
