#!/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.6  2008/09/24 16:17:22  soliday
# Updated to use the new data logger format.
#
# Revision 1.5  2000/02/21 21:53:16  borland
# Added an upper limit of 500kW on rf power to eliminate problems with
# Infinity values in data logger files.
#
# Revision 1.4  1998/06/29 23:10:32  borland
# Added CVS header.
#
#

set CVSRevisionAuthor "\$Revision: 1.7 $ \$Author: soliday $"

APSApplication . -name SRrfPowerTimeReview -version $CVSRevisionAuthor \
   -overview "Provides a number of hours during which power has been seen by a selected \
    cavity in the storage ring."

set statusText "Ready..."

APSScrolledStatus .status -parent .userFrame -textVariable statusText -width 69 \
   -contextHelp "Displays number of days of interest and number of hours during \
   which power has been seen by a selected cavity in the storage ring." 

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

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

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

    ResetMonDataFileList
    APSStrictParseArguments {rootname hour}

    global ${rootname}Month ${rootname}Year ${rootname}Day ${rootname}Hour
    
    set dateList [APSOffsetDateInfo -offset -1 -today 1 -dateFormat list \
                    -leadingZeros 0]
    set ${rootname}Day [lindex $dateList 3]
    set ${rootname}Year [lindex $dateList 0]
    set ${rootname}Month [lindex $dateList 2]

    set ${rootname}Hour $hour
}

# finds the files between the chosen dates

proc MonDataFindFiles {} {
    global DataFileList Rootname DataDir statusText
    global StartMonth StartYear StartDay StartHour
    global EndMonth EndYear EndDay EndHour cavList
    foreach cav $cavList {
        append pvFiles "[APSFindPVDataFiles -ReadbackName ${cav}ForwardPower \
                         -startDateList [APSFormatDate -year $StartYear \
                                         -month $StartMonth \
                                         -day $StartDay \
                                         -dateFormat list] \
                         -endDateList [APSFormatDate -year $EndYear \
                                         -month $EndMonth \
                                          -day $EndDay \
                                         -dateFormat list]] "
    }
    if {![llength $pvFiles]} {
        set DataFileList ""
        set statusText "0 files found for time range."
        return
    }
    set DataFileList /tmp/[APSTmpString]
    APSAddToTempFileList $DataFileList
    set statusText "[llength $pvFiles] file found. Working..."
    if {[catch {eval exec sddscombinelogfiles $pvFiles $DataFileList} result]} {
        APSSetVarAndUpdate status $result
    }
    update
}

proc ResetMonDataFileList {} {
    global DataFileList 

    set DataFileList " "
    update
}

proc Process {} {
    global Rootname DataDir
    setActionButtons 0
    update
    set Rootname SRrf
    set DataDir /home/helios/oagData/monitoring/SRrfg

    DayCorrection
    setActionButtons 1
    update
}

#DayCorrection is finding discrepancy in the input dates 

proc DayCorrection {} {
    global StartMonth StartYear StartDay StartHour StartTime
    global EndMonth EndYear EndDay EndHour EndTime
    global statusText intervalString
    set intervalString "$StartMonth/$StartDay/$StartYear@$StartHour and $EndMonth/$EndDay/$EndYear@$EndHour"

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

    if [catch {eval exec timeconvert -breakDown=year=$StartYear,month=$StartMonth,day=$StartDay,hour=$hour0} StartTime] {
        set statusText "Error: $StartTime"
    }
    if [catch {eval exec timeconvert -breakDown=year=$EndYear,month=$EndMonth,day=$EndDay,hour=$hour1} EndTime] {
        set statusText "Error: $EndTime"
    }

    if {$StartYear > $EndYear} {
        set statusText {Starting year must be <= ending year.}
        return
    } elseif {$StartYear == $EndYear} {
        if {$StartMonth > $EndMonth} {
            set statusText {Starting month must be <= ending month.}
            return
        } elseif {$StartMonth == $EndMonth} {
            if {$StartDay > $EndDay} {
                set statusText {Starting day must be <= ending day.}
                return
            } else {
                MonDataFindFiles
                CallTime
            }   
        } else { 
            MonDataFindFiles
            CallTime
        }
    } else {
        MonDataFindFiles
        CallTime
    }
}

