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

#
# $Log: not supported by cvs2svn $
# Revision 1.6  2008/01/03 23:10:19  shang
# replaced "Select the PS pattern" by "Select beamline"
#
# Revision 1.5  2008/01/03 21:51:47  shang
# merged the measurement and compare frames into one frame, and removed the "do measurement" button.
#
# Revision 1.4  2007/12/21 17:24:16  shang
# made lots of changes to simplify the simple version and compute the reference resistance only when the
# "save reference time frame" button in the expert version is clicked.
#
# Revision 1.3  2007/12/11 19:52:03  shang
# added -expert argument, the expert version has two more buttons than the simple version:
# plot button for plotting the PS current, voltage and SR current and Save button for
# saving time reference.
#
# Revision 1.2  2007/11/08 15:18:00  shang
# now uses the absolute value of current and voltage for computing the resistance
#
# Revision 1.1  2007/11/07 22:52:58  shang
# first version for checking injector power supply resistance.
#
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.7 $ \$Author: soliday $"

proc SetStatus {text} {
    global Status
    set Status "[exec date +%H:%M:%S] $text"
    update
}

proc GetLogDataParameters {args} {
    foreach rootname {Linac LTP PTB PAR BTS} {
        global $rootname
        switch $rootname {
            BTS {
                set ${rootname}(dir) /home/helios/oagData/monitoring/BTSPS
                set ${rootname}(vcol) :DCVoltageAI
                set ${rootname}(ccol) :DCCurrentAI
                set ${rootname}(fileroot) BTSPS
                set ${rootname}(filter) *:DCVoltageAI
                set ${rootname}(monFile) /home/helios/oagData/monitoring/BTSPS/BTSPS.mon
                set ${rootname}(interval) 64
            }
            PAR -
            PTB -
            LTP {
                set ${rootname}(dir) /home/helios/oagData/logging/PLETDCPS
                set ${rootname}(vcol) :Voltage 
                set ${rootname}(ccol) :Readback
                set ${rootname}(fileroot) PLETDCPS
                set ${rootname}(monFile) /home/helios/oagData/logging/PLETDCPS/PLETDCPS.mon
                set ${rootname}(interval) 64
            }
            Linac {
                set ${rootname}(dir) /home/helios/oagData/logging/linacPS
                set ${rootname}(monFile) /home/helios/oagData/logging/linacPS/linacPS.mon
                set ${rootname}(fileroot) linacPS
                set ${rootname}(vcol) :MeasVoltage
                set ${rootname}(ccol) :MeasCurrent
                set ${rootname}(filter) *:MeasVoltage
                set ${rootname}(interval) 4
            }
        }
    }
    set PTB(filter) PTB:*:Voltage
    set LTP(filter) LTP:*:Voltage
    set PAR(filter) ""
}

proc LoadReferenceTime {args} {
    set refFile /home/helios/oagData/linac/psReference/psRef.sdds
    if [file exist $refFile] {
        set names [join [exec sdds2stream -col=Name $refFile]]
        set values [join [exec sdds2stream -col=Value $refFile]]
        eval global $names
        foreach name $names val $values {
            if [regexp {Hour} $name] {
                set $name [format %.2f $val]
            } else {
                set $name [format %.0f $val]
            }
        }
        foreach type {Start End} {
            set hour [expr int([set ${type}Hour])]
            set min [expr int(([set ${type}Hour]-$hour)*60)]
            set leftHour [expr [set ${type}Hour] - $hour - $min/60.0]
            set sec [expr int($leftHour*3600)]
            set ${type}Hour [format %02d $hour]:[format %02d $min]:[format %02d $sec]
        }
    }
}

