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

proc MakeDateTimeFrame {frame} {
    global StartTextDay StartDay StartTextMonth StartYear 
    global StartHour StartMinute StartSecond StartTime
    global EndTextDay EndDay EndTextMonth EndYear 
    global EndHour EndMinute EndSecond EndTime

    set s [clock seconds]

    frame $frame
    pack $frame

    frame $frame.from
    pack $frame.from
    set f $frame.from

    label $f.label -text "From:"
    spinbox $f.textday -values "Mon Tue Wed Thu Fri Sat Sun" \
      -width 3 -wrap true -textvariable StartTextDay \
      -command {TimeAdjusted Start %W %s %d} -bg white
    spinbox $f.day -from 1 -to 31 -width 2 -wrap true \
      -textvariable StartDay \
      -validate key -vcmd {string is integer %P} \
      -command {TimeAdjusted Start %W %s %d} -bg white
    spinbox $f.month \
      -values "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec" \
      -width 3 -wrap true -textvariable StartTextMonth \
      -command {TimeAdjusted Start %W %s %d} -bg white
    spinbox $f.year -from 1900 -to 2100 -width 4 -wrap true \
      -textvariable StartYear \
      -validate key -vcmd {string is integer %P} \
      -command {TimeAdjusted Start %W %s %d} -bg white
    label $f.space -text " "
    spinbox $f.hour -from 0 -to 23 -width 2 -wrap true \
      -format %02.0f -textvariable StartHour \
      -validate key -vcmd {string is integer %P} \
      -command {TimeAdjusted Start %W %s %d} -bg white -bg white
    label $f.colon1 -text ":" -padx 0 -bd 0
    spinbox $f.minute -from 0 -to 59 -width 2 -wrap true \
      -format %02.0f -textvariable StartMinute \
      -validate key -vcmd {string is integer %P} \
      -command {TimeAdjusted Start %W %s %d} -bg white -bg white
    label $f.colon2 -text ":" -padx 0 -bd 0
    spinbox $f.second -from 0 -to 59 -width 2 -wrap true \
      -format %02.0f -textvariable StartSecond \
      -validate key -vcmd {string is integer %P} \
      -command {TimeAdjusted Start %W %s %d} -bg white -bg white

    bind $f.textday <Return> "TimeAdjustedManually"
    bind $f.day <Return> "TimeAdjustedManually"
    bind $f.month <Return> "TimeAdjustedManually"
    bind $f.year <Return> "TimeAdjustedManually"
    bind $f.hour <Return> "TimeAdjustedManually"
    bind $f.minute <Return> "TimeAdjustedManually"
    bind $f.second <Return> "TimeAdjustedManually"

    set StartTextDay [clock format $s -format %a]
    set StartDay [clock format $s -format %d]
    set StartTextMonth [clock format $s -format %b]
    set StartYear [clock format $s -format %Y]
    set StartHour 00
    set StartMinute 00
    set StartSecond 00

    set StartTime [clock scan "$StartTextDay $StartTextMonth $StartDay ${StartHour}:${StartMinute}:${StartSecond} $StartYear"]

    button $f.reset -text "Reset" -pady 0 -command "set StartTextDay $StartTextDay ; set StartDay $StartDay ; set StartTextMonth $StartTextMonth ; set StartYear $StartYear ; set StartHour $StartHour ; set StartMinute $StartMinute ; set StartSecond $StartSecond ; set StartTime $StartTime"

    pack $f.label $f.textday $f.day $f.month \
      $f.year $f.space $f.hour $f.colon1 \
      $f.minute $f.colon2 $f.second $f.reset -side left

    button $f.15min -text "last 15min" -pady 0 -command "TimePreset -minutes 15"
    pack $f.15min -side left
    button $f.30min -text "last 30min" -pady 0 -command "TimePreset -minutes 30"
    pack $f.30min -side left


    frame $frame.to
    pack $frame.to
    set f $frame.to

    label $f.label -text "  To:"
    spinbox $f.textday -values "Mon Tue Wed Thu Fri Sat Sun" \
      -width 3 -wrap true -textvariable EndTextDay \
      -command {TimeAdjusted End %W %s %d} -bg white
    spinbox $f.day -from 1 -to 31 -width 2 -wrap true \
      -textvariable EndDay \
      -validate key -vcmd {string is integer %P} \
      -command {TimeAdjusted End %W %s %d} -bg white
    spinbox $f.month \
      -values "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec" \
      -width 3 -wrap true -textvariable EndTextMonth \
      -command {TimeAdjusted End %W %s %d} -bg white
    spinbox $f.year -from 1900 -to 2100 -width 4 -wrap true \
      -textvariable EndYear \
      -validate key -vcmd {string is integer %P} \
      -command {TimeAdjusted End %W %s %d} -bg white
    label $f.space -text " "
    spinbox $f.hour -from 0 -to 23 -width 2 -wrap true \
      -format %02.0f -textvariable EndHour \
      -validate key -vcmd {string is integer %P} \
      -command {TimeAdjusted End %W %s %d} -bg white -bg white
    label $f.colon1 -text ":" -padx 0 -bd 0
    spinbox $f.minute -from 0 -to 59 -width 2 -wrap true \
      -format %02.0f -textvariable EndMinute \
      -validate key -vcmd {string is integer %P} \
      -command {TimeAdjusted End %W %s %d} -bg white -bg white
    label $f.colon2 -text ":" -padx 0 -bd 0
    spinbox $f.second -from 0 -to 59 -width 2 -wrap true \
      -format %02.0f -textvariable EndSecond \
      -validate key -vcmd {string is integer %P} \
      -command {TimeAdjusted End %W %s %d} -bg white -bg white

    bind $f.textday <Return> "TimeAdjustedManually"
    bind $f.day <Return> "TimeAdjustedManually"
    bind $f.month <Return> "TimeAdjustedManually"
    bind $f.year <Return> "TimeAdjustedManually"
    bind $f.hour <Return> "TimeAdjustedManually"
    bind $f.minute <Return> "TimeAdjustedManually"
    bind $f.second <Return> "TimeAdjustedManually"

    set EndTextDay [clock format $s -format %a]
    set EndDay [clock format $s -format %d]
    set EndTextMonth [clock format $s -format %b]
    set EndYear [clock format $s -format %Y]
    set EndHour 23
    set EndMinute 59
    set EndSecond 59

    set EndTime [clock scan "$EndTextDay $EndTextMonth $EndDay ${EndHour}:${EndMinute}:${EndSecond} $EndYear"]

    button $f.reset -text "Reset" -pady 0 -command "set EndTextDay $EndTextDay ; set EndDay $EndDay ; set EndTextMonth $EndTextMonth ; set EndYear $EndYear ; set EndHour $EndHour ; set EndMinute $EndMinute ; set EndSecond $EndSecond ; set EndTime $EndTime"

    pack $f.label $f.textday $f.day $f.month \
      $f.year $f.space $f.hour $f.colon1 \
      $f.minute $f.colon2 $f.second $f.reset -side left

    button $f.45min -text "last 45min" -pady 0 -command "TimePreset -minutes 45"
    pack $f.45min -side left
    button $f.60min -text "last 60min" -pady 0 -command "TimePreset -minutes 60"
    pack $f.60min -side left

}