proc CallTime {} {
    global Rootname DataDir lowerLim DataFileList intervalString statusText
    global StartTime EndTime cavList
    set finalList " "
    set highLim 1e300
    set combFile1 /tmp/[APSTmpString]
    set combFile2 /tmp/[APSTmpString]
    set combFile3 /tmp/[APSTmpString]
    set combFile /tmp/[APSTmpString]
    set exportFile /tmp/[APSTmpString]
    APSAddToTempFileList $combFile1 $combFile2 $combFile3 $combFile \
      $exportFile

    set finalList $DataFileList
    if [llength $finalList] {
        set printoutString "This printout includes power time in hours and its fraction in the specified period for all cavities from Storage Ring between dates $intervalString."
    } else {
       return
    }

    set optionList1 ""
    foreach cav $cavList {
        lappend optionList1 \
          "-process=Time,count,${cav}Points,functionOf=${cav}ForwardPower,lowerLimit=$lowerLim,upperLimit=500"
        lappend optionList1 \
          "-define=parameter,rfcav$cav,TimeSpread ${cav}Points * TotalSamples / factor *,units=h"
        lappend optionList1 \
          "-define=parameter,${cav}Fraction,${cav}Points TotalSamples /"
    }

    if [catch \
          {eval exec sddsprocess $finalList -pipe=out -noWarnings \
             -redefine=column,S37C1ForwardPower,S37C1ForwardPower,type=float \
             -redefine=column,S37C2ForwardPower,S37C2ForwardPower,type=float \
             -redefine=column,S37C3ForwardPower,S37C3ForwardPower,type=float \
             -redefine=column,S37C4ForwardPower,S37C4ForwardPower,type=float \
             -filter=column,Time,${StartTime},${EndTime} \
             {"-process=Time,count,TotalSamples"} \
             {"-process=Time,spread,TimeSpread"} \
             {"-define=parameter,factor,[expr 1./3600.]"}  \
             $optionList1 \
             | sddscollapse -pipe -noWarnings \
             | sddsconvert -pipe -retain=col,rfcavS??C?,S??C?Fraction \
             | sddscollect -pipe \
             -collect=prefix=rfcav,column=Time -collect=suffix=Fraction \
             | tee $exportFile \
             | sddsprintout -pipe=in $combFile3 \
             -columns=Rootname,label=Cavity \
             {"-columns=(Time,Fraction),format=%10.3f"} \
             {"-title=[APSMakeSafeQualifierString $printoutString]"}} result] {
        set statusText "Error: $result"
    } else {
        APSFileDisplayWindow .[APSUniqueName review] -packOption "-side bottom" \
          -fileName $combFile3 -sddsExportableFile $exportFile -height 30 -contextHelp \
          "Displays power time in the selected time frame for all cavities in Storage Ring."
    }
}

proc setActionButtons {state} {
    if $state {
        APSEnableButton .userFrame.process.button
    } else {
        APSDisableButton .userFrame.process.button
    }
}

set cavList [list S36C1 S36C2 S36C3 S36C4 S37C1 S37C2 S37C3 S37C4 \
               S38C1 S38C2 S38C3 S38C4 S40C1 S40C2 S40C3 S40C4]

MakeDateTimeFrame .timeFrame -parent .userFrame

set lowerLim 5
APSLabeledEntry .limit -parent .userFrame -label "Enter lower limit for the power (kW): " \
   -textVariable lowerLim -width 20 -contextHelp "Enter a value (in kW) for the minimum power to consider as significant." 

APSButton .process -parent .userFrame -text Process -command {Process} \
   -contextHelp "Invokes a setup of files of interest for selected dates\
   and calculates an amount of power time for the selected cavity" 