proc SaveReferenceTime {args} {
    global StartYear StartMonth StartDay StartHour EndYear EndMonth EndDay EndHour archiveDir 
    
    set filename psRef.sdds-0000 
    set newFile [APSNextGenerationedName -name $filename -directory $archiveDir -newFile 1 -separator -]
   
    if [catch {exec sddsmakedataset $archiveDir/$newFile -col=Name,type=string \
                   -data=StartYear,StartMonth,StartDay,StartHour,EndYear,EndMonth,EndDay,EndHour \
                   -col=Value,type=double \
                   -data=$StartYear,$StartMonth,$StartDay,$StartHour,$EndYear,$EndMonth,$EndDay,$EndHour } result] {
        return -code error $result
    }
    set fileList ""
    foreach rootname {Linac LTP PTB PAR BTS} {
        global $rootname
        if [catch {ComputeAverageResistance -rootname1 $rootname} result] {
            return -code error $result
        }
        lappend fileList [set ${rootname}(reference)] 
    }
    set filename1 psResistanceRef.sdds-0000
    set newFile1 [APSNextGenerationedName -name $filename1 -directory $archiveDir -newFile 1 -separator -]
    if [catch {eval exec sddscombine $fileList $archiveDir/$newFile1} result] {
        return -code error $result
    } 
    set oldDir [pwd]
    cd $archiveDir
    catch {exec rm psRef.sdds}
    catch {exec ln -s $newFile psRef.sdds}
    catch {exec rm psResistanceRef.sdds}
    catch {exec ln -s $newFile1 psResistanceRef.sdds}
    cd $oldDir
    SetStatus "New reference time was saved."
}

proc ComputeLinacResistance {args} {
    set type ""
    set datafile ""
    APSParseArguments {type datafile}
    
    global Linac
    
    set rootname Linac
   
    set columns [exec sddsquery -col $datafile]
    set fileList ""
    foreach col $columns {
        if [regexp Resistance $col] {
            set root [regsub :Resistance $col ""]
            SetStatus "Processing average resistance of $root ..."
            if [catch {exec sddsconvert $datafile -pipe=out -retain=col,Time,$col \
                           | sddsconvert -pipe -rename=col,$col=Resistance \
                           | sddsoutlier -pipe -stDev=0.2 -col=Resistance \
                           | sddsprocess -pipe=in -process=Resistance,average,ResistanceAve \
                           "-print=par,Description,$root resistance\=%.3f \\\$gW\\\$r,ResistanceAve" \
                           -print=par,Rootname,$root $datafile.$root} result] {
                SetStatus $result 
                continue
            }
            lappend fileList $datafile.$root
        }
    }
    if ![llength $fileList] {
        return -code error "No vaild data found for $rootname PS." 
    }
    if [catch {eval exec sddscombine $fileList -pipe=out \
                   | tee $datafile.plot \
                   | sddscollapse -pipe \
                   | sddsconvert -pipe=in -retain=col,ResistanceAve,Rootname,Description $datafile.ave } result] {
        return -code error $result
    }
    set ${rootname}($type) $datafile.ave
    catch { exec sddsplot -yscale=namestring -mode=x=offset -tick=xtime "-col=Time,Resistance" -grap=line,vary \
                -split=page -legend -sep=page -topline=@Description $datafile.plot &}
    return
}

