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

#
# $Log: not supported by cvs2svn $
# Revision 1.23  2008/03/27 18:56:33  borland
# Added radio button for controlling file overwrites.
#
# Revision 1.22  2007/10/09 15:12:27  shang
# fixed the bug that it could not export other files from GUI except the first one.
#
# Revision 1.21  2006/10/17 20:27:45  shang
# added TimeText column in EXCEL date format for converting to CVS file and fixed the bug
# in "SCAN FILE".
#
# Revision 1.20  2005/08/23 20:18:53  soliday
# Added APSRenameExecToAPSBGExec.
#
# Revision 1.19  2004/12/16 23:16:14  soliday
# Added the -fileSelectValidity 0 option to the output file entry box.
#
# Revision 1.18  2004/08/06 20:26:20  borland
# Now uses command button for filename entry widget.  Added selectAllButton and
# clearButton options to scrolled list of column names.
#
# Revision 1.17  2004/07/30 18:49:05  borland
# Added command and file select buttons to the output filename entry box.
#
# Revision 1.16  2004/01/03 18:05:55  borland
# Now turns off the time filter if there is no time filter data supplied
# from the commandline.
#
# Revision 1.15  2004/01/03 18:02:13  borland
# Added updated CSV output style as an option.
#
# Revision 1.14  2000/11/08 22:59:10  borland
# Added -timeFilter option so that the default value for the time filter
# on/off mode can be set by invoking process.
#
# Revision 1.13  2000/10/11 21:12:22  borland
# Removed code that resulted in deletion of CSV output.  Duh.
#
# Revision 1.12  2000/03/28 21:36:39  emery
# Indented lines.
#
# Revision 1.11  1999/05/05 13:35:47  borland
# Added emailing of data rather than export to file.
# Added sparsing of data.
#
# Revision 1.10  1998/07/20 21:24:27  borland
# Per D. Blachowicz: when MonitorDataReview passes time limits to
# quickSDDSplot and sddsExportData, it now adds an extra argument
# to tell these tools that they can allow the user to expand the
# time lmits to the day boundaries.
#
# Revision 1.9  1998/05/28 15:52:55  borland
# Changes by D. Blachowicz for time-filter mode:
# 1. Does not allow the user to expand the time range beyond the
# limits provided by the parent.
# 2. Requires that the start time preceed the end time.
#
# Revision 1.8  1998/05/27 19:42:31  borland
# New version per D. Blachowicz.  Now compares the user's time filter
# to those passed by the calling program.  If the user's filter is
# outside the range of provided by the calling program, an error message
# is displayed.
#
# Revision 1.7  1998/04/16 16:54:43  borland
# Improved speed by using column deletion in sddscombine step.
#
# Revision 1.6  1997/09/18 22:05:39  borland
# Further fixes to the way the path and filenames are handled.
#
# Revision 1.5  1997/09/18 20:26:08  borland
# Fixed problem with the way the data directory is handled.  Don't know
# how it ever worked, but it did.
#
# Revision 1.4  1997/07/25 15:56:41  borland
# Modified plain spreadsheet output; now uses proper format strings for
# different types of data.
#
# Revision 1.3  1997/04/23 22:12:24  borland
# Added warning if user exports without choosing any columns.
#
# Revision 1.2  1997/04/02 14:37:35  borland
# Modifies input data filename list to prepend directory name to all
# filenames.  Obviates need to change directories.
#
# Revision 1.1  1997/04/02 02:09:13  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)]
set apsttk 1
#APSDebugPath
APSRenameExecToAPSBGExec

set CVSRevisionAuthor "\$Revision: 1.24 $ \$Author: borland $"

set chosenColumns ""
set dataFileList ""
set dataFilename ""
set excludeFilter ""
set includeFilter *
set outputFile ""
set outputType SDDS
set pickFileDir ""
set sparsingFactor 1
set overwrite -1

