#!/bin/sh
# \
exec oagwish "$0" "$@"

# $Log: not supported by cvs2svn $
# Revision 1.8  1999/08/13 18:55:37  borland
# Fixedproblem with reading a live file by adding recovery operation
# to sddsconvert.
#
# Revision 1.7  1998/12/22 15:18:37  borland
# Per Blachowicz, now pops up an error dialog when there are no data files.
#
# Revision 1.6  1998/08/06 20:15:48  borland
# Added -retain=column,Time option to sddsconvert in time-range finding
# code, so it runs faster.
#
# Revision 1.5  1998/08/06 20:13:04  borland
# Added sddsconvert -recover ahead of sddsprocess command that gets the
# start and end time.  For some reason, this is needed because the file
# updates while it is being read.
#
# Revision 1.4  1998/07/15 13:54:06  borland
# New version per D. Blachowicz: added time filter input and display of
# time limits of data.  Added export and quickSDDSplot features.
#
# Revision 1.3  1998/05/19 22:31:28  emery
# Added this comment in order for cvs to start logging the changes.
#

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.9 $ \$Author: emery $"

set usage "usage: SRRFControllawReview -group <value>"
set group "3840"
set args $argv
APSParseArguments {group}

switch $group {
    3840 {
        set anum 1
        set bnum 4
        set cnum 4
    }
    3637 {
        set anum 2
        set bnum 3
        set cnum 2
    }
    default {
        puts stderr "Invalid group name: $group"
        exit 1
    }
}


APSApplication . -name SRRFControllawReview -version $CVSRevisionAuthor \
  -overview "Displays activity data for the SR RF gap voltage controllaw, showing the plot for each chosen area."

set dataDir /home/helios/oagData/controllaw/SRgapVoltage/loggedData
cd $dataDir

set statusText "Ready."
APSScrolledStatus .status -parent .userFrame -textVariable statusText -width 60 \
  -contextHelp "Displays number of launched plots." 
update

APSFrame .scrollframe -parent .userFrame -label "Logged Files List: "

if [catch {glob rf${group}Err-*.log rf${group}*.log.gz } rfList] {
    set SRrfList ""
    bell
    APSAlertBox [APSUniqueName .] -errorMessage "No files found from $group group."
} else {
    set SRrfList [lsort -decreasing $rfList]
}

APSScrolledList .fileList -parent .userFrame.scrollframe.frame -name "Logged File List" \
  -height 10 -selectMode single \
  -itemList $SRrfList -packOption "-side top" \
  -callback PickTheFile \
  -contextHelp "List of Logged files from SRrf system activity.  Click on a filename to select.  The filename format is rf<SectorPair>Err-<Year>-<MonthDay>-<StartTime>.log\[.gz\]" 

set fileName ""
APSLabeledOutput .entryLab -parent .userFrame -label "Selected File " \
  -textVariable fileName -width 27 -packOption "-anchor w"\
  -contextHelp "Display of active logged file."

set startTimeStamp ""
APSLabeledOutput .starting -parent .userFrame -label "Starting time:" \
	-width 27 -textVariable startTimeStamp -packOption "-anchor w" \
	-contextHelp "Starting time of selected file"

set endTimeStamp ""
APSLabeledOutput .ending -parent .userFrame -label "  Ending time:" \
  -width 27 -textVariable endTimeStamp -packOption "-anchor w" \
  -contextHelp "Ending time of selected file"

APSDateTimeAdjEntry .startentry -parent .userFrame -dayVariable startDay \
  -monthVariable startMonth -yearVariable startYear -hourVariable startHour \
  -label "Set starting time of interest"

APSDateTimeAdjEntry .endentry -parent .userFrame -dayVariable endDay \
  -monthVariable endMonth -yearVariable endYear -hourVariable endHour \
  -label "  Set ending time of interest"


proc PickTheFile {selectItem doubleClick} {
    global fileName dataDir 
    global startYear startMonth startDay startHour startTimeStamp startTotalSec 
    global endYear endMonth endDay endHour endTimeStamp endTotalSec 
    set fileName $selectItem 
    if $doubleClick {

        APSSetVarAndUpdate statusText "Working..."

        if [file exists $dataDir/$fileName] {
            if [catch {eval exec sddsconvert $fileName -pipe=out -recover=clip \
                         -retain=column,Time \
                         | sddsprocess -pipe \
                         -noWarnings -clip=1,1,invert \
                         | sdds2stream -pipe=in -column=Time} result] {
                APSSetVarAndUpdate statusText "proc PickTheFile: $result"
                return
            }
            set startTotalSec [lindex $result 0]
            set endTotalSec [lindex $result 1]
            if [catch {exec timeconvert -seconds=$startTotalSec -script=start} commands] {
                APSSetVarAndUpdate statusText "Error: $commands"
                return
            }
            eval $commands
            set startHour [format %.2d:%.2d:%.2d $startHours $startMinutes $startSeconds]
            if [catch {exec timeconvert -seconds=$endTotalSec -script=end} commands] {
                APSSetVarAndUpdate statusText "proc PickTheFile: $commands"
                return
            }
            eval $commands
            set endHour [format %.2d:%.2d:%.2d $endHours $endMinutes $endSeconds]
            update
        }
        APSSetVarAndUpdate statusText "Done."
    }
}