proc TimePreset {args} {
    APSStrictParseArguments {minutes}
    foreach var "Start End" {
        global ${var}TextDay ${var}Day ${var}TextMonth ${var}Year 
        global ${var}Hour ${var}Minute ${var}Second ${var}Time
    }
    set s [clock seconds]
    
    set EndTextDay [clock format $s -format %a]
    set EndDay [clock format $s -format %d]
    set EndTextMonth [clock format $s -format %b]
    set EndYear [clock format $s -format %Y]
    set EndHour 23
    set EndMinute 59
    set EndSecond 59
    set EndTime [clock scan "$EndTextDay $EndTextMonth $EndDay ${EndHour}:${EndMinute}:${EndSecond} $EndYear"]

    set s [expr $s - ($minutes * 60)]
    set StartTextDay [clock format $s -format %a]
    set StartDay [clock format $s -format %d]
    set StartTextMonth [clock format $s -format %b]
    set StartYear [clock format $s -format %Y]
    set StartHour [clock format $s -format %H]
    set StartMinute [clock format $s -format %M]
    set StartSecond [clock format $s -format %S]
    set StartTime [clock scan "$StartTextDay $StartTextMonth $StartDay ${StartHour}:${StartMinute}:${StartSecond} $StartYear"]


}

proc TimeAdjustedManually {args} {
    foreach var "Start End" {
        global ${var}TextDay ${var}Day ${var}TextMonth ${var}Year 
        global ${var}Hour ${var}Minute ${var}Second ${var}Time
        
        set ${var}Time [clock scan "[set ${var}TextMonth] [set ${var}Day] [set ${var}Hour]:[set ${var}Minute]:[set ${var}Second] [set ${var}Year]"]
        set ${var}Minute [clock format [set ${var}Time] -format %M]
        set ${var}Hour [clock format [set ${var}Time] -format %H]
        set ${var}TextDay [clock format [set ${var}Time] -format %a]
        set ${var}Day [clock format [set ${var}Time] -format %d]
        set ${var}TextMonth [clock format [set ${var}Time] -format %b]
        set ${var}Year [clock format [set ${var}Time] -format %Y]
    }
}

