#!/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.4  2010/11/16 20:45:21  shang
# moved the ramp log files to faster server to speed up the review and added hour filter to be able to review files within hours.
#
# Revision 1.3  2010/11/10 22:22:00  shang
# added option of displaying the plots in a separate panels, and added total counts display for plotting together.
#
# Revision 1.2  2010/11/08 15:48:58  shang
# modified to display message that no comparison is done when there is only one file being found.
#
# Revision 1.1  2010/11/02 15:25:08  shang
# first version for reviewing booster ramp corrections.
#

set CVSRevisionAuthor "\$Revision: 1.5 $ \$Author: shang $"

APSApplication . -name BoosterRampCorrectionReview -version "\$Revision: 1.5 $ \$Author: shang $" \
  -overview {review booster ramp current for selected dates }

set status "Ready."

proc SetStatus {text} {
    global status
    set status $text
    update
}

set BM 0
set SF 0
set QF 0
set SD 0
set SF 0
set startHour 0
set endHour 24
set dataDir /home/helios/oagData/booster/rampLogFiles/IRamp/rampCorrectionLogFiles
set IRamp 1
proc UpdateDir {args} {
    global IRamp dataDir
    if $IRamp {
        set dataDir /home/helios/oagData/booster/rampLogFiles/IRamp/rampCorrectionLogFiles
    } else {
        set dataDir /home/helios/oagData/booster/rampLogFiles/VRamp/rampCorrectionLogFiles
    }
}
proc MakeDataRevieFrame {args} {
    set parent ""
    global rootname plotSector plotPlane logPlot BM SF SD QF QD separate IRamp
    
    APSStrictParseArguments {parent}
    global StartYear StartMonth StartDay  EndYear EndMonth EndDay StartHour EndHour
    
    APSFrame .review -parent $parent -label "Data Review"
    $parent.review configure -bd 2 -relief ridge
    
    APSDateTimeAdjEntry .startDate -parent $parent.review.frame \
      -yearVariable StartYear \
      -monthVariable StartMonth \
      -dayVariable StartDay \
      -hourVariable StartHour \
      -label "Starting date/time (year, month, day): " 
    APSDateTimeAdjEntry .endDate -parent $parent.review.frame \
          -yearVariable EndYear \
          -monthVariable EndMonth \
          -dayVariable EndDay  \
          -hourVariable EndHour \
          -label "Ending date/time (year, month, day):   " 
    APSCheckButtonFrame .check -parent $parent.review.frame -label "Magnet:" \
        -buttonList {BM SF SD QF QD} -allNone 1 -variableList {BM SF SD QF QD} \
        -orientation horizontal 
    APSRadioButtonFrame .sep -parent $parent.review.frame -label "Separate plots?" -buttonList {Yes No} -valueList {1 0} \
      -variable separate -orientation horizontal
    APSRadioButtonFrame .ramp -parent $parent.review.frame -label "IRamp or VRamp?" -buttonList {IRamp VRamp} -valueList {1 0} \
      -variable IRamp -orientation horizontal
    APSButton .display -parent $parent.review.frame -text "Review" \
      -command "ReviewData"
    set StartHour 0
    set EndHour 24
    update
   
}

proc FindFiles {args} {
    set startYear ""
    set startMonth ""
    set startDay ""
    set endYear ""
    set endMonth ""
    set endDay ""
    set rootname ""
    set suffix ""
    set startHour 0
    set endHour 24
    APSParseArguments {startYear startMonth startDay endYear endMonth endDay suffix rootname startHour endHour}
    
    set starttime [clock scan ${startMonth}/$startDay/$startYear]
    set endtime [clock scan $endMonth/$endDay/$endYear]
    set startjday [scan [clock format $starttime -format %j] %d]
    set endjday [scan [clock format $endtime -format %j] %d]
    set startyear [clock format $starttime -format %Y]
    set endyear [clock format $endtime -format %Y]
    
    set fileList ""
    
    for {set year $startyear} {$year<=$endyear} {incr year} {
        if {$year==$endyear} {
            for {set jday $startjday} {$jday<=$endjday} {incr jday} {
                set time [clock scan $year-[format %03d $jday] -format %Y-%j]
                set month [clock format $time -format %m]
                set day [clock format $time -format %d]
                set dir ${year}-${month}$day
                set files [glob -nocomplain $dir/${rootname}*.$suffix]
                if [llength $files] {
                    if {$jday==$startjday || $jday==$endjday} {
                        foreach file $files {
                            set file1 [file tail $file]
                            set time [lindex [split $file1 "-"] 1]
                            set hour [scan [string range $time 0 1] %ld]
                            set min [scan [string range $time 2 3] %ld]
                            set sec [scan [string range $time 4 5] %ld]
                            set hour [expr $hour + $min/60.0 + $sec/3600.0]
                            if {($startjday==$endjday && $hour>=$startHour && $hour<=$endHour) || \
                                  ($startjday!=$endjday && $jday==$startjday && $hour>=$startHour) || \
                                  ($startjday!=$endjday && $jday==$endjday && $hour<=$endHour)} {
                                set fileList [concat $fileList $file]
                            }
                        }
                    } else {
                        set fileList [concat $fileList $files]
                    }
                }
            }
        } elseif {$year<$endYear} {
            #only consider one year before since the data only keep 6 months old
            for {set jday $startjday} {$jday<=365} {incr jday} {
                set time [clock scan $year-[format %03d $jday] -format %y-%j]
                set month [clock format $time -format %m]
                set day [clock format $time -format %d]
                set dir ${year}-${month}${day}
                set files [glob -nocomplain $dir/${rootname}*.$suffix]
                if [llength $files] {
                    set fileList [concat $fileList $files]
                }
            }
        }
    }
    return [lsort $fileList]
}