proc MakeInputFileFrame {widget args} {
    set parent ""
    set pickFileMode 0
    APSStrictParseArguments {parent pickFileMode}

    APSFrame $widget -parent $parent -label "Input File Operations" -packOption "-fill x"
    set w $parent$widget.frame

    grid [ttk::label $w.l1 -text "Include Columns:"] -row 1 -column 1 -sticky e
    APSLabeledEntry .include -parent $w -label "" \
      -width 83 -textVariable includeFilter -contextHelp \
      "Give one or more comma-separated wildcard strings for the columns to be included in the selection list when you scan the file(s)." -gridPack "-row 1 -column 2 -sticky w"
    
    grid [ttk::label $w.l2 -text "Exclude Columns:"] -row 2 -column 1 -sticky e
    APSLabeledEntry .exclude -parent $w -label "" \
      -width 83 -textVariable excludeFilter -contextHelp \
      "Give one or more comma-separated wildcard strings for the columns to be excluded in the selection list when you scan the file(s)." -gridPack "-row 2 -column 2 -sticky w"

    if $pickFileMode {
        grid [ttk::label $w.l3 -text "File:"] -row 3 -column 1 -sticky e
        APSLabeledEntry .file -parent $w -textVariable dataFilename -width 83 -label "" \
          -contextHelp "Holds the name of the file from which data will be taken.  You may enter the filename by typing or the combo box button." \
          -commandButton 1 -gridPack "-row 3 -column 2 -sticky w"
        APSButton .scan -parent $w -text "SCAN FILE" -command "ScanFile all" \
          -contextHelp "Scans the file to make lists of plottable quantities. If you change the name filters below, press this button to bring up new name selection widgets." -width "" -gridPack "-row 4 -column 1 -sticky w -columnspan 2"
    } else {
        grid [ttk::frame $w.b] -row 3 -column 1 -sticky w -columnspan 2
        APSButton .scan -parent $w.b -text "SCAN FILE(s)" -command "ScanFile all" \
          -contextHelp "Scans the file(s) to make lists of plottable quantities.  If you change the name filters below, press this button to bring up new name selection widgets." -width ""
        APSButton .fscan -parent $w.b -text "FAST SCAN" -command "ScanFile fast" \
          -contextHelp "Like SCAN FILE(s), but only scans the first and last file.  Much faster for larger numbers of files, but may miss data names in some files." -width ""
    }

}