proc ComputeResistance {args} {
    set rootname ""
    set datafile ""  
    set type "" 
    APSParseArguments {rootname datafile type}
    
    global $rootname
    
    set filter [set ${rootname}(filter)]
    set vcol [set ${rootname}(vcol)]
    set ccol [set ${rootname}(ccol)]
    if {$rootname=="PAR"} {
        if [catch {exec sddsconvert $datafile -pipe=out -del=col,PTB:*,LTP:* \
                       | sddsconvert -pipe=in $datafile.1 -retain=col,*:Voltage} result] {
            return -code error $result
        }
    } else {
        if [catch {exec sddsconvert $datafile $datafile.1 -retain=col,$filter } result] {
            return -code error $result
        }
    }
    set columns [exec sddsquery -col $datafile.1]
    set allColumns [exec sddsquery -col $datafile]
    
    set fileList ""
    foreach col $columns {
        set root [regsub $vcol $col ""]
        set currentCol ""
        switch $rootname {
            BTS {
                set col1 [regsub "VoltageAI" $col "CurrentAI"] 
                if [lsearch -exact $allColumns $col1]>=0 { 
                    set currentCol $col1 
                } else {
                    set col1 [regsub "DCVoltageAI" $col "CurrentAI"] 
                    set col2 [regsub "VoltageAI" $col "CurrentAI"]
                    if [lsearch -exact $allColumns $col1]>=0 {
                        set currentCol $col1
                    }
                }
            }
            default {
                set col1 [regsub $vcol $col $ccol]
                if [lsearch -exact $allColumns $col1]>=0 {
                    set currentCol $col1
                }
            }
        }
        SetStatus "Compute resistance of $root ..."
        if [string length $currentCol] {
            if [catch {exec sddsconvert $datafile -pipe=out -retain=col,Time,$col,$currentCol \
                           | sddsconvert -pipe -rename=col,$col=Voltage,$currentCol=Current \
                           | sddsprocess -pipe "-redefine=col,Voltage,Voltage abs" "-redefine=col,Current,Current abs" \
                           | sddsoutlier -pipe -column=Current -minimumlimit=0.1  \
                           | sddsprocess -pipe "-define=col,Resistance,Voltage Current /,units=\\\$gW\\\$r" \
                           | sddsoutlier -pipe -stDev=2 -col=Resistance \
                           | sddsprocess -pipe=in "-process=Resistance,average,ResistanceAve" \
                           "-print=par,Description,$root resistance\=%.3f \\\$gW\\\$r,ResistanceAve" \
                           -print=par,Rootname,$root $datafile.$root} result] {
                SetStatus $result 
                continue
            }
            lappend fileList $datafile.$root
        } 
    }
    if ![llength $fileList] {
        return -code error "No vaild data found for $rootname PS." 
    }
    if [catch {eval exec sddscombine $fileList -pipe=out \
                   | tee $datafile.plot \
                   | sddscollapse -pipe \
                   | sddsprocess -pipe -print=par,Beamline,$rootname \
                   | sddsconvert -pipe=in -retain=col,ResistanceAve,Rootname,Description $datafile.ave } result] {
        return -code error $result
    }
    set ${rootname}($type) $datafile.ave
    catch { exec sddsplot -yscale=namestring \
                "-col=Time,(Resistance,Voltage,Current)" -grap=line,vary -split=page \
                -legend -sep=page -topline=@Description $datafile.plot &}
    return 
}

proc FindPVDataFiles {args} {
    set ReadbackName ""
    set StartTime [clock scan "Jan 01 00:00:00 1990"]
    set EndTime [clock seconds]
    set startDateList ""
    set endDateList ""
    set SampleIntervals "1 2 4 8 16 32 64 128 256"
    APSStrictParseArguments {ReadbackName StartTime EndTime SampleIntervals startDateList endDateList}

    if {[llength $startDateList]} {
        set StartTime [clock scan "[lindex $startDateList 2]/[lindex $startDateList 3]/[lindex $startDateList 0]"]
    }
    if {[llength $endDateList]} {
        set EndTime [clock scan "23:59:59 [lindex $endDateList 2]/[lindex $endDateList 3]/[lindex $endDateList 0]"]
    }
    
    set fileList ""
    set ReadbackName [join [split $ReadbackName / ] + ]
    set year [clock format $StartTime -format %Y]
    set month [clock format $StartTime -format %m]
    set endyear [clock format $EndTime -format %Y]
    set endmonth [clock format $EndTime -format %m]
    while {($year < $endyear) || (($year == $endyear) && ($month <= $endmonth))} {
        append fileList "[lsort [glob -nocomplain /home/helios/oagData/logging/Variable/[string index ${ReadbackName} 0]/${ReadbackName}/log-${year}-${month}.{gz,xz}]] "
        append fileList "[lsort [glob -nocomplain /home/helios/oagData/logging/\{[join $SampleIntervals ,]\}/${ReadbackName}/log-${year}-${month}.{gz,xz,????}]] "
        if {$month == 12} {
            set month 01
            incr year
        } else {
            scan $month %d month
            incr month
            set month [format %02d $month]
        }
    }
    return $fileList
}