proc TimeAdjusted {var widget value direction} {
    global ${var}TextDay ${var}Day ${var}TextMonth ${var}Year 
    global ${var}Hour ${var}Minute ${var}Second ${var}Time

    if {[lindex [split $widget .] end] == "second"} {
        if {$direction == "up"} {
            set direction "+"
        } else {
            set direction "-"
        }
        set ${var}Time [expr "[set ${var}Time] $direction (1)"]
        set ${var}Second [clock format [set ${var}Time] -format %S]
        set ${var}Minute [clock format [set ${var}Time] -format %M]
        set ${var}Hour [clock format [set ${var}Time] -format %H]
        set ${var}TextDay [clock format [set ${var}Time] -format %a]
        set ${var}Day [clock format [set ${var}Time] -format %d]
        set ${var}TextMonth [clock format [set ${var}Time] -format %b]
        set ${var}Year [clock format [set ${var}Time] -format %Y]
    } elseif {[lindex [split $widget .] end] == "minute"} {
        if {$direction == "up"} {
            set direction "+"
        } else {
            set direction "-"
        }
        set ${var}Time [expr "[set ${var}Time] $direction (60)"]
        set ${var}Minute [clock format [set ${var}Time] -format %M]
        set ${var}Hour [clock format [set ${var}Time] -format %H]
        set ${var}TextDay [clock format [set ${var}Time] -format %a]
        set ${var}Day [clock format [set ${var}Time] -format %d]
        set ${var}TextMonth [clock format [set ${var}Time] -format %b]
        set ${var}Year [clock format [set ${var}Time] -format %Y]
    } elseif {[lindex [split $widget .] end] == "hour"} {
        if {$direction == "up"} {
            set direction "+"
        } else {
            set direction "-"
        }
        set ${var}Time [expr "[set ${var}Time] $direction (60 * 60)"]
        set ${var}Hour [clock format [set ${var}Time] -format %H]
        set ${var}TextDay [clock format [set ${var}Time] -format %a]
        set ${var}Day [clock format [set ${var}Time] -format %d]
        set ${var}TextMonth [clock format [set ${var}Time] -format %b]
        set ${var}Year [clock format [set ${var}Time] -format %Y]
    } elseif {[lindex [split $widget .] end] == "textday"} {
        if {$direction == "up"} {
            set direction "+"
        } else {
            set direction "-"
        }
        set ${var}Time [expr "[set ${var}Time] $direction (24 * 60 * 60)"]
        set initTextDay [set ${var}TextDay]
        set ${var}TextDay [clock format [set ${var}Time] -format %a]
        if {$initTextDay != [set ${var}TextDay]} {
            #This is needed for the transition to daylight savings time.
            set ${var}Time [expr "[set ${var}Time] $direction (1 * 60 * 60)"]
            set ${var}TextDay [clock format [set ${var}Time] -format %a]
        }
        set ${var}Day [clock format [set ${var}Time] -format %d]
        set ${var}TextMonth [clock format [set ${var}Time] -format %b]
        set ${var}Year [clock format [set ${var}Time] -format %Y]
    } elseif {[lindex [split $widget .] end] == "day"} {
        if {$direction == "up"} {
            set direction "+"
        } else {
            set direction "-"
        }
        set ${var}Time [expr "[set ${var}Time] $direction (24 * 60 * 60)"]
        set initTextDay [set ${var}TextDay]
        set ${var}TextDay [clock format [set ${var}Time] -format %a]
        if {$initTextDay == [set ${var}TextDay]} {
            #This is needed for the transition to daylight savings time.
            set ${var}Time [expr "[set ${var}Time] $direction (1 * 60 * 60)"]
            set ${var}TextDay [clock format [set ${var}Time] -format %a]
        }
        set ${var}Day [clock format [set ${var}Time] -format %d]
        set ${var}TextMonth [clock format [set ${var}Time] -format %b]
        set ${var}Year [clock format [set ${var}Time] -format %Y]
    } elseif {[lindex [split $widget .] end] == "month"} {
        set month [clock format [set ${var}Time] -format %b]
        set year [clock format [set ${var}Time] -format %Y]
        set s1 [clock scan "$month 01 00:00:00 $year"]
        if {$direction == "up"} {
            if {$month == "Dec"} {
                incr year
            }
        } else {
            if {$month == "Jan"} {
                incr year -1
            }
        }
        set s2 [clock scan "[set ${var}TextMonth] 01 00:00:00 $year"]
        set s [expr {$s2 - $s1 + (60 * 60)}]
        set ${var}Time [expr "[set ${var}Time] + $s"]
        while {[set ${var}TextMonth] != [clock format [set ${var}Time] -format %b]} {
            if {$month == [clock format [set ${var}Time] -format %b]} {
                if {$direction == "up"} {
                    set ${var}Time [expr "[set ${var}Time] + (12 * 60 * 60)"]
                } else {
                    set ${var}Time [expr "[set ${var}Time] - (12 * 60 * 60)"]
                }
            } else {
                if {$direction == "up"} {
                    set ${var}Time [expr "[set ${var}Time] - (12 * 60 * 60)"]
                } else {
                    set ${var}Time [expr "[set ${var}Time] + (12 * 60 * 60)"]
                }
            }
        }
        set ${var}TextDay [clock format [set ${var}Time] -format %a]
        set ${var}Day [clock format [set ${var}Time] -format %d]
        set ${var}TextMonth [clock format [set ${var}Time] -format %b]
        set ${var}Year [clock format [set ${var}Time] -format %Y]
    } elseif {[lindex [split $widget .] end] == "year"} {
        if {([set ${var}Day] == "29") && ([set ${var}TextMonth] == "Feb")} {
            set ${var}Day 28
        }
        set ${var}Time [clock scan "[set ${var}TextMonth] [set ${var}Day] [set ${var}Hour]:[set ${var}Minute]:[set ${var}Second] [set ${var}Year]"]
        set ${var}TextDay [clock format [set ${var}Time] -format %a]
    }
    set ${var}Time [clock scan "[set ${var}TextMonth] [set ${var}Day] [set ${var}Hour]:[set ${var}Minute]:[set ${var}Second] [set ${var}Year]"]

}

