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

#
# $Log: not supported by cvs2svn $
# Revision 1.40  2008/07/01 22:28:00  shang
# simplified the make reference procedure and added CheckReference procedure since it is being used multiple places; fixed the problem in checking waveform reference; and made it able to plot data if the reference does not exist.
#
# Revision 1.39  2007/11/16 18:59:23  shang
# the waveform name selection list now is sorted.
#
# Revision 1.38  2006/10/30 23:54:04  shang
# added alerting beep if error occurs during acquiring waveform.
#
# Revision 1.37  2006/02/17 15:21:38  borland
# Continuous running and abort features are now handled in the HP54542 machine
# procedure to reduce the number of scope setup events.
#
# Revision 1.36  2006/02/17 14:50:07  borland
# Fixed bug that prevented acquisition of waveforms if continuous acquistion
# was not requested.
#
# Revision 1.35  2006/02/16 23:09:44  borland
# Added reference link with .gz extension so the files can be accessed
# directly.
#
# Revision 1.34  2006/02/16 20:31:30  borland
# Added support for continuous archiving, which is needed by the top-up
# kicker archiver.
#
# Revision 1.33  2006/02/13 21:14:44  soliday
# Updated so that the legend is correct if the user selects to sort by signal.
# Also changed the code so that the title is correct if the user selects
# multiple files and selects to sort by date.
#
# Revision 1.32  2005/11/28 22:38:33  soliday
# Added the UserDescription to the selection listbox.
#
# Revision 1.31  2005/11/14 21:07:05  soliday
# Changed the plots that include the reference waveforms so that the date
# of the reference waveform is included in the plot title.
#
# Revision 1.30  2005/05/27 22:29:42  emery
# Made the file list decreasing so that most recent files
# are at the top.
#
# Revision 1.29  2004/07/13 19:49:09  shang
# added reference waveform feature to display reference waveforms along with any
# chosen waveform for comparison.
#
# Revision 1.28  2004/02/10 20:29:31  emery
# Made proper indents.
#
# Revision 1.27  2002/01/25 19:14:03  soliday
# Updated PV name.
#
# Revision 1.26  2002/01/21 16:30:28  borland
# Removed clip-last-half feature for PAR scope.
#
# Revision 1.25  2001/11/03 16:40:59  borland
# Changed SCR system for PAR scope to LPL.
#
# Revision 1.24  2001/07/29 22:54:53  borland
# For PAR scope, now passes -clipLastHalf option to APSDoHPScopeMeas (sp?) to
# kludge around prblem with scope waveform download.
#
# Revision 1.23  2001/05/16 15:12:20  soliday
# Added support for BunchPurity.
#
# Revision 1.22  1998/12/02 16:44:26  soliday
# Replaced sddscollapse with -collapse option in sddscombine.
#
# Revision 1.21  1998/10/07 19:26:17  borland
# Added export feature for waveforms.
#
# Revision 1.20  1998/06/16 20:44:18  borland
# Added catch around command that scrolls sddsplot execution log.
#
# Revision 1.19  1998/06/16 20:40:31  borland
# Now allows plotting waveforms normalized to PV value, if present in files.
# Also, better legends.  Uses exec log box to show sddsplot command.
#
# Revision 1.18  1998/06/09 16:35:07  borland
# Added more controls for plotting, including normalization and variable
# grouping.
#
# Revision 1.17  1998/05/20 16:45:56  borland
# Improved listbox widgets more.  Added use of clearCommand on waveform
# listbox so that the file list is cleared when the waveform selection is
# cleared.
#
# Revision 1.16  1998/05/20 16:09:58  borland
# Fixed problem with composition of plot commands when files where missing
# for one waveform.
#
# Revision 1.15  1998/05/20 15:44:40  borland
# Fixed clear button problem on waveform selection list.
#
# Revision 1.14  1998/05/20 15:42:28  borland
# Provides more control over plots.  Better organization of widgetry for
# scrolled lists.
#
# Revision 1.13  1998/05/19 20:48:02  borland
# Now permits viewing multiple signals together.
#
# Revision 1.12  1998/04/15 21:43:24  borland
# New version per D. Blachowicz.  The file selection dialog is no longer
# a pop-up but is contained within the main application.
#
# Revision 1.11  1998/02/27 16:58:18  borland
# Added slightly more informative messages to SwitchWaveformGroup for sdds
# errors.
#
# Revision 1.10  1997/11/06 22:48:59  borland
# Developmental version that I'm committing just to be safe.  Seems to work,
# but on hold until problems with scope are fixed.
#
# Revision 1.9  1997/09/19 15:33:36  borland
# Now gzip's data files after collecting them.
#
# Revision 1.8  1997/04/17 00:06:34  borland
# Modified plot command to do samescales option for y only.  This is needed
# because of big trigger changes.
#
# Revision 1.7  1997/04/09 20:38:55  borland
# Now allows selection of specific waveforms that are to be plotted,
# from a list of date/time for waveforms.
#
# Revision 1.6  1997/04/09 19:54:06  borland
# Allows user description entry and puts same on plots.
#
# Revision 1.5  1997/04/08 00:59:03  borland
# Removed -SCRSystem option from call to set up scope and take measurement.
#
# Revision 1.4  1997/03/31 21:28:17  borland
# Fixed minor bug that resulted in a plot coming up after switching
# waveform groups even if a specific waveform wasn't chosen.
#
# Revision 1.3  1997/03/12 18:32:07  borland
# Made a cosmetic change to a label.
#
# Revision 1.2  1997/02/17 16:58:27  borland
# Added check for blank plot selection string before trying to plot.
#
# Revision 1.1  1997/01/22 17:38:38  borland
# First version.
#
#

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

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

