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

proc SetStatus {text} {
    global statusText
    set statusText "$text ([clock format [clock seconds] -format %H:%M:%S])"
    update
}

proc GetFiles {args} {
    set snapshot 0
    set subSystem ""
    APSParseArguments {snapshot subSystem}

    if $snapshot {
        set rootname Snapshot_$subSystem
    } else {
        set rootname ""
    }
    global startYear startMonth startDay startHour endYear endMonth endDay endHour system
    
    set dir /home/helios/oagData/${system}/scope/archiveData/septumAcousticSignal/$subSystem

    set files [APSFindFilesBetweenDates -tailsOnly 1 -rootname "$rootname" \
                 -directory $dir \
                 -startDateList [APSFormatDate -year $startYear -month $startMonth \
                                   -day $startDay -dateFormat list] \
                 -endDateList [APSFormatDate -year $endYear -month $endMonth \
                                 -day $endDay -dateFormat list] ]
    if !$snapshot {
        set files1 [APSFindFilesBetweenDates -tailsOnly 1 -rootname "$subSystem" \
                 -directory $dir \
                      -startDateList [APSFormatDate -year $startYear -month $startMonth \
                                        -day $startDay -dateFormat list] \
                      -endDateList [APSFormatDate -year $endYear -month $endMonth \
                                      -day $endDay -dateFormat list] ]
        set files [concat $files1 $files]
    }
    if ![llength $files] {
        return -code error "No files found for $subSystem!"
    }
    return [lsort -decreasing $files]
}

proc Review {args} {
   
    global system fileSelection subSystem ReviewSnapshot
    if [catch {GetFiles -snapshot $ReviewSnapshot -subSystem $subSystem} files] {
        SetStatus $files
        return
    }
    set fileSelection ""
    if  [winfo exist .review] {
	destroy .review
    }
    APSScrolledListWindow .review -name "Ascoustic waveform files for $system" \
      -label "Select files" \
      -itemList $files -selectionVar fileSelection
    while {1} {
        tkwait variable fileSelection
        PlotData -files $fileSelection -subSystem $subSystem
    }
}