proc CalcTime {} {
    foreach var "Start End" {
        global ${var}TextDay ${var}Day ${var}TextMonth ${var}Year 
        global ${var}Hour ${var}Minute ${var}Second ${var}Time
        global dateEntryStyle ${var}Month
        if {$dateEntryStyle == "old"} {
            if [catch {APSConvertTimeToHours [set ${var}Hour]} hour] {
                APSSetVarAndUpdate status "Invalid ${var}ing hour: [set ${var}Hour]"
                return
            }
            set ${var}Time \
              [expr int([exec timeconvert \
                           -breakDown=year=[set ${var}Year],day=[set ${var}Day],month=[set ${var}Month],hour=$hour])]
        } else {
            set ${var}Time [clock scan "[set ${var}TextMonth] [set ${var}Day] [set ${var}Hour]:[set ${var}Minute]:[set ${var}Second] [set ${var}Year]"]
        }
    }
}

proc MakeOptionsFrame {frame} {
    global vibrationPVList
    frame $frame
    pack $frame -fill both -expand true
    APSScrolledList .pv -parent $frame -packOption "-side left -fill y -anchor nw" -name "PV selection" -selectMode single -itemList $vibrationPVList -listvar selectedPV

    labelframe $frame.frame -text "Options"
    pack $frame.frame -side left -expand true -fill both

    checkbutton $frame.frame.c1 -text "Plot raw data" -variable options(raw)
    checkbutton $frame.frame.c2 -text "Plot maximum absolute value of each 2.048 seconds" -variable options(maximum)
    checkbutton $frame.frame.c3 -text "Plot simple RMS of each 2.048 seconds" -variable options(rms)

    checkbutton $frame.frame.c4 -text "Plot FFT (3-200HZ) in terms of displacement for each 2.048 seconds" -variable options(fft)
    checkbutton $frame.frame.c5 -text "Plot FFT (3-200HZ) in terms of displacement for entire time frame" -variable options(fftcombine)
    checkbutton $frame.frame.c6 -text "Plot PSD (3-200HZ) in terms of displacement for each 2.048 seconds" -variable options(psd)
    checkbutton $frame.frame.c7 -text "Plot PSD (3-200HZ) in terms of displacement for entire time frame" -variable options(psdcombine)
    checkbutton $frame.frame.c8 -text "Plot bandwidth limited RMS, (100-200Hz)" -variable options(psd200)
    checkbutton $frame.frame.c9 -text "Plot bandwidth limited RMS, (30-100Hz)" -variable options(psd100)
    checkbutton $frame.frame.c10 -text "Plot bandwidth limited RMS, (5-30Hz)" -variable options(psd30)

    pack $frame.frame.c1 $frame.frame.c2 $frame.frame.c3 $frame.frame.c4 $frame.frame.c5 $frame.frame.c6 $frame.frame.c7 $frame.frame.c8 $frame.frame.c9 $frame.frame.c10 -anchor nw 
    pack $frame.frame.c1 $frame.frame.c2 $frame.frame.c3 $frame.frame.c8 $frame.frame.c9 $frame.frame.c10 -anchor nw 
}