proc ComputeAverageResistance {args} {
    set plot 0
    set rootname1 ""
    APSParseArguments {plot rootname1}
    
    global rootname
    if [string length $rootname1] {
       set rootname $rootname1
    }
    global StartYear StartMonth StartDay StartHour
    global EndYear EndMonth EndDay EndHour $rootname
    global $rootname ${rootname}RefComputed expert
    
    if !$plot {
        SetStatus "Computing average resistance for $rootname PS..."
    }
    set fileroot [set ${rootname}(fileroot)]
    set vcol [set ${rootname}(vcol)]
    set ccol [set ${rootname}(ccol)]
    set dir [set ${rootname}(dir)]
    
    set oldDir [pwd]
    #cd $dir
    set tmpfile /tmp/[APSTmpString].$rootname
    foreach type {Start End} {
        set tmpList [split [set ${type}Hour] :]
        set hour [lindex $tmpList 0]
        set min 0
        set sec 0
        if [llength $tmpList]>1 {
            set min [lindex $tmpList 1]
        }
        if [llength $tmpList]>2 {
            set sec [lindex $tmpList 2]
        }
        set ${type}Time0 [expr $hour*3600+$min*60+$sec]
    }
    set startTime [expr [clock scan [set StartMonth]/[set StartDay]/[set StartYear]] + $StartTime0]
    set endTime [expr [clock scan [set EndMonth]/[set EndDay]/[set EndYear]] + $EndTime0]
    set filter [set ${rootname}(filter)]
    set vcol [set ${rootname}(vcol)]
    set ccol [set ${rootname}(ccol)]

    if {$rootname=="PAR"} {
        set input [file join $dir $fileroot].mon
        if {[catch {exec sddsprocess $input -pipe=out "-match=col,ReadbackName=*:Voltage,ReadbackName=PTB:*,!,&,ReadbackName=LTP:*,!,&" | sdds2stream -pipe -col=ReadbackName} columns]} {
            return -code error $columns
        }
    } else {
        set input [file join $dir $fileroot].mon
        if {[catch {exec sddsprocess $input -pipe=out "-match=col,ReadbackName=$filter" | sdds2stream -pipe -col=ReadbackName} columns]} {
            return -code error $columns
        }
    }
    if {[catch {exec sdds2stream $input -col=ReadbackName} allColumns]} {
        return -code error $allColumns
    }
    set colList ""
    foreach col $columns {
        set root [regsub $vcol $col ""]
        set currentCol ""
        switch $rootname {
            BTS {
                set col1 [regsub "VoltageAI" $col "CurrentAI"] 
                if [lsearch -exact $allColumns $col1]>=0 { 
                    set currentCol $col1 
                } else {
                    set col1 [regsub "DCVoltageAI" $col "CurrentAI"] 
                    set col2 [regsub "VoltageAI" $col "CurrentAI"]
                    if [lsearch -exact $allColumns $col1]>=0 {
                        set currentCol $col1
                    }
                }
            }
            default {
                set col1 [regsub $vcol $col $ccol]
                if [lsearch -exact $allColumns $col1]>=0 {
                    set currentCol $col1
                }
            }
        }
        if [string length $currentCol] {
            lappend colList $currentCol
            lappend colList $col
        }
    }
    foreach col $colList {
        append pvFiles "[FindPVDataFiles -ReadbackName $col -SampleIntervals [set ${rootname}(interval)] \
                       -startDateList [APSFormatDate -year [set StartYear] -month [set StartMonth] \
                                          -day [set StartDay] -dateFormat list] \
                       -endDateList [APSFormatDate -year [set EndYear] -month [set EndMonth] \
                                        -day [set EndDay] -dateFormat list]] "
    }
    if ![llength $pvFiles] {
        SetStatus "No data found in given time range."
        return
    }
    if {$rootname == "Linac"} {
        foreach f $pvFiles {
            set prefix [string range [file tail [file dirname $f]] 0 1]
            lappend linacPVFiles($prefix) $f
        }
    }

    if $plot {
        #plot SR current
        set fileList [FindPVDataFiles -ReadbackName S35DCCT -SampleIntervals 8 \
                        -startDateList [APSFormatDate -year [set StartYear] -month [set StartMonth] \
                                          -day [set StartDay] -dateFormat list] \
                        -endDateList [APSFormatDate -year [set EndYear] -month [set EndMonth] \
                                        -day [set EndDay] -dateFormat list]]
        if ![llength $fileList] {
            return -code error "No charge data found!"
        }
        #Split the Linac plots up because they take so long to display
        if {$rootname == "Linac"} {
            SetStatus "Plotting Linac data may take 60 seconds."
            foreach prefix [lsort [array names linacPVFiles]] {
                eval exec sddsplot -yscale=namestring -grap=line,vary -sep=2 -leg -tick=xtime -filter=column,Time,$startTime,$endTime \
                  -group=namestring -col=Time,*$vcol -col=Time,*$ccol $linacPVFiles($prefix)  &
            }
            eval exec sddsplot -col=Time,S35DCCT -tick=xtime -mode=x=offset -filter=column,Time,$startTime,$endTime $fileList &
        } else {
            eval exec sddsplot -yscale=namestring -grap=line,vary -sep=2 -leg -tick=xtime -filter=column,Time,$startTime,$endTime \
              -group=namestring -col=Time,*$vcol -col=Time,*$ccol $pvFiles 2> /dev/null &
            eval exec sddsplot -col=Time,S35DCCT -tick=xtime -mode=x=offset -filter=column,Time,$startTime,$endTime $fileList &
        }
        return
    }
    
    if {[catch {eval exec sddscombinelogfiles $pvFiles -pipe=out | \
                  sddsprocess -pipe=input $tmpfile -filter=col,Time,$startTime,$endTime} result]} {
        return -code error $result
    }
    if [catch {ComputeResistance -datafile $tmpfile -rootname $rootname -type reference} result] {
        return -code error $result
    }
    
    SetStatus "$rootname PS resistance average was successfully computed." 
}