set apsScopeWaveformAbort 0

set usage "usage: ScopeWaveformHistory -ring {SR | PAR}"
set args $argv
set ring PAR
if [APSStrictParseArguments {ring}] {
    APSAlertBox [APSUniqueName .] -errorMessage "$usage"
    exit 1
}
switch $ring {
    PAR {
        set dataDir /home/helios/oagData/par/scope/archiveData2
        set SCRSystem LPL
    }
    SR {
        set dataDir /home/helios/oagData/sr/scope/archiveData1
        set SCRSystem SR
    }
    default {
        APSAlertBox [APSUniqueName .] -errorMessage "$usage"
        exit 1
    }
}

APSApplication . -name $ring:ScopeWaveformHistory -version $CVSRevisionAuthor \
  -overview "Provides for acquisition and review of scope waveforms from HP54542A digital scopes."

set status Working...
APSScrolledStatus .status -parent .userFrame -textVariable status \
  -width 110 -height 6 -packOption "-fill x" -lineLimit 10000
update

set waveformGroup ""
set lastWaveformGroup ""
set groupNameList ""
set specFileList ""
set abortHonoredList ""

proc MakeGroupSelectionWidget {widget args} {
    set parent ""
    APSStrictParseArguments {parent}
    
    global waveformGroup dataDir lastWaveformGroup groupNameList specFileList  env abortHonoredList
    global doPromptList 

    set specList [lsort [glob -nocomplain $dataDir/*.spec]]
    if [string compare $env(USER) "asdops"] {
        set specList [lsort [glob -nocomplain $dataDir/*.spec $dataDir/*.spec-hidden]]
    }
    if [llength $specList]==0 {
        APSAlertBox [APSUniqueName .] -errorMessage \
          "No measurement specifications for $ring!"
        exit 1
    }
    set titleFile /tmp/[APSTmpString]
    if {[catch {eval exec sddscombine $specList -collapse -pipe=out | sddssort -pipe=in $titleFile -col=Title -unique } result] || \
          [catch {APSGetSDDSColumn -fileName $titleFile \
                    -column Title -page 0} groupNameList] || \
          [catch {APSGetSDDSColumn -fileName $titleFile \
                    -column Filename -page 0} specFileList]} {
        APSAlertBox [APSUniqueName .] -errorMessage "$result"
        catch {exec rm $titleFile}
        exit 1
    }
    if {[catch {APSGetSDDSColumn -fileName $titleFile -column DoPrompt -page 0} doPromptList]} {
        set doPromptList [APSReplicateItem -item 1 -number [llength $specFileList]]
    }
    if [catch {APSGetSDDSColumn -fileName $titleFile -column AbortHonored} abortHonoredList] {
        set abortHonoredList [APSReplicateItem -item 0 -number [llength $groupNameList]]
    }

    set commandList ""
    foreach elem $groupNameList {
        lappend commandList SwitchWaveformGroup 
    }
    #catch {exec rm $titleFile}
    set lastWaveformGroup None
    APSRadioButtonFrame $widget -parent $parent -label "Waveform group: " \
      -variable waveformGroup -buttonList $groupNameList \
      -valueList $groupNameList -orientation vertical \
      -commandList $commandList -limitPerRow 2 \
      -contextHelp \
      "Choose the waveform group for archiving and review."
}

proc SwitchWaveformGroup {} {
    global waveformGroup lastWaveformGroup dataDir specFileList groupNameList
    global waveformListWidget waveformSelection directoryList waveformList
    global directorySelection fileListWidget
    set waveformSelection ""
    set directorySelection ""
    if [string compare $waveformGroup $lastWaveformGroup]==0 {
        return
    }
    set index [lsearch $groupNameList $waveformGroup]
    if $index==-1 {
        APSSetVarAndUpdate status "Invalid group: $waveformGroup !"
        return
    }
    set tmpfile /tmp/[APSTmpString].scope
    APSAddToTmpFileList -ID scopehis -fileList $tmpfile
    if [catch {exec sddssort -col=WaveformName -numericHigh [lindex $specFileList $index] $tmpfile} result] { 
        APSSetVarAndUpdate status "$result"
        return
    }
    if [catch {APSGetSDDSColumn -fileName $tmpfile \
                 -column WaveformName} waveformList] {
        APSSetVarAndUpdate status "$waveformList reading [lindex $specFileList $index]"
        return
    }
    if [catch {APSGetSDDSColumn -fileName $tmpfile \
                 -column DirectoryName} directoryList] {
        APSSetVarAndUpdate status "$directoryList reading [lindex $specFileList $index]"
        return
    }
    if {[file tail [lindex $specFileList $index]] == "SRScopeMeasStoredBeam.spec"} {
        append waveformList " BunchPurity"
        append directoryList " BunchPurity"
    }
    set lastWaveformGroup $waveformGroup
    $waveformListWidget.listbox delete 0 end
    eval $waveformListWidget.listbox insert 0 $waveformList
    
    $fileListWidget.listbox delete 0 end
}

set waveformSelectionList ""
proc SwitchWaveform {selectionList} {
    global waveformSelectionList directorySelection directoryList waveformList
    set waveformSelectionList $selectionList
    SearchForWaveformFiles
}

set waveformListWidget ""
set fileListWidget ""
set reviewFrameWidget ""
proc MakeReviewFrame {widget args} {
    set parent ""
    APSStrictParseArguments {parent}
    global waveformListWidget reviewFrameWidget fileListWidget

    APSFrame $widget -parent ${parent} -packOption "-fill both -expand true"

    set w $parent${widget}.frame
    set reviewFrameWidget $w
    set waveformListWidget $w.signals.frame.wflist.userFrame.sl
    set fileListWidget $w.files.frame.list.userFrame.sl

    APSFrame .signals -parent $w -label "Review" -packOption "-side left -fill y -expand false"
    pack configure $w.signals.frame -expand true -fill y

    APSScrolledListWindow .wflist -parent $w.signals.frame \
      -closeButton 0 -clearButton 1 -acceptButton 1 \
      -selectionVar dummySelection \
      -packOption "-fill both -expand true" \
      -autoAccept 0 -callback SwitchWaveform -contextHelp \
      "Select the waveform or waveforms you want to plot, then hit Accept." 

    APSFrame .files -parent $reviewFrameWidget -label "File Selection List" \
      -packOption "-side right -fill both -expand true"
    APSScrolledListWindow .list -parent $reviewFrameWidget.files.frame \
      -name "FileSelectionWindow" \
      -packOption "-fill both -expand true" \
      -clearButton 0 -closeButton 0 -acceptButton 0 -selectionVar listSelection \
      -autoAccept 1 -contextHelp \
      "Select the specific waveforms you want to see and press Plot.  The individual waveforms are labeled by year, Julian day, month, day, and time, in the format YYYY-JJJ-MMDD-HHMMSS."
    
    APSButton .plot \
      -parent $reviewFrameWidget.files.frame.list.buttonRow -text Plot -command "PlotWaveforms" 
    APSButton .export \
      -parent $reviewFrameWidget.files.frame.list.buttonRow -text Export -command "ExportWaveforms" 
    APSButton .remove \
      -parent $reviewFrameWidget.files.frame.list.buttonRow -text Delete -command "DeleteWaveforms" 
    APSButton .reference \
      -parent $reviewFrameWidget.files.frame.list.buttonRow -text "Make Reference" \
      -command "MakeReferenceWaveform"
    APSButton .kickerpar \
      -parent $reviewFrameWidget.files.frame.list.buttonRow -text "Plot Kicker Parameters" \
      -command "PlotKickerParameters"
}

set selectCheck(none) 1
set descDir ""
proc SearchForWaveformFiles {args} {

    global waveformSelectionList dataDir directorySelection directoryList waveformList
    if ![llength $waveformSelectionList] {
        APSSetVarAndUpdate status "Select something to plot."
        return
    }

    set waveformSelection [lindex $waveformSelectionList 0]
    set directorySelection [lindex $directoryList [lsearch $waveformList $waveformSelection]]
    set fileList0 [lsort -decreasing [glob -nocomplain $dataDir/$directorySelection/????-???-????-?????? \
                                        $dataDir/$directorySelection/????-???-????-??????.gz \
                                       $dataDir/$directorySelection/????-???/????-???-????-??????.gz]]
    if ![llength $fileList0] {
        APSSetVarAndUpdate status "No data for $waveformSelection"
        return
    }

    global listSelection fileListWidget selectCounter selectCheck descDir
    set listSelection ""
    regsub -all $dataDir/${directorySelection}/ $fileList0 {} fileList
    regsub -all .gz $fileList {} fileList0
    unset -nocomplain selectCheck
    set selectCheck(none) 1
    set descDir $dataDir/$directorySelection
    $fileListWidget.listbox delete 0 end
    eval $fileListWidget.listbox insert 0 $fileList0
    GetDescriptions -dir $dataDir/$directorySelection
    bindtags $fileListWidget.scroll "Scrollbar $fileListWidget.scroll . all"
    bind $fileListWidget.scroll <B1-ButtonRelease> {GetDescriptions -dir $dataDir/$directorySelection}
    
}

proc GetDescriptions {args} {
    global fileListWidget selectCheck descDir
    set index [$fileListWidget.listbox index @0,0]
    set endseen 0
    if {[llength [$fileListWidget.listbox bbox end]]} {
        set endseen 1
    }
    set i 0
    while {([llength [$fileListWidget.listbox bbox $index]]) || ($i < 2)} {
        if {![llength [$fileListWidget.listbox bbox $index]]} {
            incr i
        }
        if {[info exists selectCheck($index)]} {
            incr index
            continue
        }
        set selectCheck($index) 1
        set item [$fileListWidget.listbox get $index]
        if {[llength $item] != 1} {
            incr index
            continue
        }
        set f ${descDir}/${item}.gz
        if {![file exists $f]} {
            set f ${descDir}/${item}
        }
        if {[catch {APSGetSDDSParameter -fileName $f -parameter UserDescription -page 1} desc]} {
            set desc ""
        }
        $fileListWidget.listbox delete $index
        $fileListWidget.listbox insert $index "${item} [join $desc]"
        incr index
    }
    if {$endseen == 1} {
        $fileListWidget.listbox see end
    }
    update
}

proc PlotWaveforms {} {
    global listSelection waveformSelectionList dataDir directorySelection directoryList waveformList
    global normalizeSignals hLimitLow hLimitHigh userOptions sameScales groupPlotsBy
    global includeReference

    set oldDir [pwd]
    set optionList ""
    set suffix ""
    switch $normalizeSignals {
        0 {
        }
        1 {
            set optionList -mode=y=normalize
            lappend optionList "-ylabel=edit=ei/ Normalized to 1/"
        }
        Setpoint {
            set suffix Norm
        }
    }
    if $sameScales {
        lappend optionList "-sameScales=x,y,global"
    }
  # lappend optionList "-title=@UserDescription"
    set otherOptions ""
    set options1 ""
    set step -1
    set items ""
    foreach item [lsort -index 0 $listSelection] {
        append items "[lindex $item 0] "
    }
    foreach item $items {
        incr step
        foreach waveform $waveformSelectionList {
            set index [lsearch $waveformList $waveform]
            set dirname [lindex $directoryList $index]
            if $includeReference {
                if [catch {CheckReference -waveform $waveform} reference] {
                    APSSetVarAndUpdate status "$reference"
                    return
                }
            }
            if [file exists $dataDir/$dirname/$item.gz] {
                if {$dirname == "BunchPurity"} {
                    lappend options1 -column=Index,(S35:mca1.VAL,S36AM:BP:mca) -graph=impulse -mode=y=log,y=special
                    if {$groupPlotsBy=="Date" || !$step} {
                        lappend otherOptions -column=Index,(S35:mca1.VAL,S36AM:BP:mca) -graph=impulse -mode=y=log,y=special
                    }
                } else {
                    lappend options1 -column=t,${waveform}$suffix
                    if {$groupPlotsBy=="Date" || !$step} {
                        lappend otherOptions -column=t,${waveform}$suffix
                    }
                }
                lappend options1 $dataDir/$dirname/$item.gz
                if {[catch {exec sdds2stream $dataDir/$dirname/$item.gz -parameter=TimeStamp -page=1 -noquotes} title]} {
                    APSSetVarAndUpdate status "Error: unable to read timestamp parameter"
                    return
                }
                if {$includeReference} {
                    if [file exist $reference] {
                        lappend otherOptions $reference
                        if {[catch {exec sdds2stream $reference -parameter=TimeStamp -page=1 -noquotes} title2]} {
                            APSSetVarAndUpdate status "Error: unable to read timestamp parameter"
                            return
                        }
                        append title " - ($title2 Reference)"
                    }
                }
            } else {
                if [file exists $dataDir/$dirname/$item] {
                    if {$dirname == "BunchPurity"} {
                        lappend options1 -column=Index,(S35:mca1.VAL,S36AM:BP:mca) -graph=impulse -mode=y=log,y=special
                        if {$groupPlotsBy=="Date" || !$step} {
                            lappend otherOptions -column=Index,(S35:mca1.VAL,S36AM:BP:mca) -graph=impulse -mode=y=log,y=special
                        }
                    } else {
                        lappend options1 -column=t,${waveform}$suffix
                        if {$groupPlotsBy=="Date" || !$step} {
                            lappend otherOptions -column=t,${waveform}$suffix
                        }
                    }
                    lappend options1 $dataDir/$dirname/$item
                    if {[catch {exec sdds2stream $dataDir/$dirname/$item -parameter=TimeStamp -page=1 -noquotes} title]} {
                        APSSetVarAndUpdate status "Error: unable to read timestamp parameter"
                        return
                    }
                    if {$includeReference} {
                        if [file exist $reference] {
                            if {$groupPlotsBy=="Date" || !$step} {
                                lappend otherOptions $reference
                                if {[catch {exec sdds2stream $reference -parameter=TimeStamp -page=1 -noquotes} title2]} {
                                    APSSetVarAndUpdate status "Error: unable to read timestamp parameter"
                                    return
                                }
                                append title " - ($title2 Reference)"
                            }
                        }
                    }
                } else {
                    APSSetVarAndUpdate status "No file found for $waveform $item"
                    continue
                }
            }
            switch $groupPlotsBy {
                Date {
                    lappend options1 -tag=[lsearch $items $item] 
                    lappend options1 "-legend=specified=$waveform"
                    lappend otherOptions -tag=[lsearch $items $item] 
                    lappend otherOptions "-legend=specified=${waveform}_ref"
                }
                Signal {
                    lappend options1 -tag=[lsearch $waveformSelectionList $waveform]
                    lappend options1 "-legend=specified=$item,edit=5f4d"
                    if !$step {
                        lappend otherOptions -tag=[lsearch $waveformSelectionList $waveform]
#                        lappend otherOptions "-legend=specified=$item,edit=5f4dei/(ref)/"
                        lappend otherOptions "-legend=specified=${waveform}_ref"
                    }
                }
            }
            lappend options1 "-title=$title"
        }
    }
    if {!$includeReference} {
        set otherOptions ""
    }
    set unixCommand "sddsplot -split=page -topline=@UserDescription -split=page -graph=line,vary  \
      -groupby=tag -sep=tag \
      -scale=$hLimitLow,$hLimitHigh,0,0 \
       $userOptions $optionList $otherOptions $options1"
    APSExecLog .scopePlots -unixCommand $unixCommand -name "sddsplot execution window" \
      -width 100
    catch {.scopePlots.userFrame.text.text see end}
    cd $oldDir
    APSSetVarAndUpdate status "Plot launched."
}

proc ExportWaveforms {} {
    global listSelection waveformSelectionList dataDir directorySelection directoryList waveformList

    global doExportWaveforms exportWaveformsDir exportWaveformsRootname
    set doExportWaveforms -1

    set widget [APSUniqueName  .]
    APSDialogBox $widget -okCommand "set doExportWaveforms 1" \
      -cancelCommand "set doExportWaveforms 0"
    APSLabeledEntry .le1 -parent $widget.userFrame -textVariable exportWaveformsDir \
      -label "Export to directory: " -width 40 -contextHelp \
      "Enter the name of a directory in which the files will be placed."
    APSLabeledEntry .le2 -parent $widget.userFrame -textVariable exportWaveformsRootname \
      -label "Export to rootname:  " -width 40 -contextHelp \
      "Enter a rootname for creation of filenames for the exported data."
    update 
    tkwait variable doExportWaveforms
    if !$doExportWaveforms {
        APSSetVarAndUpdate status "Export cancelled."
    }
    
    set items ""
    foreach item [lsort -index 0 $listSelection] {
        append items "[lindex $item 0] "
    }
    foreach item $items {
        foreach waveform $waveformSelectionList {
            set index [lsearch $waveformList $waveform]
            set dirname [lindex $directoryList $index]
            if [file exists $dataDir/$dirname/$item.gz] {
                set fileName $dataDir/$dirname/$item.gz
                set extension .gz
            } else {
                if [file exists $dataDir/$dirname/$item] {
                    set fileName $dataDir/$dirname/$item
                    set extension ""
                } else {
                    APSSetVarAndUpdate status "No file found for $waveform $item"
                    continue
                }
            }
            APSSetVarAndUpdate status "Working on $waveform $item"
            if [catch \
                  {exec cp $fileName \
                     $exportWaveformsDir/$exportWaveformsRootname-$waveform-$item$extension} \
                  result] {
                APSSetVarAndUpdate status "Error: $result"
            }
        }
    }
    APSSetVarAndUpdate status "File export done."
}

proc DeleteWaveforms {} {
    global listSelection waveformSelectionList dataDir directorySelection directoryList waveformList

    set items ""
    foreach item [lsort -index 0 $listSelection] {
        append items "[lindex $item 0] "
    }
    foreach item $items {
        foreach waveform $waveformSelectionList {
            set index [lsearch $waveformList $waveform]
            set dirname [lindex $directoryList $index]
            set fileToDelete ""
            if [file exists $dataDir/$dirname/$item.gz] {
                set fileToDelete $dataDir/$dirname/$item.gz
            } else {
                if [file exists $dataDir/$dirname/$item] {
                    set fileToDelete $dataDir/$dirname/$item
                } else {
                    APSSetVarAndUpdate status "No file found for $waveform $item"
                    continue
                }
            }
            if {[string length $fileToDelete] && \
                  [APSMultipleChoice [APSUniqueName .] \
                     -question "Delete $item $waveform?" \
                     -returnList {0 1} -labelList {No Yes}]} {
                if [catch {exec rm -f $fileToDelete} result] {
                    APSSetVarAndUpdate status "Can't delete $item $waveform: $result"
                    continue
                }
                APSSetVarAndUpdate status "$item $waveform deleted."
            }
        }
    }
}

proc PlotKickerParameters {} {
    global listSelection waveformSelectionList dataDir directorySelection directoryList waveformList
    
    set item [lindex [lindex $listSelection 0] 0]
    
    foreach waveform $waveformSelectionList {
        set index [lsearch $waveformList $waveform]
        set dirname [lindex $directoryList $index]
      #  puts $dirname
        if [regexp "TopUpIK" $dirname] {
            PlotTopUpKickerParameters -kicker $dirname
        } else {
            #skip, only plot for topup kickers
            continue
        }
    }
}

proc PlotTopUpKickerParameters {args} {
    set kicker ""
    APSParseArguments {kicker}

    set kickerDir /home/helios/oagData/monitoring/$kicker
    cd $kickerDir
    set files [lsort -decreasing [glob ${kicker}*.gz]]
  #  puts $files
    
    global fileSelection ""
    set fileSelection1 ""
    APSScrolledListWindow .process -name "Select a file" \
      -label "Select a file" \
      -itemList $files -selectionVar fileSelection
    tkwait variable fileSelection
    if ![string length $fileSelection] {
        APSSetVarAndUpdate status  "No file chosen"
        return
    }
    if [llength $fileSelection]>1 {
        set tmpRoot /tmp/[APSTmpString]
        if [catch {eval exec sddscombine $fileSelection -merge -pipe=out \
                     | sddssort -pipe=in $tmpRoot -col=Time } result] {
            return -code error "Error combining kicker parameter files: $result"
        }
        set plotFile $tmpRoot
        APSAddToTmpFileList -ID scopehis -fileList $tmpRoot
    } else {
        set plotFile $fileSelection
    }
    
    exec sddsplot -col=Time,IK*PeakPos $plotFile -grap=sym,conn,sca=2,fil -leg \
      -tick=xtime &
    

}

proc MakeReferenceWaveform {} {
    global listSelection waveformSelectionList dataDir directorySelection directoryList waveformList
    
    if [llength $listSelection]==0 {
        APSSetVarAndUpdate status "No files selected for making reference waveform."
        return
    } elseif [llength $listSelection]>1 {
        APSSetVarAndUpdate status "error: more than one files are selected for making reference waveform."
        return
    }
    set item [lindex [lindex $listSelection 0] 0]
    
    foreach waveform $waveformSelectionList {
        set index [lsearch $waveformList $waveform]
        set dirname [lindex $directoryList $index]
        set fileLinkTo ""
        set referenceWaveform $dataDir/$dirname/${waveform}.ref
        if [file exists $dataDir/$dirname/$item.gz] {
            set fileLinkTo $dataDir/$dirname/$item.gz
            set referenceWaveform $dataDir/$dirname/${waveform}.ref.gz
        } else {
            if [file exists $dataDir/$dirname/$item] {
                set fileLinkTo $dataDir/$dirname/$item
            } else {
                APSSetVarAndUpdate status "No file found for $waveform $item"
                continue
            }
        }
	catch {exec rm $referenceWaveform}
	
        if [catch {exec ln -s $fileLinkTo $referenceWaveform} result] {
            APSSetVarAndUpdate status "Error in linking $fileLinkTo to $referenceWaveform: $result"
            continue
        }
        # APSSetVarAndUpdate status "$fileLinkTo is made as reference of $waveform."
        # exec setfacl -m mask:rwx $referenceWaveform
        # exec chmod a+w $referenceWaveform
        APSSetVarAndUpdate status "Reference for $waveform waveform made."
    }  
}

proc IncludeReferenceSelection {} {
    global listSelection waveformSelectionList dataDir directorySelection directoryList waveformList
    global includeReference    
    
    if [llength $waveformSelectionList] {
        foreach waveform $waveformSelectionList { 
            if [catch {CheckReference -waveform $waveform} reference] {
                APSSetVarAndUpdate status "$reference."
                set includeReference 0
                return
            }
        }  
        set includeReference 1
    } else {
        APSSetVarAndUpdate status "Error: No waveforms selected."
        set includeReference 0
        return
    }
}

proc EnableDisableButton {args} {
    global acquireButton Enable
    if $Enable {
	APSEnableWidget $acquireButton
    } else {
	APSDisableWidget $acquireButton
    }
}

set userDescription ""
proc MakeArchiveFrame {widget args} {
    set parent ""
    APSStrictParseArguments {parent}

    global acquireButton Enable
    set Enable 0
    APSFrame $widget -parent $parent -label "Archive"
    set w $parent$widget.frame
    APSLabeledEntry .descrip -parent $w -label "Description: " \
      -textVariable userDescription -width 60 -contextHelp \
      "Enter a text description of the circumstances under which this data is being taken."
    APSButton .acquire -parent $w \
      -text Acquire -command "AcquireWaveforms -widget $w" -contextHelp \
      "Acquires data for the archive for the selected group of waveforms."
    set acquireButton $w.acquire
    APSButton .abort -parent $w \
      -text Abort -command "set apsScopeWaveformAbort 1" -contextHelp \
      "Aborts acquisition of waveforms"
    #APSButton .enable -parent $w -text "Enable" -command "APSEnableWidget $acquireButton"
    APSCheckButtonFrame .enable -parent $w -packOption "-side left" -label "" \
	-buttonList "enable/disable" -variableList "Enable" -commandList EnableDisableButton
    APSDisableWidget $w.abort
    APSDisableWidget $w.acquire
}

proc BunchPurityMeas {args} {
    set dataDir ""
    set rootname ""
    set statusCallback ""
    set doPrompt 0
    set userDescription ""
    set doGzip 0
    APSStrictParseArguments {dataDir rootname statusCallback doPrompt userDescription doGzip}

    catch {exec timeconvert -breakdown=now} seconds
    catch {exec timeconvert -seconds=$seconds -textOutput} timeStamp
    catch {exec timeconvert -seconds=$seconds} timeList
    set file [format %04ld-%03ld-%02ld%02ld-%02ld%02ld%02ld \
                [lindex $timeList 0] [lindex $timeList 1] \
                [lindex $timeList 2] [lindex $timeList 3] \
                [lindex $timeList 5] [lindex $timeList 6] \
                [lindex $timeList 7]]
    if {[catch {exec sddswmonitor [file join $dataDir BunchPurity $file] -pv=S36AM:BP:mca} results]} {
        APSSetVarAndUpdate status "$results"
        return
    }
    if {[catch {exec sddsprocess [file join $dataDir BunchPurity $file] \
                  [file join $dataDir BunchPurity $file].gz  \
                  "-print=param,UserDescription,[APSMakeSafeQualifierString $userDescription]"} results]} {
        file delete -force [file join $dataDir BunchPurity $file].gz
        APSSetVarAndUpdate status "$results"
    }
    file delete -force [file join $dataDir BunchPurity $file]
    return
}

proc AcquireWaveforms {args} {
    set widget ""
    APSStrictParseArguments {widget}
    global waveformGroup lastWaveformGroup dataDir specFileList groupNameList
    global waveformListWidget SCRSystem userDescription ring abortHonoredList
    global doPromptList

    set index [lsearch $groupNameList $waveformGroup]
    if $index==-1 {
        APSSetVarAndUpdate status "Invalid group: $waveformGroup !"
        return
    }
    if ![string length $userDescription] {
        APSSetVarAndUpdate status "No description---can't save data."
        return
    }
    set specFile [lindex $specFileList $index]
    set doPrompt [lindex $doPromptList $index]

    APSSetVarAndUpdate status "Archiving $waveformGroup waveforms"
    if {[file tail [file rootname $specFile]] == "SRScopeMeasStoredBeam"} {
        if [catch {BunchPurityMeas -dataDir $dataDir \
                       -rootname [file tail [file rootname $specFile]] \
                       -statusCallback "APSSetVarAndUpdate status" \
                       -userDescription $userDescription \
                       -doPrompt 1 -doGzip 1} result] {
            APSSetVarAndUpdate status "$result"
            APSAlertBox [APSUniqueName .] -beep continuous -announceWorkstation 1 \
                -errorMessage "$result"
            return
        }
    }
    set clipLastHalf 0
    if [string compare $ring PAR]==0 {
        set clipLastHalf 0
    }
    set continuous 0
    if [lindex $abortHonoredList $index]==1 {
        APSEnableWidget $widget.abort
        APSDisableWidget $widget.acquire
        set continuous 1
    }
    set continuous 0
    global apsScopeWaveformAbort
    set apsScopeWaveformAbort 0
    if [catch {APSMpCollectHP9000ScopeData -dataDir $dataDir -ring $ring \
                 -clipLastHalf $clipLastHalf -continuous $continuous \
                 -rootname [file tail [file rootname $specFile]] \
                 -statusCallback "APSSetVarAndUpdate status" \
                 -userDescription $userDescription \
                 -doPrompt $doPrompt -doGzip 1 -abortVariable apsScopeWaveformAbort} result] {
        APSSetVarAndUpdate status "$result"
        APSAlertBox [APSUniqueName .] -beep continuous -announceWorkstation 1 \
          -errorMessage "$result"
    } else {
        APSSetVarAndUpdate status "Waveform archiving completed."
    }
    APSEnableWidget $widget.acquire
    APSDisableWidget $widget.abort
   
}

proc ResetPlotOptions {} {
    global normalizeSignals hLimitLow hLimitHigh userOptions sameScales groupPlotsBy
    set groupPlotsBy Date
    set normalizeSignals 0
    set sameScales 0
    set hLimitLow 0
    set hLimitHigh 0
    set userOptions ""
}

ResetPlotOptions
proc MakePlotOptions {widget args} {
    set parent ""
    APSStrictParseArguments {parent}
    APSFrame $widget -parent $parent -label "Plot Options"

    set w $parent$widget.frame
    APSRadioButtonFrame .rb1 -parent $w -label "Normalize signals?: " \
      -variable normalizeSignals -orientation horizontal \
      -buttonList {No "Norm to 1" "Norm to Setpoint"} -valueList {0 1 Setpoint} -contextHelp \
      "Choose whether to normalize the signals or not.  Normalizing to 1 is sometimes useful if plotting several signals together.  Normalizing to setpoint refers to showing the waveform normalized to some pre-defined PV value, like the setpoint for a kicker."
    APSRadioButtonFrame .rb2 -parent $w -label "Same scales: " \
      -variable sameScales -orientation horizontal \
      -buttonList {Yes No} -valueList {1 0} -contextHelp \
      "Choose whether to use the same scales for all plots in a series.  The default is autoscaling for each plot."
    APSRadioButtonFrame .rb3 -parent $w -label "Group by: " \
      -variable groupPlotsBy -orientation horizontal \
      -buttonList {Date Signal} -valueList {Date Signal} -contextHelp \
      "Choose whether to use the same scales for all plots in a series.  The default is autoscaling for each plot."
    APSLabeledEntryFrame .lef1 -parent $w -label "Horizontal plot limits: " \
      -variableList {hLimitLow hLimitHigh} -width 8 -orientation horizontal \
      -contextHelp "Optionally enter the lower and upper horizontal limits for the plot. If the numbers are the same, they are ignored."
    APSLabeledEntry .le1 -parent $w -label "sddsplot args: " \
      -textVariable userOptions -width 60 -contextHelp \
      "Optionally enter commandline arguments for sddsplot."
    global includeReference
    APSRadioButtonFrame .ref -parent $w -label "Include reference waveform:" -packOption "-side top" \
      -variable includeReference -buttonList {Yes No} -valueList {1 0} -orientation horizontal \
      -contextHelp "if Yes is selected, the reference waveform will also be plotted for comparison." \
      -commandList {"IncludeReferenceSelection" ""}
    APSButton .b1 -parent $w -text "Reset" \
      -command "ResetPlotOptions" -contextHelp \
      "Resets the plot options to the default values."
   
}

proc CheckReference {args} {
    set waveform ""
    APSParseArguments {waveform}
    global dataDir waveformList directoryList
    set index [lsearch $waveformList $waveform]
    set dirname [lindex $directoryList $index]
    if [file exist $dataDir/$dirname/${waveform}.ref.gz] {
        set reference [APSResolveLink $dataDir/$dirname/${waveform}.ref.gz]
    } elseif [file exist $dataDir/$dirname/${waveform}.ref] {
        set reference [APSResolveLink $dataDir/$dirname/${waveform}.ref]
    } else {
        return -code error "Error: No reference is made for $waveform"
    }
    return $reference
}

set includeReference 0
MakeGroupSelectionWidget .group -parent .userFrame
MakeReviewFrame .review -parent .userFrame
MakePlotOptions .plotOptions -parent .userFrame
MakeArchiveFrame .archive -parent .userFrame
set status Ready