proc Plot {args} {
    APSStrictParseArguments {log}
    global StartTime EndTime status options selectedPV
    CalcTime

    set sel [.userFrame.options.pv.listbox curselection]
    if {$sel == ""} {
        set status "Please select a PV to plot"
        bell
        return
    }
    foreach s $sel {
        lappend pv [lindex $selectedPV $s]
        lappend systems [lindex [split [lindex $selectedPV $s] :] 0]
    }
    set systems [lsort -unique $systems]

    if {[clock format $StartTime -format %D] != [clock format $EndTime -format %D]} {
        set status "Please do not span multiple days in the time frame."
        bell
        return
    }
    if {$StartTime > $EndTime} {
        set tmp $EndTime
        set EndTime $StartTime
        set StartTime $tmp
    }
    
    set dataFiles ""
    foreach system $systems {
        set df [glob -nocomplain /home/helios/oagData/logging/VMS/VMS-${system}-[clock format $StartTime -format "%Y-%j-%m%d"].????? /home/helios/oagData/logging/VMS/VMS-${system}-[clock format $StartTime -format "%Y-%j-%m%d"].xz]
        if {[llength $df] > 0} {
            append dataFiles " $df"
        }
    }
    set dataFiles [string trim $dataFiles]

    if {[llength $dataFiles] == 0} {
        set status "No data files found for the selected date."
        bell
        return
    }
    APSSetVarAndUpdate status "Found $dataFiles"

    APSSetVarAndUpdate status "Processing..."
    set sec [clock seconds]
    if {[file isdirectory /local]} {
        set fn /local/VMS-[APSTmpString].tmp
    } else {
        set fn /tmp/VMS-[APSTmpString].tmp
    }
    APSAddToTempFileList $fn
    set n 0
    foreach name [array names options] {
        if {$options($name)} {
            incr n
        }
    }
    if {[llength $dataFiles] > 1} {
        if {($options(raw)) || ($options(maximum)) || ($options(fft)) || ($options(fftcombine)) || ($options(psd)) || ($options(psdcombine))} {
            if {[catch {eval exec sddscombine $dataFiles -pipe=out -retain=column,Index,[join $pv ,] -retain=param,Time,*:RMS* | sddsprocess -pipe -filter=param,Time,${StartTime},${EndTime} | sddsxref -pipe /home/helios/oagData/logging/VMS/VMS.TimeWF.sdds -equate=Index -take=TimeWF -reuse=page | sddsprocess -pipe \"-define=column,TimeData,i_row &TimeWF \\\[ Time +\" | sddsprocess -pipe=in $fn -delete=column,TimeWF,Index} results]} {
                set status "Unable to process $dataFiles.\n$results"
                file delete $fn
                bell
                return
            }
        } else {
            if {[catch {eval exec sddscombine $dataFiles -pipe=out -delete=column,* -retain=param,Time,*:RMS* | sddsprocess -pipe=in $fn -filter=param,Time,${StartTime},${EndTime} -nowarn} results]} {
                set status "Unable to process $dataFiles.\n$results"
                file delete $fn
                bell
                return
            }
        }
    } else {
        if {($options(raw)) || ($options(maximum)) || ($options(fft)) || ($options(fftcombine)) || ($options(psd)) || ($options(psdcombine))} {
            if {[catch {exec sddsprocess $dataFiles -pipe=out -retain=column,Index,[join $pv ,] -retain=param,Time,PageTimeStamp,*:RMS* -filter=param,Time,${StartTime},${EndTime} | sddsxref -pipe /home/helios/oagData/logging/VMS/VMS.TimeWF.sdds -equate=Index -take=TimeWF -reuse=page | sddsprocess -pipe "-define=column,TimeData,i_row &TimeWF \[ Time +" | sddsprocess -pipe=in $fn -delete=column,TimeWF,Index} results]} {
                set status "Unable to process $dataFiles.\n$results"
                file delete $fn
                bell
                return
            }
        } else {
            if {[catch {exec sddsprocess $dataFiles $fn -delete=column,* -retain=param,Time,*:RMS* -filter=param,Time,${StartTime},${EndTime} -nowarn} results]} {
                set status "Unable to process $dataFiles.\n$results"
                file delete $fn
                bell
                return
            }
        }
    }

    if {$log} {
        set mode "-mode=y=log,y=special -range=ymin=1"
    } else {
        set mode "-mode=y=linear"
    }

    if {$options(raw)} {
        APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
        if {$log} {
            APSSetVarAndUpdate status "Log plotting not available for raw data."
        }
        APSSetVarAndUpdate status "Plotting raw data..."
        exec sddsplot -legend -tick=xtime "-title=" "-topline=VMS Raw Data (m/s\$a2\$n)" $fn -col=TimeData,([join $pv ,]) -sever=xgap=.5 -graph=line,vary &
    }
    if {$options(maximum)} {
        APSAddToTempFileList ${fn}.max
        set cmdOptions ""
        foreach p $pv {
            append cmdOptions "-process=${p},largest,${p}:MAX "
        }
        if {[catch {eval exec sddsprocess $fn -pipe=out $cmdOptions -delete=column,TimeData | sddsprocess -pipe=in ${fn}.max -nowarn -delete=column,[join $pv ,]} results]} {
            set status "Unable to process $dataFiles.\n$results"
            file delete $fn ${fn}.max 
            bell
            return
        }
        APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
        APSSetVarAndUpdate status "Plotting maximum absolute values..."
        eval exec sddsplot $mode -legend -tick=xtime "{-title=}" "{-topline=VMS maximum absolute values (m/s\$a2\$n)}" ${fn}.max -param=Time,([join ${pv} ":MAX,"]:MAX) -sever=xgap=.5 -graph=symbol,connect=subtype,vary=subtype &
    }
    if {$options(rms)} {
        if {($options(raw)) || ($options(maximum))} {
            APSAddToTempFileList ${fn}.rms

            if {[catch {exec sddsprocess $fn ${fn}.rms -delete=column,* -nowarn} results]} {
                set status "Unable to process $dataFiles.\n$results"
                file delete $fn ${fn}.rms
                bell
                return
            }

            APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
            APSSetVarAndUpdate status "Plotting RMS values..."
            eval exec sddsplot $mode -legend -tick=xtime "{-title=}" "{-topline=VMS RMS values (m/s\$a2\$n)}" ${fn}.rms -param=Time,([join ${pv} ":RMS,"]:RMS) -sever=xgap=.5 -graph=symbol,connect=subtype,vary=subtype &
        } else {
            APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
            APSSetVarAndUpdate status "Plotting RMS values..."
            eval exec sddsplot $mode -legend -tick=xtime "{-title=}" "{-topline=VMS RMS values (m/s\$a2\$n)}" ${fn} -param=Time,([join ${pv} ":RMS,"]:RMS) -sever=xgap=.5 -graph=symbol,connect=subtype,vary=subtype &
        }
    }
    
    if {$options(fft)} {
        APSAddToTempFileList ${fn}.fft
        set cmdOptions ""
        foreach p $pv {
            append cmdOptions "\"-redefine=column,FFT${p},i_row &FFT$p \\\[ i_row &f \\\[ pi * 2 * sqr /\" "
        }

        if {[catch {eval exec sddsfft -nowarn $fn -pipe=out -columns=TimeData,[join $pv ,] | sddsprocess -pipe=in ${fn}.fft -filter=column,f,3,200 $cmdOptions } results]} {
            set status "Unable to process $dataFiles.\n$results"
            file delete $fn ${fn}.fft
            bell
            return
        }
        APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
        APSSetVarAndUpdate status "Plotting FFT values..."
        eval exec sddsplot $mode -samescale -split=page -sep=page -legend "{-title=@PageTimeStamp}" "{-topline=VMS FFT values}" ${fn}.fft -col=f,(FFT[join ${pv} ",FFT"]) -graph=line,vary &
    }
    if {$options(fftcombine)} {
        APSAddToTempFileList ${fn}.fftcombine
        set cmdOptions ""
        foreach p $pv {
            append cmdOptions "\"-redefine=column,FFT${p},i_row &FFT$p \\\[ i_row &f \\\[ pi * 2 * sqr /\" "
        }
        if {[catch {eval exec sddscombine $fn -pipe=out -merge | sddsfft -nowarn -pipe -columns=TimeData,[join $pv ,] | sddsprocess -pipe=in ${fn}.fftcombine -filter=column,f,3,200 $cmdOptions } results]} {
            set status "Unable to process $dataFiles.\n$results"
            file delete $fn ${fn}.fftcombine
            bell
            return
        }
        APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
        APSSetVarAndUpdate status "Plotting FFT values..."
        eval exec sddsplot $mode -samescale -split=page -sep=page -legend "{-title=}" "{-topline=VMS FFT values}" ${fn}.fftcombine -col=f,(FFT[join ${pv} ",FFT"]) -graph=dots,vary &
    }
    if {$options(psd)} {
        APSAddToTempFileList ${fn}.psd
        set cmdOptions ""
        foreach p $pv {
            append cmdOptions "\"-redefine=column,PSD${p},i_row &PSD$p \\\[ i_row &f \\\[ pi * 2 * sqr /\" "
        }
        if {[catch {eval exec sddsfft -nowarn $fn -pipe=out -psd -columns=TimeData,[join $pv ,] | sddsprocess -pipe=in ${fn}.psd -filter=column,f,3,200 $cmdOptions } results]} {
            set status "Unable to process $dataFiles.\n$results"
            file delete $fn ${fn}.psd
            bell
            return
        }
        APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
        APSSetVarAndUpdate status "Plotting PSD values..."
        eval exec sddsplot $mode -samescale -split=page -sep=page -legend "{-title=@PageTimeStamp}" "{-topline=VMS PSD values}" ${fn}.psd -col=f,(PSD[join ${pv} ",PSD"]) -graph=line,vary &
    }
    if {$options(psdcombine)} {
        APSAddToTempFileList ${fn}.psdcombine
        set cmdOptions ""
        foreach p $pv {
            append cmdOptions "\"-redefine=column,PSD${p},i_row &PSD$p \\\[ i_row &f \\\[ pi * 2 * sqr /\" "
        }
        if {[catch {eval exec sddscombine $fn -pipe=out -merge | sddsfft -nowarn -pipe -psd -columns=TimeData,[join $pv ,] | sddsprocess -pipe=in ${fn}.psdcombine -filter=column,f,3,200 $cmdOptions } results]} {
            set status "Unable to process $dataFiles.\n$results"
            file delete $fn ${fn}.psdcombine
            bell
            return
        }
        APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
        APSSetVarAndUpdate status "Plotting PSD values..."
        eval exec sddsplot $mode -samescale -split=page -sep=page -legend "{-title=}" "{-topline=VMS PSD values}" ${fn}.psdcombine -col=f,(PSD[join ${pv} ",PSD"]) -graph=dots,vary &
    }
    
    if {$options(psd200)} {
        if {($options(raw)) || ($options(maximum))} {
            APSAddToTempFileList ${fn}.psd200

            if {[catch {exec sddsprocess $fn ${fn}.psd200 -delete=column,* -nowarn} results]} {
                set status "Unable to process $dataFiles.\n$results"
                file delete $fn ${fn}.psd200
                bell
                return
            }

            APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
            APSSetVarAndUpdate status "Plotting PSD values..."
            eval exec sddsplot $mode -legend -tick=xtime "{-title=}" "{-topline=Bandwidth Limited RMS 100-200Hz (m)}" ${fn}.psd200 -param=Time,([join ${pv} ":RMS:100Hz:200Hz:BW,"]:RMS:100Hz:200Hz:BW) -sever=xgap=.5 -graph=symbol,connect=subtype,vary=subtype &
        } else {
            APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
            APSSetVarAndUpdate status "Plotting PSD values..."
            eval exec sddsplot $mode -legend -tick=xtime "{-title=}" "{-topline=Bandwidth Limited RMS 100-200Hz (m)}" ${fn} -param=Time,([join ${pv} ":RMS:100Hz:200Hz:BW,"]:RMS:100Hz:200Hz:BW) -sever=xgap=.5 -graph=symbol,connect=subtype,vary=subtype &
        }
    }
    if {$options(psd100)} {
        if {($options(raw)) || ($options(maximum))} {
            APSAddToTempFileList ${fn}.psd100

            if {[catch {exec sddsprocess $fn ${fn}.psd100 -delete=column,* -nowarn} results]} {
                set status "Unable to process $dataFiles.\n$results"
                file delete $fn ${fn}.psd100
                bell
                return
            }

            APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
            APSSetVarAndUpdate status "Plotting PSD values..."
            eval exec sddsplot $mode -legend -tick=xtime "{-title=}" "{-topline=Bandwidth Limited RMS 30-100Hz (m)}" ${fn}.psd100 -param=Time,([join ${pv} ":RMS:30Hz:100Hz:BW,"]:RMS:30Hz:100Hz:BW) -sever=xgap=.5 -graph=symbol,connect=subtype,vary=subtype &
        } else {
            APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
            APSSetVarAndUpdate status "Plotting PSD values..."
            eval exec sddsplot $mode -legend -tick=xtime "{-title=}" "{-topline=Bandwidth Limited RMS 30-100Hz (m)}" ${fn} -param=Time,([join ${pv} ":RMS:30Hz:100Hz:BW,"]:RMS:30Hz:100Hz:BW) -sever=xgap=.5 -graph=symbol,connect=subtype,vary=subtype &
        }
    }
    if {$options(psd30)} {
        if {($options(raw)) || ($options(maximum))} {
            APSAddToTempFileList ${fn}.psd30

            if {[catch {exec sddsprocess $fn ${fn}.psd30 -delete=column,* -nowarn} results]} {
                set status "Unable to process $dataFiles.\n$results"
                file delete $fn ${fn}.psd30
                bell
                return
            }

            APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
            APSSetVarAndUpdate status "Plotting PSD values..."
            eval exec sddsplot $mode -legend -tick=xtime "{-title=}" "{-topline=Bandwidth Limited RMS 5-30Hz (m)}" ${fn}.psd30 -param=Time,([join ${pv} ":RMS:5Hz:30Hz:BW,"]:RMS:5Hz:30Hz:BW) -sever=xgap=.5 -graph=symbol,connect=subtype,vary=subtype &
        } else {
            APSSetVarAndUpdate status "Processing took [expr [clock seconds] - $sec] seconds."
            APSSetVarAndUpdate status "Plotting PSD values..."
            eval exec sddsplot $mode -legend -tick=xtime "{-title=}" "{-topline=Bandwidth Limited RMS 5-30Hz (m)}" ${fn} -param=Time,([join ${pv} ":RMS:5Hz:30Hz:BW,"]:RMS:5Hz:30Hz:BW) -sever=xgap=.5 -graph=symbol,connect=subtype,vary=subtype &
        }
    }
    APSSetVarAndUpdate status "Done."
}



APSApplication . -name "Vibration Monitor Display"

set status "Ready..."
APSScrolledStatus .status -parent .userFrame -textVariable status -packOption "-fill both -expand true"


if {[catch {exec sdds2stream /home/helios/oagData/logging/VMS/VMS.wmon -column=WaveformName} vibrationPVList]} {
     APSSetVarAndUpdate status "Error reading /home/helios/oagData/logging/VMS/VMS.wmon. \n $vibrationPVList"
     bell
     set vibrationPVList ""
}
set vibrationPVList [join [split $vibrationPVList]]
MakeOptionsFrame .userFrame.options

set dateEntryStyle new
MakeDateTimeFrame .userFrame.date
TimePreset -minutes 60

APSButton .plot -parent .userFrame -text "Linear Plot" -command "Plot -log 0"
APSButton .logplot -parent .userFrame -text "Log Plot" -command "Plot -log 1"
set options(rms) 1