proc PlotData {args} {
    set files ""
    set subSystem ""
    APSParseArguments {files subSystem}
    global plotRaw plotVt plotFFT plotVtFFT separate sameScale plotOptions 
    global RawData RawVtData FFTData VtFFTData plotSignal_KHz plotSignal_f BV_KData BV_FData
    global system
    set dir /home/helios/oagData/${system}/scope/archiveData/septumAcousticSignal/$subSystem
    if ![llength $files] {
        SetStatus "No files chosen for plot"
        return
    }
    switch $system {
        sr {
            set col1 SpMgAM:2:scaledTimeAxisWF 
        }
        booster {
            set col1 SpMgAM:1:scaledTimeAxisWF 
        }
    }
    switch $subSystem {
        par {
            set col2 SpMgAM:1:chan1ScaledWaveWF
        }
        boo_inj {
            set col2 SpMgAM:1:chan2ScaledWaveWF
        }
        boo_ext_thin {
            set col2 SpMgAM:2:chan1ScaledWaveWF
        }
        boo_ext_thick {
            set col2 SpMgAM:2:chan2ScaledWaveWF
        }
        sr_thick {
            set col2 SpMgAM:2:chan3ScaledWaveWF
        }
        sr_thin {
            set col2 SpMgAM:2:chan4ScaledWaveWF
        }
        default {
            return -code error "Unknow system - $subSystem given"
        }
    }
    foreach file $files {
        if ![file exist $dir/$file] {
            continue
        }
        lappend fileList1 $dir/$file
        if ![file exist $dir/${file}.fft] {
            if [catch {exec sddsfft $dir/$file -pipe=out -col=$col1,$col2 \
                         | sddsprocess -pipe=in $dir/${file}.fft \
                         "-def=col,SignaldBV,FFT$col2 2 sqrt / 0.001 / log 20 *,units=dBVrms" \
                         "-define=col,KHz,f 1e+6 *,units=KHz" } result] {
                return -code error $result
            }
        }
        if ![file exist $dir/${file}.vt.fft] {
            if [catch {exec sddsfft $dir/$file $dir/${file}.vt.fft -col=t,V } result] {
                return -code error $result
            }
        }
        lappend fileList2 $dir/${file}.fft
        lappend fileList3 $dir/${file}.vt.fft
    }
    set plotOption ""
    if $separate {
        append plotOption " -separate"
    }
    if $sameScale {
        append plotOption " -samescale=y"
    }
    append plotOption " -graph=line,vary"
    append plotOption " $plotOptions"
    append plotOption " -legend=rootname,edit=a2Z\-%/.gz//%/.fft//%/.vt.fft//"
    if $plotRaw {
        set plotRawOption $plotOption
        append plotRawOptio " \-topline=ScopeWaveform versus time(us)\""
        append plotRawOption " -scale=$RawData(xstart),$RawData(xend),$RawData(ystart),$RawData(yend)"
        append plotRawOption " $fileList1 -col=$col1,$col2"
        eval exec sddsplot $plotRawOption &
    }
    if $plotVt {
        set plotVtOption $plotOption
        append plotVtOption " \"-topline=Voltage(V) versus time(s)\""
        append plotVtOption " -scale=$RawVtData(xstart),$RawVtData(xend),$RawVtData(ystart),$RawVtData(yend)"
        append plotVtOption " $fileList1 -col=t,V"
        eval exec sddsplot $plotVtOption &
    }
    if $plotFFT {
        set plotFFTOption $plotOption
        append plotFFTOption " \"-topline=FFT of scope waveform\""
        append plotFFTOption " -scale=$FFTData(xstart),$FFTData(xend),$FFTData(ystart),$FFTData(yend)"
        append plotFFTOption " $fileList2 -col=f,FFT${col2}"
        eval exec sddsplot $plotFFTOption &
    }
    if $plotVtFFT {
        set plotVtFFTOption $plotOption
        append plotVtFFTOption " \"-topline=FFT of Voltage\""
        append plotVtFFTOption " -scale=$VtFFTData(xstart),$VtFFTData(xend),$VtFFTData(ystart),$VtFFTData(yend)"
        append plotVtFFTOption " $fileList3 -col=f,FFTV"
        eval exec sddsplot $plotVtFFTOption &
    }
    if $plotSignal_KHz {
        set plot1 $plotOption
        append plot1 " \"-topline=Signal dBV versus KHz\" \"-ylabel=Singal dBV (dBVrms)\""
        append plot1 " -scale=$BV_KData(xstart),$BV_KData(xend),$BV_KData(ystart),$BV_KData(yend)"
        append plot1 " $fileList2 -col=KHz,SignaldBV"
        eval exec sddsplot $plot1 &
    } 
    if $plotSignal_f {
        set plot2 $plotOption
        append plot2 " \"-topline=Signal dBV versus f\" \"-ylabel=Singal dBV (dBVrms)\""
        append plot2 " -scale=$BV_FData(xstart),$BV_FData(xend),$BV_FData(ystart),$BV_FData(yend)"
        append plot2 " $fileList2 -col=f,SignaldBV"
        eval exec sddsplot $plot2 &
    }
}
proc SetupInitialScales {args} {
    global RawData RawVtData FFTData VtFFTData BV_KData BV_FData system subSystem
    switch $subSystem {
        par -
        boo_inj {
            set system booster
        }
        boo_ext_thin -
        boo_ext_thick -
        sr_thick -
        sr_thin {
            set system sr
        }
        default {
            return -code error "Unknown sub system given!"
        }
    }   
    set RawDataList {0 0 0 0}
    set FFTDataList {0 0 0 0}
    set RawVtDataList {0 .02 0 1}
    set VtFFTDataList {0 2000 0 .5}
    set BV_KDataList {0 20000 0 60}
    set BV_FDataList {0 .05 0 0}
    switch $subSystem {
        par {
            set RawDataList   {-10000  110000 -5  5   }
            set FFTDataList   {-.0001 .005   0  .5 }
            set RawVtDataList {-.01   .11   -2  2   }
            set VtFFTDataList {-100    5000    0  .3 }
            set BV_KDataList  {-1000   51000  -50 50  }
            set BV_FDataList  {-.001  .051  -50 50  }
        }
        boo_inj {
            set RawDataList    {-10000   110000    -2     2}
            set FFTDataList    {-.0001  .005      0     .1}
            set RawVtDataList  {-.01    .11      -.8   .8}
            set VtFFTDataList  {-100     5000       0     .04}
            set BV_KDataList   {-1000    51000     -60    40}
            set BV_FDataList   {-.001   .051     -60    40}
        }
        boo_ext_thin {
            set RawDataList {-1000 101000 -.5 1.5}
            set FFTDataList {-.0001 .003 0 .03}
            set RawVtDataList {-.01 .11 -.3 .03}
            set VtFFTDataList {-100 3000 0 .02}
            set BV_KDataList {-1000 51000 -70 40}
            set BV_FDataList {-.001 .051 -70 40}
        }
        boo_ext_thick {
            set FFTDataList {-.00001 .0005 0 0}
            set VtFFTDataList {-100 1000 0 0}
        }
        sr_thick {
            set FFTDataList {-.0001 .002 0 0}
            set VtFFTDataList {-100 2000 0 0}
        }
        sr_thin {
            set FFTDataList {-.0001 .002 0 0}
            set VtFFTDataList {-100 2000 0 0}
        }
    }
    foreach name {RawData RawVtData FFTData VtFFTData BV_KData BV_FData} {
        set valueList [set ${name}List]
        set i 0
        foreach axis {xstart xend ystart yend} {
            set ${name}($axis) [lindex $valueList $i]
            incr i     
        }
    }
}

