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

#
# $Log: not supported by cvs2svn $
# Revision 1.5  2000/08/24 05:08:50  emery
# Test differently the need for generating a reference file
# of audit files. Cleaned up the synatx, i.e. removed " and { }
# pairs where they weren't needed. Reduced the reliance on global
# variable for passing file names between procedures.
# Use APS*TmpFile procedures to clean up temp files at the end
# of execution.
#
# Revision 1.4  2000/02/21 23:18:27  emery
# Added -same=x option for plotting. Indented code, and removed
# extraneous curly braces and quotations marks.
#
# Revision 1.3  1998/08/24 16:36:48  borland
# New version by D. Blachowicz. Much faster due to better composition of
# matching commands and a single invocation of sddsprocess.
#
# Revision 1.2  1998/07/14 15:12:32  borland
# New version per D. Blachowicz.  Works faster by determining the start/end
# time for each audit file, then only using those files that are relevant
# to the user's specified time interval.
#
# Revision 1.1  1998/05/26 20:40:53  borland
# First version, by D. Blachowicz.
#
#
set CVSRevisionAuthor "\$Revision: 1.6 $ \$Author: shang $"

APSApplication . -name SRSteeringActivityReview -version $CVSRevisionAuthor \
  -overview "Displays activity data for the SR beam steering, showing the plot for each chosen area."

set dataDir /home/helios/oagData/logDaemonData/steeringAudit
set resDataDir /home/helios/oagData/logDaemonData

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

set logsList [glob -nocomplain ${dataDir}/steeringAudit.log.*]
lappend logsList [glob -nocomplain $resDataDir/steeringAudit.log]
set ordLogsList [lsort $logsList]
set refFile /home/helios/oagData/logDaemonData/publicFiles/SteeringAudit.ref

proc InitViewTime {} {
    global buttList secVarList statusText instanceList steeringActivity
    global ordLogsList printoutString actionType refFile
    global StartYear StartMonth StartDay StartHour dataDir
    global EndYear EndMonth EndDay EndHour instanceList

    set intervalString "$StartMonth/$StartDay/$StartYear $StartHour and $EndMonth/$EndDay/$EndYear $EndHour"

    set fileList ""
    set instanceList ""
    setOpenCloseResetBut 0
    setOpenCloseViewBut 0
    set statusText "Working..."
    update
    set tempFile /tmp/[APSTmpString]

    #This is in the case of hour selection in format 0:00:00
    set sHour [APSConvertTimeToHours ${StartHour}] 
    set eHour [APSConvertTimeToHours ${EndHour}]
    set lowLimit [exec timeconvert -breakDown=year=${StartYear},month=${StartMonth},day=${StartDay},hour=$sHour]
    set highLimit [exec timeconvert -breakDown=year=${EndYear},month=${EndMonth},day=${EndDay},hour=$eHour]
    
    if {$lowLimit >= $highLimit} {
        set statusText "Wrong time frame selection!"
        setOpenCloseViewBut 1
        return
    }

    set processFileList \
      [APSFindFilesBetweenDates -tailsOnly 0 -extensionList {"*"}\
         -directory $dataDir \
         -startDateList [APSFormatDate -year $StartYear -month $StartMonth \
                           -day $StartDay -dateFormat list] \
         -endDateList [APSFormatDate -year $EndYear -month $EndMonth \
                         -day $EndDay -dateFormat list] ]
    if [llength $processFileList] {
        if [catch {eval exec sddscombine $processFileList -pipe=out -merge \
                     | sddsprocess -pipe -noWarnings \
                     -filter=column,Time,$lowLimit,$highLimit \
                     | sddstimeconvert -pipe=in $tempFile \
                     -breakdown=col,Time,year=Year,month=Month,day=Day,hour=Hour,text=${actionType}Time \
                 } result] {
            set statusText $result
            return
        }
    } else {
        set statusText "No log data found."
        return 
    }
    set fVar 1
    set numVar 0
    set numSec 0
    set beamString ""
    global matchBeamList
    set matchBeamList ""
    set tempRoot /tmp/[APSTmpString]
    foreach var $buttList {
        # beamline type: ID BM AM
        global $var
        if [set $var] {
            incr numVar
            foreach sec $secVarList {
                # sectors
                global $sec
                if [set $sec] {
                    incr numSec
                    set tempFile$fVar $tempRoot.${var}${sec}
                    lappend beamString ${var}${sec}
                    if {$fVar == 1} {
                        set matchBeamList "Instance=${var}${sec}"
                    } else {
                        append matchBeamList ",Instance=${var}${sec},|"
                    }     
                    incr fVar
                }
            }
        }
    }

    if {!$numVar || !$numSec} {
        set statusText "No beam line or sector selected"
        setOpenCloseResetBut 1
        setOpenCloseViewBut 1
        return
    }

    #returns a file of steering activity
    if [catch {ViewTime -file [set tempFile]} steeringActivity] {
        setOpenCloseResetBut 0
        set statusText "$steeringActivity"
        return
    }
    set printoutString "This printout includes [join $instanceList ,] between dates $intervalString."
    if [catch {MakeScrollList -file $steeringActivity \
             } result ] {
        set statusText "$result"
        return
    }
    setOpenCloseResetBut 1
    setOpenCloseViewBut 1
    set statusText "Done with the processing of the log files."
    update
    APSAddToTmpFileList -ID results -fileList $steeringActivity
}

