#!/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
set CVSRevisionAuthor "\$Revision: 1.20 $ \$Author: borland $"

set SrVhistDataDir /home/helios/oagData/monitoring/SRvacIG

proc SRVacuumHistoryOverview {} {
        return "This is the storage vacuum history review utility.\n\
It allows you to review archived data on storage ring vacuum.  The plot interface allows printing and saving the plot."
        }

APSApplication . -name SRVacuumHistory -version $CVSRevisionAuthor -overview [SRVacuumHistoryOverview] 

proc MakeDailyPlotButtons {widget args} {
    set parent ""
    APSParseArguments {parent}
    set w $parent$widget
    frame $w
    pack $w -side top -fill x
    frame $w.cb 
    frame $w.ob 
    pack $w.cb $w.ob -side top -fill x
    APSButton .splot -parent $w.ob -text "SUMMARY PLOT" -command DoVhistSummaryPlot \
      -contextHelp "Plots minimum, maximum, and average ion gauge data for the selected day and shift."
    APSButton .mplot -parent $w.ob -text "DETAIL PLOT" -command DoVhistDetailPlot \
      -contextHelp "Plots ion gauge data for the selected day and shift in movie form."
}

proc DoVhistSummaryPlot {} {
    global SrVhistYear SrVhistMonth SrVhistDay SrVhistShift 
    global SrVhistDataDir
    SetSrVhistStatus "Working..."
    SetSrVhistStatus \
      [MakeVacuumHistoryPlots -year $SrVhistYear -month $SrVhistMonth -day $SrVhistDay \
         -shift $SrVhistShift -dataDir $SrVhistDataDir ] 
}

proc DoVhistDetailPlot {} {
    global SrVhistYear SrVhistMonth SrVhistDay SrVhistShift 
    global SrVhistDataDir
    SetSrVhistStatus "Working..."
    SetSrVhistStatus \
      [MakeVacuumDetailPlots -year $SrVhistYear -month $SrVhistMonth -day $SrVhistDay \
         -shift $SrVhistShift -dataDir $SrVhistDataDir ] 
}

proc SetSrVhistStatus {text} {
    global SrVhistStatus
    set SrVhistStatus $text
    update
} 

proc MakeCombinedFile {rootname} {
    set fileList [glob -nocomplain "$rootname.\[0-9\]\[0-9\]\[0-9\]\[0-9\]"]
    if [llength $fileList]==0 {
        return ""
    }
    set tmpfile /tmp/[APSTmpString]
    if [catch {eval exec sddscombine $fileList $tmpfile} result] {
        return ""
    }
    return $tmpfile
}

proc MakeVacuumDetailPlots {args} {
    set year ""
    set day ""
    set month ""
    set shift ""
    set dataDir /home/helios/oagData/monitoring/SRvacIG
    APSParseArguments {year day month shift dataDir}
    set dateTag [APSFormatDate -day $day -month $month -year $year -dateFormat Y-J-MD]
    set filename  $dataDir/SRvacIG-${dateTag}
    set removeFile 0
    if {![file exists $filename] && ![file exists ${filename}.gz]} {
        set filename [MakeCombinedFile $dataDir/SRvacIG-${dateTag}]
        if [string length $filename]==0 {
            return "No file found for that day."
        }
        set removeFile 1
    }
    switch $shift {
        0       {set timeStart 0 ; set timeEnd 24 }
        1       {set timeStart 0 ; set timeEnd 8  }
        2       {set timeStart 8 ; set timeEnd 16 }
        3       {set timeStart 16; set timeEnd 24 }
        default {
            return "Invalid shift: must be 0, 1, 2, or 3"
        }
    }
    set tmpFile ""
    if {![file exists $filename]} {
        set tmpFile /tmp/[APSTmpString]
        exec gzip -dcn ${filename}.gz > $tmpFile
        set filename $tmpFile
        set removeFile 0
        if {![file exists $filename]} {
            return "Attempt to melt frozen data file failed."
        }
    }
    set vacFile /tmp/[APSTmpString]
    exec sddsprocess $filename $vacFile \
      "-redefine=param,TimeOfDay,TimeOfDay,units=h,description=,symbol=t" \
      "-define=param,IntHour,TimeOfDay int,units=hr,type=long" \
      "-define=param,IntMins,TimeOfDay IntHour - 60 * int,units=min,type=long" \
      "-edit=param,DateString,TimeStamp,3F1D" \
      "-print=param,TimeString,%s %02ld:%02ld,DateString,IntHour,IntMins" \
      "-filter=param,TimeOfDay,$timeStart,$timeEnd" -nowarnings  \
      "-filter=col,VGC1.PRES,1e-12,1e-4" \
      "-define=col,logVGC1.PRES,VGC1.PRES 1e9 * log,symbol=Log\$b10\$n Pressure,units=nT"
    if {[exec sddscollapse $vacFile -pipe=out | sdds2stream -rows -pipe=in]=="0 rows"} {
        return "No data for that shift."
    }

    exec sddsplot -labelsize=0.0225 -groupby=page -separate=page -title=@TimeString -same \
      "-topline=Storage ring ion gauge detailed history" \
      -col=Index,logVGC1.PRES $vacFile -graph=bar,vary=type \
        -ticks=ylog "-ylabel=Pressure (nT)" \
        -offset=xchange=1 -xlabel=Sector \
      -split=page,column=logVGC1.PRES,start=-12,width=1  &

    if {$vacFile!=""} { after [expr 5*60*1000] "exec rm $vacFile" }
    if {$tmpFile!=""} { after [expr 5*60*1000] "exec rm $tmpFile" }
    if $removeFile { after [expr 5*60*1000] "exec rm $filename" }

    return "OK."
}