set outputType SDDS
proc MakeOutputFrame {widget args} {
    set parent ""
    APSParseArguments {parent}

    global outputType outputFile
    global hourStart dayStart monthStart yearStart
    global hourEnd dayEnd monthEnd yearEnd doTimeFilter

    APSFrame $widget -parent $parent -label "Output File Operations"
    set w $parent$widget.frame

    if !$doTimeFilter {
        #  set some defaults for time filter should it be selected.
        set hourStart 0
        set hourEnd 24
        APSDateBreakDown -dayVariable dayStart -monthVariable monthStart \
          -yearVariable yearStart -twoDigitYear 0 -leadingZeros 0
        APSDateBreakDown -dayVariable dayEnd -monthVariable monthEnd \
          -yearVariable yearEnd -twoDigitYear 0 -leadingZeros 0
    }
    

    grid [ttk::label $w.l1 -text "Time filter:"] -row 1 -column 1 -sticky e
    APSRadioButtonFrame .filter -parent $w -orientation horizontal \
      -variable doTimeFilter -label "" \
      -buttonList "Yes No" -valueList "1 0" -contextHelp \
      "Choose whether to apply an time filter to the data or not." -gridPack "-row 1 -column 2 -sticky w"
    grid [ttk::label $w.l2 -text "Start (Y/M/D/H):"] -row 2 -column 1 -sticky e
    APSLabeledEntryFrame .start -parent $w -label "" \
      -contextHelp "Enter the start time in year, month, day, and hour for time filtering." \
      -variableList {yearStart monthStart dayStart hourStart} \
      -orientation horizontal -width 5 -packOption "-side top -anchor w" -gridPack "-row 2 -column 2 -sticky w"
    grid [ttk::label $w.l3 -text "End (Y/M/D/H):"] -row 3 -column 1 -sticky e
    APSLabeledEntryFrame .end   -parent $w -label "" \
      -contextHelp "Enter the end time in year, month, day, and hour for time filtering." \
      -variableList {yearEnd monthEnd dayEnd hourEnd} \
      -orientation horizontal -width 5 -packOption "-side top -anchor w" -gridPack "-row 3 -column 2 -sticky w"
    grid [ttk::label $w.l4 -text "Sparsing:"] -row 4 -column 1 -sticky e
    APSRadioButtonFrame .sparse -parent $w -orientation horizontal \
      -variable sparsingFactor -label "" \
      -buttonList {1 2 4 8 16 32 100 1000} -valueList {1 2 4 8 16 32 100 1000} -contextHelp \
      "Choose whether to sparse the data and by what factor.  Sparsing allows elimination of data to make smaller data sets." -gridPack "-row 4 -column 2 -sticky w"

    grid [ttk::label $w.l5 -text "Output Type:"] -row 5 -column 1 -sticky e
    APSRadioButtonFrame .type -parent $w -label "" \
      -variable outputType -orientation horizontal \
      -buttonList {SDDS Text "Plain spreadsheet" "CSV spreadsheet" "Old-style CSV"} \
      -valueList {SDDS Text Plain CSV CSVOld} \
      -contextHelp "Allows specifying what type of output is desired. Plain spreadsheet data is \
ascii text with tab-separated data.  CSV spreadsheet data is comma-separated-values format data, \
which consists of two files; one file gives the data, the other gives the header.  Old-style CSV \
is an obsolete format that includes the SCH header file." -gridPack "-row 5 -column 2 -sticky w"

    grid [ttk::label $w.l6 -text "Overwrite file if exists?"] -row 6 -column 1 -sticky e
    APSRadioButtonFrame .overwrite -parent $w -label "" \
      -variable overwrite -orientation horizontal \
      -buttonList {Yes No Ask} \
      -valueList {1 0 -1} \
      -contextHelp "Allows specifying behavior if the output file already exists." -gridPack "-row 6 -column 2 -sticky w"
    grid [ttk::label $w.l7 -text "Filename or email address:"] -row 7 -column 1 -sticky e
    APSLabeledEntry .filename -parent $w -label "" \
      -textVariable outputFile -width 75 \
      -commandButton 1 -fileSelectButton 1 -fileSelectValidity 0 \
      -contextHelp \
      "Enter the name of the file in which to place the data, or the email address to which to send it." -gridPack "-row 7 -column 2 -sticky w"

    grid [ttk::frame $w.b] -row 8 -column 1 -sticky w -columnspan 2
    APSButton .export -parent $w.b -text "Export" -command ExportData \
      -contextHelp "Exports the chosen data to the output file." -width ""
    APSButton .email -parent $w.b -text "Email" -command "ExportData -email 1" \
      -contextHelp "Exports the chosen data to the output file." -width ""
}