proc DoMeasurement {args} {
    global rootname samples interval
    global $rootname

    SetStatus "Taking Data for $rootname PS ...."
   
    set tmpRoot /tmp/[APSTmpString].$rootname
    if [catch {exec sddslogger [set ${rootname}(monFile)] $tmpRoot -steps=$samples -sampleInterval=$interval } result] {
        return -code error $result
    }
    SetStatus "Computing $rootname PS resistance ..."
    if [catch {ComputeResistance -datafile $tmpRoot -rootname $rootname -type data} result] {
        return -code error $result
    }
    SetStatus "Done."
  #  if [info exist ${rootname}(reference)] {
  #      CompareAndDisplay -rootname $rootname
  #  }
   # eval Do${rootname}Measurement
}

set monFile 0
proc MeasureLinacResistance {args} {
    global Linac monFile samples interval
    
    set rootname Linac
    if !$monFile {
        set tmpfile /tmp/[APSTmpString].Linac.mon
        if [catch {exec sddsprocess $Linac(monFile) $tmpfile -match=col,ReadbackName=*Resistance } result] {
            return -code error $result
        }
        set Linac(monFile) $tmpfile
        set monFile 1
    }
    set tmpRoot /tmp/[APSTmpString].Linac
    if [catch {exec sddslogger [set ${rootname}(monFile)] $tmpRoot -steps=$samples -sampleInterval=$interval } result] {
        return -code error $result
    }
    if [catch {ComputeLinacResistance -datafile $tmpRoot -type data} result] {
        return -code error $result
    }
}