proc CreateOptionWidget {args} {
    set parent ""
    set name ""
    APSStrictParseArguments {name parent}
    global $name
    APSFrame .f1 -parent $parent -label "$name"
    set w $parent.f1.frame
    APSLabeledEntry .xstart -parent $w -label "xstart:" -width 7 \
      -textVariable ${name}(xstart) -contextHelp "the start value of x-axis for plotting, if both xstart and xend are 0, auto scale is used for x-axis"
    APSLabeledEntry .xend -parent $w -label "xend:" -width 7 \
      -textVariable ${name}(xend) -contextHelp "the end value of x-axis for plotting, if both xstart and xend are 0, auto scale is used for x-axis"
     APSLabeledEntry .ystart -parent $w -label "ystart:" -width 7 \
      -textVariable ${name}(ystart) -contextHelp "the start value of y-axis for plotting, if both ystart and yend are 0, auto scale is used for x-axis"
    APSLabeledEntry .yend -parent $w -label "yend:" -width 7 \
      -textVariable ${name}(yend) -contextHelp "the end value of y-axis for plotting, if both ystart and xend are 0, auto scale is used for y-axis"
    
}

proc TakeSnapshot {args} {
    SetStatus "Taking snapshot..."
    global subSystem 
    if [catch {exec TakeSeptumScopeWaveformData \
                 -snapshot 1 -system $subSystem} result] {
        SetStatus "Error in taking snapshots: $result"
        return
    }
    SetStatus "done."
}

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

set statusText "ready."
set system booster
set subSystem par
APSApplication . -name "SeptumAcousticSignalReview" -version $CVSRevisionAuthor \
  -overview "Displays the septum acoustics signal waveform and fft plots."
APSScrolledStatus .status -parent .userFrame -textVariable statusText \
  -width 70
APSRadioButtonFrame .system -parent .userFrame -label "System:" \
  -buttonList {par boo_inj boo_ext_thin boo_ext_thick sr_thick sr_thin} \
  -valueList {par boo_inj boo_ext_thin boo_ext_thick sr_thick sr_thin} \
  -variable subSystem -orientation horizontal \
  -commandList {SetupInitialScales SetupInitialScales SetupInitialScales SetupInitialScales SetupInitialScales SetupInitialScales} \
  -contextHelp \
  "choose sr or booster for display the waveform."
APSDateTimeAdjEntry .startTime -parent .userFrame \
  -dayVariable startDay -yearVariable startYear \
  -monthVariable startMonth -hourVariable startHour \
  -label "Start date/time: " -twoDigitYear 0 -defaultHour 0
set startHour 0
APSDateTimeAdjEntry .stopTime -parent .userFrame \
  -dayVariable endDay -yearVariable endYear \
  -monthVariable endMonth -hourVariable endHour \
  -label "Stop date/time: " -twoDigitYear 0 -defaultHour 24
set endHour 24

set plotRaw 0
set plotVt 0
set plotFFT 1
set plotVtFFT 0
set plotSignal_KHz 0
set plotSignal_f 0
APSFrame .f1 -parent .userFrame -label "Choose Plots"
APSCheckButtonFrame .check -parent .userFrame.f1.frame -label "" \
  -buttonList {"raw_data  " "fft of raw  " "V ~ t  " "fft of V  " \
                 "Signal dBV ~ KHz  " "Signal dBV ~ f "} \
  -variableList {plotRaw plotFFT  plotVt plotVtFFT plotSignal_KHz plotSignal_f} -allNone 1  \
  -orientation horizontal \
  -contextHelp "check to plot raw data, plot V versus t in the raw data, plot the fft of raw data, plot
the fft of V-t, or plot of SignaldBV versus KHz and SignaldBV versus f of raw data's fft" 

APSFrame .scale -parent .userFrame -label "Scale Options"
APSFrameGrid .fg -parent .userFrame.scale.frame -xList {x1 x2 x3 x4 x5 x6}
for {set i 1} {$i<=6} {incr i} {
    set x$i .userFrame.scale.frame.fg.x$i
}
SetupInitialScales 
CreateOptionWidget -name RawData -parent $x1
CreateOptionWidget -name FFTData -parent $x2
CreateOptionWidget -name RawVtData -parent $x3
CreateOptionWidget -name VtFFTData -parent $x4
CreateOptionWidget -name BV_KData -parent $x5
CreateOptionWidget -name BV_FData -parent $x6
set separate 0
set sameScale 0
APSCheckButtonFrame .gr -parent .userFrame -label "Grouping: " -buttonList {separate "same scale"} \
  -variableList {separate sameScale} -orientation horizontal
set plotOptions ""
APSLabeledEntry .plotOption -parent .userFrame \
  -label "Other options:" -textVariable plotOptions \
  -contextHelp "Enter other options for all the plots." \
  -width 80

set ReviewSnapshot 0

APSButton .view -parent .userFrame -text "Review" -command Review
APSButton .testshot -parent .userFrame -text "Snapshot" -command TakeSnapshot
APSCheckButtonFrame .test -parent .userFrame -label "" -buttonList {"Review Snapshot"} \
    -variableList ReviewSnapshot -contextHelp "check to review test snapshots." \
    -packOption "-side left"