proc TimeFrameForFile {} {
    global startYear startMonth startDay startHour startTime
    global endYear endMonth endDay endHour endTime
    global fileName tmpFile selectionVarList columnList
    set tmpFile /tmp/[APSTmpString]
    set varList ""
    set index 0

    foreach selectionVar $selectionVarList {
        global $selectionVar

        if [subst \$$selectionVar] {
            lappend varList [lindex $columnList $index]
        }
        incr index
    }

    if ![llength $varList] {
        return -code error "None of variables is selected."
    }
    
    set varString [join $varList ,]

    if {[catch {APSConvertTimeToHours $startHour} hour0] || \
          [catch {APSConvertTimeToHours $endHour} hour1]} {
        APSAlertBox [APSUniqueName .] -errorMessage "Bad hour syntax in time filter."
        return -code error "Bad hour syntax in time filter."
    }

    if [catch {eval exec timeconvert -breakDown=year=$startYear,month=$startMonth,day=$startDay,hour=$hour0} startTime] {
        return -code error "Error: $startTime" 
    }
    if [catch {eval exec timeconvert -breakDown=year=$endYear,month=$endMonth,day=$endDay,hour=$hour1} endTime] {
        return -code error "Error: $endTime"
    }
    if [catch {eval exec sddsconvert $fileName -pipe=out \
                 {"-retain=col,Time,$varString"} -recover=clip -nowarning \
                 | sddsprocess -pipe=in $tmpFile {"-noWarnings"} \
                 {"-filter=column,Time,${startTime},${endTime}"}} result] {
        return -code error "Error: $result"
    }
    return -code ok
}

proc Plot { } {
    global toplineList columnList selectionVarList fileName statusText tmpFile
    set acom "-graph=line,vary"
    set bcom "-ticks=xtime"
    set ccom "-legend &"
    set plotList ""
    set index -1
    set number 0

    APSSetVarAndUpdate statusText "Working..."
    APSSetVarAndUpdate statusText "Please wait, executing plotting..."

    if {[string length $fileName] == 0}  {
        set statusText "No log file has been selected"
    } else {
        if [catch {TimeFrameForFile} result] {
            APSSetVarAndUpdate statusText "$result"
            return
        }
        foreach selectionVar $selectionVarList {
            global $selectionVar
            incr index

            if [subst \$$selectionVar] {
                lappend plotList -column=Time,[lindex $columnList $index] 
                lappend plotList -topline=[lindex $toplineList $index] 
                lappend plotList $tmpFile
                lappend plotList $acom 
                lappend plotList $bcom 
                lappend plotList $ccom    
                lappend plotList -end
                
                incr number
            }
        }
        if [llength $plotList] {
            
            eval exec sddsplot $plotList &
            if {$number == 1} {
                set statusText "$number plot launched"
            } else { 
                set statusText "$number plots launched"
            }
        } else {
            set statusText "No plots selected."
        }
    }
}

proc Butt_2_3_Exec {command} {
    global tmpFile
    global startYear startMonth startDay startHour
    global endYear endMonth endDay endHour

    APSSetVarAndUpdate statusText "Working..."
    APSSetVarAndUpdate statusText "Please wait, executing $command..."

    set startT [list $startYear $startMonth $startDay $startHour]
    set endT [list $endYear $endMonth $endDay $endHour]

    if [catch {TimeFrameForFile} result] {
        APSSetVarAndUpdate statusText "$result"
        return
    }

    APSExec -unixCommand "$command -dataFileList $tmpFile \
             -timeFilterStart \"$startT\" -timeFilterEnd \"$endT\""

    APSSetVarAndUpdate statusText "$command is done."
}

proc AddGroup {buttonName columnOption} {
    global toplineList buttonList selectionVarList columnList nGroups
    lappend buttonList $buttonName
    lappend toplineList $buttonName
    lappend columnList $columnOption
    lappend selectionVarList selectionVar$nGroups
    incr nGroups
}

set tmpFile ""
set buttonList ""
set selectionVarList ""
set columnList ""
set nGroups 0

# These groups are wildcards for plotting.
AddGroup "Gap Voltage Error" S?TotalGapVoltageError
AddGroup "Gap Voltage" S?TotalGapGapVolt
AddGroup "Cavity Forward Power" "S?:C:envDet?Ch0KWatt"
AddGroup "Cavity Field Probe Power" "S?:C:envDet?Ch2KWatt"
AddGroup "AGC setpoint" S?:setpoint
AddGroup "Klystron Voltage" S?:KPS:beamVoltageV
AddGroup "Klystron Current" S?:KPS:beamCurrent
AddGroup "Klystron Anode Voltage" S?:KPS:anodeVoltage
AddGroup "Klystron feedback setpoint" S?:K:feedback*
AddGroup "AGC engage" S?:K:FB_EngageBI"
AddGroup "Klystron Power" "S?:K:envDet?Ch?KWatt"

APSCheckButtonFrame .rb1 -parent .userFrame -label "Groups: " \
  -buttonList $buttonList -allNone 1 -limitPerRow 6 \
  -variableList $selectionVarList -orientation vertical \
  -contextHelp "Button for selection of readback and control variables for plotting." 

APSButton .butt1 -parent .userFrame -text "Plot" -command Plot -contextHelp \
  "Plot button causes a display of a number of launched plots in the status window & invokes a creation of the plots"
APSButton .butt2 -parent .userFrame -text "quickSDDSplot..." \
  -command "Butt_2_3_Exec quickSDDSplot" -contextHelp "Click to launch quickSDDSplot"

APSButton .butt3 -parent .userFrame -text "Export..." \
  -command "Butt_2_3_Exec sddsExportData" -contextHelp "Click to export SDDS file"

update