proc TimeFilterControl {} {
    global hourStart dayStart monthStart yearStart
    global hourEnd dayEnd monthEnd yearEnd doTimeFilter
    global inithourStart initdayStart initmonthStart inityearStart
    global inithourEnd initdayEnd initmonthEnd inityearEnd
    global time0 time1 timeFilterMode
    
    if {[catch {APSConvertTimeToHours $hourStart} hour0] || \
          [catch {APSConvertTimeToHours $hourEnd} hour1]} {
        return -code error "Bad hour syntax in time filter"
    }
    if {[catch {APSConvertTimeToHours $inithourStart} inithour0] || \
          [catch {APSConvertTimeToHours $inithourEnd} inithour1]} {
        return -code error "Bad hour syntax in initial time filter"
    }
    if {[catch {exec timeconvert \
                  -breakDown=year=$yearStart,month=$monthStart,day=$dayStart,hour=$hour0} \
           time0] || \
          [catch {exec timeconvert \
                    -breakDown=year=$yearEnd,month=$monthEnd,day=$dayEnd,hour=$hour1} \
             time1]} {
        return -code error "Error in time syntax for time filter"
    }
    if {[catch {exec timeconvert \
                  -breakDown=year=$inityearStart,month=$initmonthStart,day=$initdayStart,hour=0} \
           modeTime0] || \
          [catch {exec timeconvert \
                    -breakDown=year=$inityearEnd,month=$initmonthEnd,day=$initdayEnd,hour=24} \
             modeTime1]} {
        return -code error "Error in time syntax for time filter"
    }
    if {[catch {exec timeconvert \
                  -breakDown=year=$inityearStart,month=$initmonthStart,day=$initdayStart,hour=$inithour0} \
           inittime0] || \
          [catch {exec timeconvert \
                    -breakDown=year=$inityearEnd,month=$initmonthEnd,day=$initdayEnd,hour=$inithour1} \
             inittime1]} {
        return -code error "Error in time syntax for initial time filter"
    }
    if {$time0 < $inittime0 || $time1 > $inittime1} {
        if ![string compare $timeFilterMode exact] {
            set hourStart $inithourStart
            set dayStart $initdayStart
            set monthStart $initmonthStart
            set yearStart $inityearStart
            set hourEnd $inithourEnd
            set dayEnd $initdayEnd
            set monthEnd $initmonthEnd
            set yearEnd $inityearEnd
            update
            return -code error "Error: Time filter range disagrees with the time range allowed for the transferred sdds files. Input has been reset to initial values."
        } elseif ![string compare $timeFilterMode day] {
            if {$time0 < $modeTime0 || $time1 > $modeTime1} {
                set hourStart $inithourStart
                set dayStart $initdayStart
                set monthStart $initmonthStart
                set yearStart $inityearStart
                set hourEnd $inithourEnd
                set dayEnd $initdayEnd
                set monthEnd $initmonthEnd
                set yearEnd $inityearEnd
                update
                return -code error "Error: Time filter range disagrees with the time range allowed for the transferred sdds files. Input has been reset to initial values."
            }
        } else {
            return -code error "Error: invalid option for -timeFilterMode" 
        }
    } elseif {$time0 >= $time1} {
        return -code error "Error: Start Time must be earlier than End Time. Please, correct this error."
    } else {
        return -code ok
    }
}