proc CompareAndDisplay {args} {
    global rootname error
    global $rootname
    SetStatus "Checking $rootname PS resistance ..."
    if ![info exist ${rootname}(reference)] {
        set tmpRoot /tmp/[APSTmpString].$rootname
        if [catch {exec sddsprocess /home/helios/oagData/linac/psReference/psResistanceRef.sdds \
                       -match=par,Beamline=$rootname $tmpRoot} result] {
            return -code error $result
        }
        set ${rootname}(reference) $tmpRoot
    }
    set doMeas 0
    if ![info exist ${rootname}(data)] {
        set doMeas 1
    } else {
        set doMeas [APSYesNoPopUp "The $rootname resistance has been measured, would you like to measure it again?"]
    }
    if $doMeas {
        if [catch {DoMeasurement -rootname $rootname} result] {
            return -code error $result
        }
    }
    set tmpRoot /tmp/[APSTmpString].$rootname.compare
    if [catch {exec sddsselect [set ${rootname}(data)] [set ${rootname}(reference)] -match=Rootname $tmpRoot.1
        exec sddsxref $tmpRoot.1 [set ${rootname}(reference)] -edit=col,ResistanceAve,ei/Ref/ \
                   -pipe=out  -match=Rootname -nowarnings \
                   | sddsprocess -pipe "-define=col,RelativeDiff,ResistanceAve ResistanceAveRef - abs ResistanceAveRef / 100 *" \
                   | sddsprocess -pipe  "-define=col,Flag,RelativeDiff $error > ? 1 : 0 $ ,type=short" \
                   | sddsprintout -pipe=in $tmpRoot.printout "-title=$rootname power supply resistance check (acceptable difference =+-$error%)" \
                   -col=Rootname,label=PowerSupply -col=ResistanceAve,label=Current_Resistance,format=%10.3f \
                   -col=ResistanceAveRef,label=Reference_resistance,format=%10.3f -col=Flag,label=Out_Of_Range } result] {
        return -code error $result
    }
    APSAddToTmpFileList -ID resiscalc -fileList "$tmpRoot.1  $tmpRoot.printout"
    set displayW  [APSUniqueName .diff] 
    APSFileDisplayWindow $displayW  -fileName $tmpRoot.printout -width 80 -height 50 -printCommand "enscript -r"
    APSWaitWithUpdate -waitSeconds 1
    set data [${displayW}.userFrame.file.text get 1.0 end]
    set indexList ""
    set n 1
    foreach line [split $data \n] {
        if {[lindex $line end] == 1} {
            append indexList "$n.0 [expr {$n + 1}].0 "
        }
        incr n
    }
    if {[llength $indexList]} {
        eval ${displayW}.userFrame.file.text tag add tag1 $indexList
    }
    ${displayW}.userFrame.file.text tag configure tag1 -foreground red -background black
    SetStatus "done."
}

proc ResetDataFileList {} {
    

}

proc SetDateTimeToToday {args} {
    set rootname ""
    set hour 0  
  
    APSStrictParseArguments {rootname hour }
  
    global ${rootname}Year ${rootname}Month ${rootname}Day ${rootname}Hour
    set result [clock format [clock seconds] -format %d:%m:%Y:%H:%M:%S]
    set dateList [split $result :]
    set ${rootname}Day [scan [lindex $dateList 0] %ld]
    set ${rootname}Month [scan [lindex $dateList 1] %ld]
    set ${rootname}Year [lindex $dateList 2]
    set ${rootname}Hour $hour
}

proc SetDateTimeToYesterday {args} {
    set rootname ""
    set hour 0
    APSStrictParseArguments {rootname hour}
    set result [clock format [expr [clock seconds]-3600*24] -format %d:%m:%Y:%H:%M:%S]
    set dateList [split $result :]
    global ${rootname}Hour ${rootname}Year ${rootname}Month ${rootname}Day
    set ${rootname}Day [scan [lindex $dateList 0] %ld]
    set ${rootname}Month [scan [lindex $dateList 1] %ld]
    set ${rootname}Year [lindex $dateList 2]
    set ${rootname}Hour $hour
}