proc MakeVacuumHistoryPlots {args} {
    set year ""
    set day ""
    set month ""
    set shift ""
    set dataDir /home/helios/oagData/monitoring/SRvacIG
    APSParseArguments {year day month shift dataDir}
    set dateTag [APSFormatDate -year $year -month $month -day $day -dateFormat Y-J-MD]
    set filename  $dataDir/SRvacIG-${dateTag}
    if {![file exists $filename] && ![file exists ${filename}.gz] && ![file exists ${filename}.proc.gz]} {
        return "No file found for that day."
    }
    switch $shift {
        0       {set timeStart 0 ; set timeEnd 24 }
        1       {set timeStart 0 ; set timeEnd 8  }
        2       {set timeStart 8 ; set timeEnd 16 }
        3       {set timeStart 16; set timeEnd 24 }
        default {
            return "Invalid shift: must be 0, 1, 2, or 3"
        }
    }
    set vacTmp ""
    set tmpFile ""
    set tmpFile1 ""
    if ![file exists ${filename}.proc.gz] {
        if {![file exists $filename]} {
            set tmpFile /tmp/[APSTmpString]
            exec gzip -dcn ${filename}.gz > $tmpFile
            set filename $tmpFile
            if {![file exists $filename]} {
                return "Attempt to melt frozen data file failed."
            }
        }
        set names ""
        catch { set names [exec sddsquery $filename -parameter | grep VGC1.PRES ] }
        set namelist [split $names]
        if [llength $namelist]!=3 {
            set tmpFile1 /tmp/[APSTmpString]
            exec sddsprocess $filename $tmpFile1 "-test=param,n_rows 0 >" \
              -filter=col,VGC1.PRES,1e-30,1e-4  \
              -process=VGC1.PRES,min,MinVGC1.PRES \
              "-redefine=param,MinVGC1.PRES,MinVGC1.PRES 1e9 *,symbol=Min\[VGC1\],units=nTorr" \
              -process=VGC1.PRES,max,MaxVGC1.PRES \
              "-redefine=param,MaxVGC1.PRES,MaxVGC1.PRES 1e9 *,symbol=Max\[VGC1\],units=nTorr" \
              -process=VGC1.PRES,ave,AveVGC1.PRES \
              "-redefine=param,AveVGC1.PRES,AveVGC1.PRES 1e9 *,symbol=Ave\[VGC1\],units=nTorr"
            set filename $tmpFile1
        }
        set vacTmp /tmp/[APSTmpString]
        set vacFile $vacTmp
        exec sddscollapse $filename -pipe=out | sddsprocess -pipe=in $vacFile \
          "-redefine=column,TimeOfDay,TimeOfDay,units=h,description=,symbol=t" \
          "-filter=column,TimeOfDay,$timeStart,$timeEnd" -nowarnings 
        if {[exec sdds2stream -rows $vacFile]=="0 rows"} {
            return "No data for that shift."
        }
    } else {
        set vacFile $filename.proc.gz
    }

    exec sddsplot -labelsize=0.03 -pspace=0,0,0.175,0.9 \
      "-column=TimeOfDay,(MinVGC1.PRES,MaxVGC1.PRES,AveVGC1.PRES)" \
        $vacFile "-xlabel=Time (hours)" \
      "-ylabel=Pressure (nT)" -legend -graph=line,vary \
      "-topline=Storage ring ion gauge data" \
      "-title=Date: ${month}${day}${year}    Shift: $shift" \
      -limit=xmin=$timeStart,xmax=$timeEnd,ymax=1e6,ymin=1e-6 -mode=y=log,y=special \
      -sever=xgap=-1.5 &

    if {$vacTmp!=""} { after 30000 "exec rm $vacTmp" }
    if {$tmpFile!=""} { after 30000 "exec rm $tmpFile" }
    if {$tmpFile1!=""} { after 30000 "exec rm $tmpFile1" }

    return "OK."
}

proc MakeShiftEntry {widget args} {
    set parent ""
    set variable ""
    APSParseArguments {parent variable}
    set w $parent$widget
    if {$variable == ""} { return 0 }
    global $variable
    frame $w 
    pack $w -side top
    radiobutton $w.s1 -text Owl -variable $variable -value 1
    radiobutton $w.s2 -text Day -variable $variable -value 2
    radiobutton $w.s3 -text Evening -variable $variable -value 3
    radiobutton $w.s0 -text All -variable $variable -value 0
    pack $w.s1 $w.s2 $w.s3 $w.s0 -side left -fill x
}