proc DefineProcessList {} {
    global ordLogsList resDataDir dataDir statusText
    set ignore ${dataDir}/steeringAudit.log.00010.corrupted
    set dataList ""
    set i 1

    if [llength $ordLogsList] {
        foreach elem $ordLogsList {
            if [string match $elem $ignore] continue
            set tempFile.$i /tmp/[APSTmpString]
            if [string match $elem $resDataDir/steeringAudit.log] {
                if [catch {eval exec sddsprocess $elem -pipe=out \
                             -noWarnings \
                             -define=parameter,Rows,n_rows,type=long \
                             -process=Time,first,TimeFirst \
                             -define=parameter,TimeLast,1e300,units=s \
                             | sddsconvert -pipe \
                             -retain=parameter,Rows,TimeFirst,TimeLast \
                             | sddscollapse -pipe -noWarnings \
                             | sddsprocess -pipe=in [set tempFile.$i] \
                             -noWarnings \
                             -print=column,FileName,${elem} \
                         } result] {
                    set statusText "$result"
                } else {
                    lappend dataList [set tempFile.$i]
                    APSAddToTmpFileList -ID timeInfo -fileList [set tempFile.$i]
                    incr i
                }
            } else {
                if [catch {eval exec sddsprocess $elem -pipe=out \
                             -noWarnings \
                             -define=parameter,Rows,n_rows,type=long \
                             -process=Time,first,TimeFirst \
                             -process=Time,last,TimeLast \
                             | sddsconvert -pipe \
                             -retain=parameter,Rows,TimeFirst,TimeLast \
                             | sddscollapse -pipe -noWarnings \
                             | sddsprocess -pipe=in [set tempFile.$i] \
                             -noWarnings \
                             -print=column,FileName,${elem} \
                         } result] {
                         return -code error "DefineProcessList:$result"
                } else {
                    lappend dataList [set tempFile.$i]
                    APSAddToTmpFileList -ID timeInfo -fileList [set tempFile.$i]
                    incr i
                }
            }
        }
        return $dataList
    }
}

proc ViewTime {args} {
    global statusText instanceList actionType matchBeamList actionType
    set activityFile /tmp/[APSTmpString].steeringActivity
    set file ""
    APSParseArguments {file}
    if ![string length $file] {
        return -code error "ViewTime: No file supplied."
    }
    if ![file exists $file] {
        return -code error "ViewTime: Can't find file $file."
    }        
    if [llength $matchBeamList] {
        if [catch {exec sddsprocess $file -pipe=out -noWarnings \
                     -match=col,$matchBeamList \
                     -match=col,Action=$actionType \
                     -define=col,Spike,1,type=long \
                     | sddssort -pipe=in $activityFile \
                     -column=Instance,increasing \
                     -column=${actionType}Time,increasing \
                 } result] {
            return -code error "ViewTime: $result"
        }

        if [catch {exec sdds2stream $activityFile -columns=Instance \
                 } beamtempList] {
            return -code error "ViewTime: $beamtempList"
        }
        
        set controlList ""
        foreach name [list AM BM ID] {
            for {set i 1} {$i <= 40} {incr i} {
                lappend controlList ${name}${i}
            }
        }

        set tmpInstanceList ""
        foreach ent $beamtempList {
            if {[lsearch -exact $tmpInstanceList $ent] < 0} {
                lappend tmpInstanceList $ent
            }
        }
        set instanceList ""
        foreach elem $controlList {
            if {[lsearch -exact $tmpInstanceList $elem] >= 0} {
                lappend instanceList $elem
            }
        }
    }
    return -code ok $activityFile
}

proc MakeScrollList {args} {
    global actionType printoutString
    set file ""
    APSParseArguments {file}
    if ![string length $file] {
        return -code error "MakeScrollList: No file supplied."
    }
    if ![file exists $file] {
        return -code error "MakeScrollList: Can't find file $file."
    }        
    set printoutFile /tmp/[APSTmpString].print
    APSAddToTmpFileList -ID results -fileList $printoutFile

    exec sddsprintout $file $printoutFile -column=Instance \
      -column=${actionType}Time \
      -title=[APSMakeSafeQualifierString $printoutString]

    APSFileDisplayWindow .[APSUniqueName review] -packOption "-side bottom" \
      -fileName $printoutFile -sddsExportableFile $file -contextHelp \
      "Displays a list of beam lines with existing data in the selected time frame and a list of related steering start times."
    return
}