proc ReviewData {args} {
    global StartYear StartMonth StartDay EndYear EndMonth EndDay BM SF SD QF QD separate StartHour EndHour dataDir
    
  #  set dataDir /home/helios/oagData/booster/ramps/rampLogFiles
  
    set oldDir [pwd]
    cd $dataDir
    set tmpRoot /tmp/[APSTmpString]
    
    if $separate {
        set option "-sep -same=y"
    } else  {
        set option ""
    }
    foreach magnet {BM SF SD QF QD} {
        if [set $magnet] {
            SetStatus "Searching files for $magnet..."
            set files [FindFiles -startYear $StartYear -startMonth $StartMonth -startDay $StartDay \
                         -endYear $EndYear -endMonth $EndMonth -endDay $EndDay -startHour $StartHour -endHour $EndHour \
                         -rootname ${magnet}new -suffix afg100 ]
            if ![llength $files] {
                SetStatus "No ramp files found for $magnet at selected dates."
            } elseif {[llength $files]==1} {
                SetStatus "Only one file found for $magnet, unable to do comparison."
            } else {
                if [catch {eval exec sddscombine $files -pipe=out \
                             |  sddschanges -changesIn=RampSetpoint \
                             -copy=RampTime,index -pipe=in $tmpRoot.$magnet.ramp } result] {
                    return -code error "ReviewData1: $result"
                }
                APSAddToTmpFileList -ID booramp -fileList $tmpRoot.$magnet.ramp
                if !$separate {
                    set option {"-title=total [llength $files] corrections."}
                }
               eval exec sddsplot $option -col=RampTime,ChangeInRampSetpoint \
                  -grap=li,vary $tmpRoot.$magnet.ramp -split=pages \
                  -filter=col,RampTime,15,250 \
                  -leg=para=TimeStamp \
                  -stagger=xIncrement=300 -topline=$magnet  &
            }
            set files [FindFiles -startYear $StartYear -startMonth $StartMonth -startDay $StartDay \
                         -endYear $EndYear -endMonth $EndMonth -endDay $EndDay -startHour $StartHour -endHour $EndHour \
                         -rootname ${magnet}current -suffix file ]
            if ![llength $files] {
                SetStatus "No current files found for $magnet at selected dates."
            } elseif {[llength $files]==1} {
                SetStatus "Only one current file found for $magnet, unable to do comparison."
            } else {
                if !$separate {
                    set option {"-title=total [llength $files] corrections."}
                }
                if [catch {eval exec sddscombine $files -pipe=out \
                             | sddsprocess -pipe \"-redefine=col,RampTime,index 0.09765625 *\" \
                             |  sddschanges -changesIn=B:${magnet}:CurrentWF \
                             -copy=RampTime,index -pipe=in $tmpRoot.$magnet.current } result] {
                    return -code error "ReviewData1: $result"
                }
                APSAddToTmpFileList -ID booramp -fileList $tmpRoot.$magnet.current
               eval  exec sddsplot  $option -col=RampTime,ChangeInB:${magnet}:CurrentWF \
                  -grap=li,vary $tmpRoot.$magnet.current -split=pages \
                  -filter=col,RampTime,25,255 \
                  -leg=para=TimeStamp \
                  -stagger=xIncrement=$magnet -topline=$magnet &
            }
            SetStatus "done."
        }

    }
    
    cd $oldDir
}

set separate 0
APSScrolledStatus .status -parent .userFrame -width 60 \
  -textVariable status
MakeDataRevieFrame -parent .userFrame