proc DoVhistMonthlyPlot {args} {
    global SrVhistYear SrVhistMonth SrVhistDay SrVhistShift 
    global SrVhistDataDir
    set mode summary
    APSParseArguments {mode}

    SetSrVhistStatus "Working..." 
    SetSrVhistStatus [MakeVacuumMonthlyPlot -year $SrVhistYear -month $SrVhistMonth \
                        -dataDir $SrVhistDataDir -mode $mode ] 
}

proc MakeVacuumMonthlyPlot {args} {
    set year ""
    set month ""
    set dataDir ""
    set mode "summary"
    APSParseArguments {year month dataDir mode} 
    scan $month "%ld" month
    set month [format "%02ld" $month]
    set year [APSMakeFourDigitYear $year]
    set filename $dataDir/SRvacIG-${year}-${month}
    if ![file exists $filename] {
        return "No summary data for that month."
    }
    if {$mode=="detail"} {
        set tmpfile /tmp/[APSTmpString]
        exec sddscombine $filename -merge -pipe=out \
          | sddsbreak -pipe -decreaseOf=TimeOfDay  \
          | sddsprocess -pipe=in $tmpfile -filter=col,TimeOfDay,0,24 \
          -process=DayOfMonth,ave,Day \
          "-print=param,DateString,${month}/%.0f/${year},Day"  
        exec sddsplot -split=page -filter=col,DayOfMonth,0,0,\! \
          "-title=" "-topline=Storage ring vacuum gauge data monthly detail plot." -labelsize=0.025 \
          "-column=TimeOfDay,(MinVGC1.PRES,MaxVGC1.PRES,AveVGC1.PRES)" -mode=y=log,y=special \
          -limit=ymax=1e6,ymin=1e-6 -sever=xgap=-1.5 \
          -graph=line,vary,eachpage -legend "-ylabel=Pressure (nTorr)" $tmpfile \
          "-title=@DateString" \
          "-split=page" "-separate=page" &
        return "OK.  Expect a plot with about 30 pages."
        after 60000 "exec rm $tmpfile"
    } else {
        exec sddsplot -split=page -filter=col,DayOfMonth,0,0,\! \
          "-title=" "-topline=Storage ring vacuum gauge data monthly summary" -labelsize=0.025 \
          "-column=DayOfMonth,(MinVGC1.PRES,MaxVGC1.PRES,AveVGC1.PRES)" -mode=y=log,y=special \
          "-xlabel=Day of Month"  \
          -limit=ymax=1e6,ymin=1e-6 -sever=xgap=-1.5 \
          -graph=line,vary,eachpage -legend "-ylabel=Pressure (nTorr)" $filename \
          "-title=Month: ${month}/${year}" &
        return "OK.  Expect a single-page plot."
    }
}

APSStatusLine .status -parent .userFrame -variable SrVhistStatus  -width 40
set SrVhistStatus "Ready."

frame .userFrame.daily -bd 2 -relief raised
pack .userFrame.daily -fill x -side top
label .userFrame.daily.label -text "PLOTS BY DAY AND SHIFT" -relief ridge
pack .userFrame.daily.label -side top -fill x 
frame .userFrame.daily.data  -relief raised
pack .userFrame.daily.data -fill x -side top
APSDateEntry .date -dayVariable SrVhistDay -yearVariable SrVhistYear \
  -monthVariable SrVhistMonth -parent .userFrame.daily.data

set hourOfDay [exec date +%H]
if {[string compare $hourOfDay "09"]!=1} {
    set hourOfDay [string range $hourOfDay 1 1]
}
set SrVhistShift 0
MakeShiftEntry .shift -variable SrVhistShift -parent .userFrame.daily.data
frame .userFrame.daily.ops 
pack .userFrame.daily.ops -fill x -side top

MakeDailyPlotButtons .userFrame.daily.ops.plbuttons 

frame .userFrame.monthly -bd 2 -relief raised
pack .userFrame.monthly -fill x -side top
label .userFrame.monthly.label -text "PLOTS BY MONTH" -relief ridge
pack .userFrame.monthly.label -fill x -side top
APSYearMonthEntry .date -yearVariable SrVhistYear -monthVariable SrVhistMonth -parent .userFrame.monthly
frame .userFrame.monthly.ops 
pack .userFrame.monthly.ops -fill x -side top
APSButton .splot -parent .userFrame.monthly.ops -text "SUMMARY PLOT" -command "DoVhistMonthlyPlot -mode summary" \
  -contextHelp "Plots statistical data for ion gauges for the selected month on one page."
APSButton .dplot -parent .userFrame.monthly.ops -text "DETAIL PLOT" -command "DoVhistMonthlyPlot -mode detail" \
  -contextHelp "Plots statistical data for ion gauges for the selected month using one page per day."