proc MakePlot {args} {
    global instanceList 
    set file ""
    APSParseArguments {file}
    if ![string length $file] {
        return -code error "MakePlot: No file supplied."
    }                           
    if ![file exists $file] {   
        return -code error "MakePlot: Can't find file $file."
    }        

    set plotFileList ""
    set plotFileCompl /tmp/[APSTmpString]
    setOpenCloseResetBut 0
    setOpenCloseViewBut 0
    if [llength $instanceList] {
        foreach beamline $instanceList {
            set plotFile /tmp/[APSTmpString].plot
            exec sddsprocess $file $plotFile -noWarnings \
              -match=col,Instance=$beamline \
              "-print=para,Beamline,Beamline $beamline"
            lappend plotFileList $plotFile
        }
        APSAddToTmpFileList -ID plot -fileList $plotFileList
        eval exec sddsplot $plotFileList -col=Time,Spike -uns=y -tick=xtime \
          -same=x -graph=impulse -separate -topline=@Beamline &
    }
    setOpenCloseResetBut 1
    setOpenCloseViewBut 1
    return
}

# makes frame for date/time selection widgets (for range
# of dates to process)

proc MakeDateTimeFrame {widget args} {
    set parent .

    APSStrictParseArguments {parent}

    set label "Date/Time Range of Interest"

    APSFrame $widget -parent $parent -label $label

    set w $parent$widget.frame

    APSDateTimeAdjEntry .startDate -parent $w \
      -yearVariable StartYear \
      -monthVariable StartMonth \
      -dayVariable StartDay \
      -hourVariable StartHour \
      -label "Starting date/time (year, month, day, hour): " \
      -defaultHour 0 \
      -command ResetMonDataFileList
    APSDateTimeAdjEntry .endDate -parent $w \
      -yearVariable EndYear \
      -monthVariable EndMonth \
      -dayVariable EndDay \
      -hourVariable EndHour \
      -label "Ending date/time (year, month, day, hour):   " \
      -defaultHour 24 \
      -command ResetMonDataFileList

    SetDateTimeToToday -rootname Start -hour 0
    SetDateTimeToToday -rootname End  -hour 24
}

proc SetDateTimeToToday {args} {
    set rootname ""
    set hour 0

    ResetMonDataFileList
    APSStrictParseArguments {rootname hour}

    global ${rootname}Month ${rootname}Year ${rootname}Day ${rootname}Hour
    
    APSDateBreakDown -dayVariable ${rootname}Day -yearVariable ${rootname}Year \
      -monthVariable ${rootname}Month -twoDigitYear 0 -leadingZeros 0
    set ${rootname}Hour $hour
}

proc ResetMonDataFileList {} {
    global DataFileList 

    set DataFileList " "
    update
}

proc setOpenCloseResetBut {state} {
    global f
    if $state {
        APSEnableButton $f.plot.button
    } else {
        APSDisableButton $f.plot.button
    } 
}

proc setOpenCloseViewBut {state} {
    global f
    if $state {
        APSEnableButton $f.butt.button
    } else {
        APSDisableButton $f.butt.button
    } 
}

proc cleanUpFiles {} {
    APSDeleteTempFiles -ID plot
    APSDeleteTempFiles -ID results
    APSDeleteTempFiles -ID timeInfo
}

MakeDateTimeFrame .timeFrame -parent .userFrame  

APSFrame .chckbut -parent .userFrame -width 80 -packOption "-side top" \
  -label "Beam Line:"
set w .userFrame.chckbut.frame

set ID 1
set buttList [list ID BM AM]

APSCheckButtonFrame .type -parent $w -label "Beam Line Type" \
  -orientation horizontal -buttonList $buttList -variableList $buttList \
  -packOption "-side top" -allNone 1 -contextHelp \
  "Selection of a type of a beam line from the Storage Ring." 

set sectorList ""
set secVarList ""
for {set i 1} {$i <= 40} {incr i} {
    if $i<10 {
        lappend sectorList " $i"
        lappend secVarList $i
    } else { 
        lappend sectorList $i
        lappend secVarList $i
    }
}

set 1 1
APSCheckButtonFrame .bframe -parent $w -label "Sector" \
  -buttonList $sectorList \
  -variableList $secVarList -allNone 1 \
  -orientation horizontal -limitPerRow 10 \
  -contextHelp "Selection of a sector from Storage Ring for the beam line of interest." 

APSFrame .butframe -parent .userFrame -packOption "-side top"

set f .userFrame.butframe.frame

set actionType Done
APSRadioButtonFrame .action -parent $f \
  -label "Action Type" -variable actionType \
  -orientation horizontal -buttonList {Start Exit Abort Done} \
  -valueList {Start Exit Abort Done} \
  -contextHelp "Allows specifying what type of action is desired for a viewing" \
  -packOption "-side left"


APSButton .butt -parent $f -text "View time" \
  -packOption "-side left" \
  -command InitViewTime -contextHelp \
  "Invokes data analysis from steeringAudit log files for the chosen beam lines in the selected time frame." 

APSButton .plot -parent $f -text "Plot" -packOption "-side left" \
  -command {MakePlot -file $steeringActivity} -contextHelp \
  "Makes a plot from the existing data for each chosen beam line separately."

setOpenCloseResetBut 0

dp_atexit append cleanUpFiles