proc ExportData {args} {
    set email 0
    APSStrictParseArguments {email}

    global dataFileList chosenColumns
    global outputType outputFile 
    global doTimeFilter time0 time1 sparsingFactor dataFilename hasInput

    if {!$hasInput && [file isfile $dataFilename]} {
        set dataFileList $dataFilename
    
    }
    if {![llength $dataFileList]} {
        APSSetVarAndUpdate status "No input file(s) chosen."
        return
    }

    if ![string length $outputFile] {
        APSSetVarAndUpdate status "Give an output filename or email address."
        return
    }
    if ![llength $chosenColumns] {
        APSSetVarAndUpdate status "Warning: no columns were chosen for export."
    }

    set localOutputFile $outputFile
    if $email {
        set localOutputFile [APSTmpDir]/[APSTmpString]
        set emailAddress $outputFile
        APSAddToTempFileList $localOutputFile
    }

    if {[string compare $outputType CSV]} {
        if {[file exists $localOutputFile] && \
            ![AllowOverwrite -message "$localOutputFile exists. Overwrite it?"]} {
            APSSetVarAndUpdate status "Give a different output filename."
            return
        }
    } else {
        if {([file exists $localOutputFile.csv] || [file exists $localOutputFile.sch]) && \
            ![AllowOverwrite -message "$localOutputFile.csv and/or $localOutputFile.sch exists. Overwrite it?"]} {
            APSSetVarAndUpdate status "Give a different output filename."
            return
        }
    }

    if {$doTimeFilter} {
        if [catch {TimeFilterControl} result] {
            APSAlertBox [APSUniqueName .] -errorMessage $result
            return
        }
        set dataFile [APSTmpDir]/[APSTmpString]
        APSAddToTempFileList $dataFile
        if [catch {eval exec sddscombine -merge $dataFileList -pipe=out \
                     -retain=column,[join $chosenColumns ,],Time \
                     | sddsprocess -sparse=$sparsingFactor \
                     -pipe=in $dataFile -filter=column,Time,$time0,$time1} result] {
            APSSetVarAndUpdate status "$result"
            return
        }
    } elseif {$sparsingFactor==1} {
        set dataFile [APSTmpDir]/[APSTmpString]
        if [catch  {eval exec sddscombine -merge \
                      -retain=column,[join $chosenColumns ,] \
                      $dataFileList $dataFile} result] {
            APSSetVarAndUpdate status "$result"
            return
        }
        APSAddToTempFileList $dataFile
    } else {
        set dataFile [APSTmpDir]/[APSTmpString]
        if [catch  {eval exec sddscombine -merge \
                      -retain=column,[join $chosenColumns ,] \
                      $dataFileList -pipe=out \
                      | sddsprocess -pipe=in -sparse=$sparsingFactor $dataFile} result] {
            APSSetVarAndUpdate status "$result"
            return
        }
        APSAddToTempFileList $dataFile
    }

    switch $outputType {
        SDDS {
            if [catch {exec cp $dataFile $localOutputFile} result] {
                APSSetVarAndUpdate status "$result"
                return
            }
        }
        Text {
            if [catch {exec sddsprintout $dataFile -column -parameter $localOutputFile} result] {
                APSSetVarAndUpdate status "$result"
                return
            }
        }
        Plain {
            if [catch {exec sddsprintout -nowarnings $dataFile \
                         -format=float=%.15e,double=%.8e,short=%hd,long=%ld,string=%s,character=%c \
                         -column -parameter -spreadsheet=delimiter=\t $localOutputFile} result] {
                APSSetVarAndUpdate status "$result"
                return
            }
        }
        CSVOld {
            set columns [exec sddsquery -col $dataFile]
            if [lsearch $columns Time]>=0 {
                if [catch {exec sddstimeconvert $dataFile -pipe=out \
                               -break=col,Time,year=Year,month=Month,day=Day,text=TimeText1 \
                               | sddsprocess -pipe -reedit=col,TimeText1,11d \
                               | sddsprocess -pipe "-print=col,TimeText,%d/%d/%d %s,Month,Day,Year,TimeText1" \
                               | sddsconvert -pipe -dele=col,TimeText1,Year,Month,Day \
                               | sddsprintout -pipe=in -collumn=TimeText -column  -notitle -nowarnings \
                               -formatDefaults=double=%.15e,float=%.8e,long=%ld,short=%hd,string=%s,character=%c \
                               -spreadsheet=delimiter=\\,,quotemark=\",nolabels,schfile=$localOutputFile.sch \
                               $localOutputFile.csv} result] {
                    APSSetVarAndUpdate status "$result"
                    return
                }
            } else {
                if [catch {exec sddsprintout $dataFile -column  -notitle -nowarnings \
                               -formatDefaults=double=%.15e,float=%.8e,long=%ld,short=%hd,string=%s,character=%c \
                               -spreadsheet=delimiter=\\,,quotemark=\",nolabels,schfile=$localOutputFile.sch \
                               $localOutputFile.csv} result] {
                    APSSetVarAndUpdate status "$result"
                    return
                }
            }
        }
        CSV {
            set columns [exec sddsquery -col $dataFile]
            if [lsearch $columns Time]>=0 {
                if [catch {exec sddstimeconvert $dataFile -pipe=out \
                               -break=col,Time,year=Year,month=Month,day=Day,text=TimeText1 \
                               | sddsprocess -pipe -reedit=col,TimeText1,11d \
                               | sddsprocess -pipe "-print=col,TimeText,%d/%d/%d %s,Month,Day,Year,TimeText1" \
                               | sddsconvert -pipe -dele=col,TimeText1,Year,Month,Day \
                               | sddsprintout -pipe=in -column=TimeText -column  -notitle -nowarnings \
                               -formatDefaults=double=%.15e,float=%.8e,long=%ld,short=%hd,string=%s,character=%c \
                               -spreadsheet=csv $localOutputFile} result] {
                    APSSetVarAndUpdate status "$result"
                    return
                }
            } else {
                if [catch {exec sddsprintout $dataFile -column  -notitle -nowarnings \
                               -formatDefaults=double=%.15e,float=%.8e,long=%ld,short=%hd,string=%s,character=%c \
                               -spreadsheet=csv $localOutputFile} result] {
                    APSSetVarAndUpdate status "$result"
                    return
                }
            }
        }
    }
    if $email {
        switch $outputType {
            CSV {
                if [catch {exec /usr/ucb/mail -s "Exported data part 1" $emailAddress < $localOutputFile.csv
                    exec /usr/ucb/mail -s "Exported data part 2" $emailAddress < $localOutputFile.sch} result] {
                    APSSetVarAndUpdate status "$result"
                }
            }
            default {
                if [catch {exec /usr/ucb/mail -s "Exported data" $emailAddress < $localOutputFile} result] {
                    APSSetVarAndUpdate status "$result"
                }
            }
        }
    }
    APSSetVarAndUpdate status "[clock format [clock seconds] -format %H:%M:%S]: Data exported."
    APSDeleteTempFiles
}

proc ScanFile {mode} {
    global dataFileList includeFilter excludeFilter
    global pickFileMode dataFilename hasInput

    if {!$hasInput && [file isfile $dataFilename]} {
        set dataFileList $dataFilename
    }
    
    set fileCount [llength $dataFileList]
    if $fileCount==0 {
        APSSetVarAndUpdate status "Supply a filename"
        return
    }

    set dataFilename [lindex $dataFileList 0]
    if ![file exists $dataFilename] {
        APSSetVarAndUpdate status "$dataFilename does not exist."
        return
    }
    set pickFileDir [file dirname $dataFilename]

    set increment 1
    if [string compare $mode all] {
        set increment [expr $fileCount-1]
        if $increment<1 {
            set increment 1
        }
    }
    
    set tmpRoot [APSTmpDir]/[APSTmpString]
    set columnFileList ""
    for {set index 0} {$index<$fileCount} {incr index $increment} {
        APSSetVarAndUpdate status "Scanning [lindex $dataFileList $index]"
        APSAddToTempFileList $tmpRoot.$index
        if [catch {exec sddsquery [lindex $dataFileList $index] -column -sddsOutput=$tmpRoot.$index} \
              result] {
            APSSetVarAndUpdate status "Problem scanning [lindex $dataFileList $index]: $result"
            return
        }
        lappend columnFileList $tmpRoot.$index
    }
    
    APSAddToTempFileList $tmpRoot $tmpRoot.m
    APSSetVarAndUpdate status "Combining and sorting."
    if [catch {eval exec sddscombine $columnFileList -merge -pipe=out \
                 | sddssort -pipe=in $tmpRoot -column=Name -unique} result] {
        APSSetVarAndUpdate status "Problem making list of column names: $result"
        return
    }

    set matchCommand ""
    if ![string length $includeFilter] {
        set includeFilter *
    }
    set first 1
    set matchElement ""
    foreach elem [split $includeFilter ,] {
        if $first {
            set matchElement -match=column,Name=$elem
            set first 0
        } else {
            set matchElement $matchElement,Name=$elem,|
        }
    }
    lappend matchCommand $matchElement

    if [string length $excludeFilter] {
        set first 1
        set matchElement ""
        foreach elem [split $excludeFilter ,] {
            if $first {
                set matchElement "-match=column,Name=$elem"
                set first 0
            } else {
                set matchElement "$matchElement,Name=$elem,|"
            }
        }
        lappend matchCommand "$matchElement,!"
    }
    if [llength $matchCommand] {
        if [catch {eval exec sddsprocess $tmpRoot $tmpRoot.m \
                     $matchCommand} result] {
            APSSetVarAndUpdate status "Problem making list of column names: $result"
            return
        }
    }

    if [catch {APSGetSDDSColumn -fileName $tmpRoot.m -column Name} nameList] {
        APSSetVarAndUpdate status "Problem getting list of names: $nameList"
        return
    }

    set slw [APSUniqueName .]
    APSScrolledListWindow $slw \
      -itemList $nameList -name "Export Selection List" \
      -label "Export Selection List" -selectionVar chosenColumns \
      -callback dataSelectionCallback -selectAllButton 1 -clearButton 1
}

proc AcceptAllItems {args} {
    set selectionVar ""
    set itemList ""
    set widget ""
    APSStrictParseArguments {selectionVar itemList widget}
    destroy $widget
    global selectionVar 
    set $selectionVar $itemList
}

proc dataSelectionCallback {itemList} {
    global chosenColumns
    APSSetVarAndUpdate status "[llength $chosenColumns] items chosen for export."
}

proc AllowOverwrite {args} {
    set message "?"
    APSStrictParseArguments {message}
    global overwrite
    if $overwrite==1 {
        return 1
    }
    if $overwrite==0 {
        return 0
    }
    return [APSMultipleChoice [APSUniqueName .] -question "$message" -labelList "Yes No" -returnList "1 0"]
}

set apOverview "This is a utility for exporting data from SDDS data files.  It will list the available columns for you and let you pick which you want."


if [llength $argv] {
    set pickFileMode 0
    set apOverview "$apOverview This invocation has been made by another program, so the data files are preselected.  Use the SCAN FILE(s) button to get lists of choices of things to plot.  You may enter name filters prior to scanning to reduce the number of choices."
} else {
    set pickFileMode 1
    set apOverview "$apOverview To start, enter a filename and SCAN it, or use the PICK FILE... button."
}

APSApplication . -name sddsExportData -version $CVSRevisionAuthor \
  -overview "$apOverview"

set message1 ""
set message2 ""
set doTimeFilter 0
set timeFilterMode 0

set originalDir [pwd]
set saveFileDir $originalDir
set dataDirectory ""
set dataFileList {}
set autoTimeMode 0
set timeFilterStart ""
set timeFilterEnd ""
set timeFilter 1
set hasInput 1
if [llength $argv] {
    set args $argv
    set message ""
    APSStrictParseArguments {dataDirectory dataFileList autoTimeMode message timeFilterMode timeFilterStart timeFilterEnd timeFilter}
    if [llength $dataFileList]==0 {
        APSAlertBox [APSUniqueName .] -errorMessage "Fatal error: no filenames passed to sddsExportData by parent." 
        exit
    }
    if [string length $message] {
        set message1 $message
    }
    set message2 "[llength $dataFileList] data files passed by parent."
    if [string length $dataDirectory] {
        foreach dataFile $dataFileList {
            if [string compare [file dirname $dataFile] .]==0  {
                lappend dataFileList0 $dataDirectory/$dataFile
            } else {
                lappend dataFileList0 $dataFile
            }
        }
        set dataFileList $dataFileList0
    }
    if {[llength $timeFilterStart]==4 && [llength $timeFilterEnd]==4} {
        set doTimeFilter 1
        set index 0
        foreach elem {year month day hour} {
            set ${elem}Start [lindex $timeFilterStart $index]
            set init${elem}Start [lindex $timeFilterStart $index]
            set ${elem}End [lindex $timeFilterEnd $index]
            set init${elem}End [lindex $timeFilterEnd $index]
            incr index
        }
    }
} else {
    set message1 Ready.
}
if ![llength $dataFileList] {
    set hasInput 0
    #if not from input, then export sdds from input with dataFilename
}

if {![string length timeFilterStart] || ![string length $timeFilterEnd]} {
    set timeFilter 0
}
set doTimeFilter $timeFilter

set status "$message1"
APSScrolledStatus .status -parent .userFrame -textVariable status -width 75 -packOption "-fill both -expand true"
if [string length $message2] {
    set status "$message2"
}

MakeInputFileFrame .input -parent .userFrame -pickFileMode $pickFileMode
MakeOutputFrame .output -parent .userFrame