proc MakeOptionFrame {args} {
    set parent ""
    APSParseArguments {parent}
    
    global rootname expert
    APSRadioButtonFrame .radio -parent $parent -label "Select beamline:" -buttonList {Linac LTP PTB PAR BTS} \
        -variable rootname -valueList {Linac LTP PTB PAR BTS} -orientation horizontal \
        -contextHelp "select the beamlines for checking the resistance of the power supplies in selected beamline."
    
    global samples interval error 
    set samples 30
    set  interval 1
    APSFrame .ref -parent $parent -label "Reference Time Frame"
    if $expert {
        #make time frame
        set w $parent.ref.frame
        APSDateTimeAdjEntry .startDate -parent $w \
            -yearVariable StartYear \
            -monthVariable StartMonth \
            -dayVariable StartDay \
            -hourVariable StartHour \
            -label "Starting date/time (year, month, day, hour): " -defaultHour 0 \
            -command ResetDataFileList
        APSDateTimeAdjEntry .endDate -parent $w \
            -yearVariable EndYear \
            -monthVariable EndMonth \
            -dayVariable EndDay \
            -hourVariable EndHour \
            -label "Ending date/time (year, month, day, hour):   " -defaultHour 24 \
            -command ResetDataFileList
        LoadReferenceTime
        
        APSButton .plot -parent $w -text "Plot Voltage and Current" -command "ComputeAverageResistance -plot 1" \
           -contextHelp "for plotting the voltage and current of the power supplies in the selected beamline and also the storage ring \
             beam current in interested time range (from start time to end time)."
        #APSButton .compute -parent $w -text "Compute Average Resistance" -command "ComputeAverageResistance"
        APSButton .save -parent $w -text "Save Reference Time Frame" -command "SaveReferenceTime" \
          -contextHelp  "this button saves the selected time range (start time and end time) and compute the reference resistance of \
             the power supplies in all beamlines in selected reference time range and save the results as reference."
    } else {
        APSLabeledEntryFrame .start -parent $parent.ref.frame -label "Start Time (Year/Month/Day/Hour):" \
            -variableList {StartYear StartMonth StartDay StartHour} -orientation horizontal -width 10 \
            -contextHelp "display the start time of reference time frame."
        APSLabeledEntryFrame .end -parent $parent.ref.frame -label "End Time (Year/Month/Day/Hour):  " \
            -variableList {EndYear EndMonth EndDay EndHour} -orientation horizontal -width 10 \
            -contextHelp "display the end time of reference time frame."
        foreach nm {entry1 entry2 entry3 entry4} {
            #APSDisableWidget $parent.ref.frame.start.frame.$nm
            #APSDisableWidget $parent.ref.frame.end.frame.$nm
            $parent.ref.frame.start.frame.$nm configure -state readonly
            $parent.ref.frame.end.frame.$nm configure -state readonly
        }
        APSButton .load -parent $parent.ref.frame -text "Update Reference Time" -command "LoadReferenceTime" \
            -contextHelp "update the reference time in case new reference is saved."
    }
    APSFrame .current -parent $parent -label "Measure, Compare and Display" \
       -contextHelp "measure the resistance of the power supplies in selected beamline."
    set w $parent.current.frame
    APSLabeledEntryFrame .mon -parent $w -label "Measurement samples and interval (seconds):" \
        -width 10 -variableList [list samples interval] -orientation horizontal  \
        -contextHelp "input the number of samples of data monitoring and interval time between two samples."
  
    set error 15
    APSLabeledEntry .flag -parent $parent.current.frame -label "Percentage of allowable difference (+-)%" -width 21 \
        -textVariable error -contextHelp "input the percentage of allowable difference of the measured resistance from the reference"
    APSButton .compare -parent $parent.current.frame -text "Compare And Display" \
        -command "CompareAndDisplay" -contextHelp "This buttons compares the measured resistance with reference and display the result for selected beamline, out of range supplies will be red colored."
}
set archiveDir  /home/helios/oagData/linac/psReference
LoadReferenceTime
set args $argv
set expert 0
APSParseArguments {expert}
APSApplication . -name PowerSupplyResistanceCalculation -version $CVSRevisionAuthor -overview \
    "Power supply resistance check."
set Status ""
APSScrolledStatus .status -parent .userFrame -textVariable Status -width 60 -packOption "-fill x"

set rootname BTS
MakeOptionFrame -parent .userFrame
GetLogDataParameters
