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

# $Log: not supported by cvs2svn $
# Revision 1.4  2002/03/07 01:50:44  soliday
# Made some minor improvements.
#
# Revision 1.3  2002/03/05 20:02:01  soliday
# Modified the scroll region.
#
# Revision 1.2  2002/01/24 22:18:01  soliday
# Fixed filter problem
#
# Revision 1.1  2002/01/24 21:54:54  soliday
# 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.5 $ \$Author: soliday $"

proc ScrollAdjust {} {
    global runRow u
    set rows 0
    for {set i 0} {$i <= $runRow} {incr i} {
        if {[winfo exists $u.remove$i]} {
            incr rows
        }
    }
    .userFrame.f3.scrollWin.frame.canvas config -scrollregion "0 0 1000 [expr 30 * ($rows)]"
}

proc RemoveRun {args} {
    APSStrictParseArguments {row}
    global u
    destroy $u.remove$row
    destroy $u.station$row
    destroy $u.density$row
    destroy $u.firstFile$row
    destroy $u.lastFile$row
    ScrollAdjust
}

proc FindFile {args} {
    set row 0
    set type first
    set vld 0
    APSStrictParseArguments {row type vld}
    global time firstFile lastFile
    set name [APSFileSelectDialog .findDialog -checkValidity 1 -pattern {*.hdf} -path [file join /home/helios/IDGROUP1/daily [string range $time(year) [expr [string length $time(year)] - 2] end]$time(month) $time(day) data/hdf/VLD${vld}]]
    if {[llength $name]} {
	if {$type == "first"} {
	    set firstFile($row) [file tail $name]
	} else {
	    set lastFile($row) [file tail $name]
	}
    }
}

set runRow 0
proc AddRun {args} {
    global u runColumn runRow
    set vld 0
    APSStrictParseArguments {vld}

    APSButton .remove$runRow -parent $u -text "Remove" \
	-command "RemoveRun -row $runRow" \
	-contextHelp "Delete corrisponding sub-window" \
	-size small \
	-gridPack "-column 0 -row $runRow"

    grid [label $u.station$runRow \
	      -text "$vld" \
	      -bg grey \
	      -width 8] -column 1 -row $runRow

    global density firstFile lastFile
    set density($runRow) 0.0
    APSLabeledEntry .density$runRow \
	-parent $u \
	-textVariable density($runRow) \
	-width 20 \
	-label "" \
	-type real \
	-gridPack "-column 2 -row $runRow"

    set firstFile($runRow) "VLD${vld}_0000000001.hdf"
    APSLabeledEntry .firstFile$runRow \
	-parent $u \
	-textVariable firstFile($runRow) \
	-width 20 \
	-label "" \
	-gridPack "-column 3 -row $runRow"

    pack [button $u.firstFile$runRow.findfirst$runRow -text "F" -command "FindFile -row $runRow -type first -vld $vld"] -side right
    pack forget $u.firstFile$runRow.entry
    pack $u.firstFile$runRow.entry -side left

    set lastFile($runRow) "VLD${vld}_0000000100.hdf"
    APSLabeledEntry .lastFile$runRow \
	-parent $u \
	-textVariable lastFile($runRow) \
	-width 20 \
	-label "" \
	-gridPack "-column 4 -row $runRow"

    pack [button $u.lastFile$runRow.findlast$runRow -text "F" -command "FindFile -row $runRow -type last -vld $vld"] -side right
    pack forget $u.lastFile$runRow.entry
    pack $u.lastFile$runRow.entry -side left

    incr runRow
    ScrollAdjust
    APSSetVarAndUpdate status "Added station $vld"
}

proc RefreshPVs {args} {
    for {set filter 1} {$filter <= 3} {incr filter} {
	for {set vld 9} {$vld >= 0} {incr vld -1} {
	    if {(($filter == 3) && ($vld <= 3))} {
		continue
	    }
	    global fel choices${vld}${filter}
	    pv getw fel(${vld}${filter}) FEL:filt${vld}[expr ($filter + 2)]
	    set choices [lindex [join [pv info fel(${vld}${filter}) choices]] 1]
	    set i 0
	    foreach choice $choices {
		if {$choice == [set fel(${vld}${filter})]} {
                    set choices${vld}${filter} $choice
		    break
		}
		incr i
	    }
	    
	}
    }
    APSSetVarAndUpdate status "Refreshed PVs"    
}

proc SetOutputFile {args} {
    global outputFile
    set name [APSFileSelectDialog .saveDialog -checkValidity 0 -path /home/helios/IDGROUP1/gainLog -pattern {*.sdds}]
    if {[llength $name]} {
	set outputFile $name
    }
}

proc WriteOutputFile {args} {
    global outputFile data
    if {![llength $outputFile]} {
	APSSetVarAndUpdate status "error: No output file given"
	bell
	return
    }
    catch {unset data}
    set data(ParameterNames) "Station F1 F2 F3 ND"
    set data(ParameterInfo.ND) "type SDDS_DOUBLE"
    set data(ColumnNames) "fileName"
    
    global runRow u density time lastFile firstFile

    set directory [file join /home/helios/IDGROUP1/daily [string range $time(year) [expr [string length $time(year)] - 2] end]$time(month) $time(day) data/hdf]

    for {set i 0} {$i <= $runRow} {incr i} {
        if {[winfo exists $u.remove$i]} {
	    set vld [$u.station$i cget -text]
	    lappend data(Parameter.Station) $vld

	    lappend data(Parameter.F1) [.userFrame.f1.cb${vld}1 get]
	    lappend data(Parameter.F2) [.userFrame.f1.cb${vld}2 get]
	    if {($vld <= 3)} {
		lappend data(Parameter.F3) absent
	    } else {
		lappend data(Parameter.F3) [.userFrame.f1.cb${vld}3 get]
	    }
	    lappend data(Parameter.ND) $density($i)
	    
	    set n 0
	    set lastIndex [set firstIndex -1]
	    for {set k [expr ([string length $firstFile($i)] - 1)]} {$k >= 0} {incr k -1} {
		if {$n == 0} {
		    if {[string is integer -strict [string range $firstFile($i) $k $k]]} {
			set lastIndex $k
			set n 1
		    }
		} elseif {$n == 1} {
		    if {![string is integer -strict [string range $firstFile($i) $k $k]]} {
			set firstIndex [expr ($k + 1)]
			break
		    }
		}
	    }
	    set numbers [string range $firstFile($i) $firstIndex $lastIndex]
	    set len [string length $numbers]
	    set numbers [string trimleft $numbers 0]
	    if {[string length $numbers] == 0} {
		set numbers 0
	    }
	    
	    set files ""
	    while 1 {
		set filename [string replace $firstFile($i) $firstIndex $lastIndex [format "%0${len}s" $numbers]]
		incr numbers

#		if {![file exists [file join $directory VLD${vld} $filename]]} {
#		    APSSetVarAndUpdate status "error: $filename does not exist"
#		    bell
#		    return
#		}
		lappend files [file join $directory VLD${vld} $filename]
		if {$filename == $lastFile($i)} {
		    break
		}
	    }
	    lappend data(Column.fileName) $files
        }
    }
    if {[catch {sdds save $outputFile data} results]} {
	APSSetVarAndUpdate status "error: $results"
	bell
	return
    }
    APSSetVarAndUpdate status "File written"    
}

proc CreateWidgets {args} {
    global CVSRevisionAuthor status
    APSApplication . -name idGroupVLDInfo -version $CVSRevisionAuthor

    set status "Ready..."
    APSScrolledStatus .status \
	-parent .userFrame \
	-textVariable status \
	-packOption "-fill x" \
	-withButtons 1

    pack [frame .userFrame.f1 -relief ridge -borderwidth 2] -fill x
    set w .userFrame.f1
    set row -1
    for {set filter 1} {$filter <= 3} {incr filter} {
	incr row
	set col 0
	grid [label $w.filter$filter -text "F$filter"] -column $col -row [expr ($row * 2 + 1)]
	for {set vld 9} {$vld >= 0} {incr vld -1} {
	    incr col
	    if {(($filter == 3) && ($vld <= 3))} {
		continue
	    }
	    global fel
	    pv linkw fel(${vld}${filter}) FEL:filt${vld}[expr ($filter + 2)]
	    
	    entry $w.e${vld}${filter} \
		-textvariable fel(${vld}${filter}) \
		-state disabled \
		-width 12 \
		-justify center \
		-relief flat \
		-bg brown \
		-fg green \
		-font {-adobe-courier-medium-r-normal-*-10-*-*-*-*-*-*-*}
	    
	    grid $w.e${vld}${filter} -column $col -row [expr ($row * 2)]
            set choices [lindex [join [pv info fel(${vld}${filter}) choices]] 1]
            global choices${vld}${filter}
            eval tk_optionMenu $w.cb${vld}${filter} choices${vld}${filter} $choices
	    grid $w.cb${vld}${filter} -column $col -row [expr ($row * 2 + 1)]
	    
	    set i 0
	    foreach choice $choices {
		if {$choice == [set fel(${vld}${filter})]} {
                    set choices${vld}${filter} $choice
		    break
		}
		incr i
	    }
	}
    }

    APSButton .refresh \
	-parent $w \
	-text Refresh \
	-gridPack "-column 8 -row 4 -columnspan 2 -rowspan 2 -sticky ew" \
	-command RefreshPVs

    set col 1
    for {set vld 9} {$vld >= 0} {incr vld -1} {
	APSButton .vld$vld \
	    -parent $w \
	    -text "Add D$vld" \
	    -gridPack "-column $col -row 6" \
	    -command "AddRun -vld $vld"
	
	incr col
    }

    pack [frame .userFrame.f2 -relief ridge -borderwidth 2]
    global time
    set time(day) [clock format [clock seconds] -format "%d"]
    set time(month) [clock format [clock seconds] -format "%m"]
    set time(year) [clock format [clock seconds] -format "%Y"]
    APSLabeledEntry .day \
	-parent .userFrame.f2 \
	-textVariable time(day) \
	-width 6 \
	-label "Day:" \
	-type integer \
	-gridPack "-column 0 -row 0"
    APSLabeledEntry .month \
	-parent .userFrame.f2 \
	-textVariable time(month) \
	-width 6 \
	-label "   Month:" \
	-type integer \
	-gridPack "-column 1 -row 0"
    APSLabeledEntry .year \
	-parent .userFrame.f2 \
	-textVariable time(year) \
	-width 6 \
	-label "   Year:" \
	-type integer \
	-gridPack "-column 2 -row 0 -sticky w"
    grid columnconfigure .userFrame.f2 2 -weight 1

    pack [frame .userFrame.f3 -relief ridge -borderwidth 2] -fill both -expand true
    pack [frame .userFrame.f3.labelFrame] -fill x
    pack [label .userFrame.f3.labelFrame.station -text "      Station"] -side left
    pack [label .userFrame.f3.labelFrame.density -text "    Neutral Density"] -side left
    pack [label .userFrame.f3.labelFrame.firstfilename -text "       First Filename"] -side left
    pack [label .userFrame.f3.labelFrame.lastfilename -text "       Last Filename"] -side left

    APSScroll .scrollWin -parent .userFrame.f3 -name "" -packOption "-fill both -expand true"
    .userFrame.f3.scrollWin.frame.canvas config -yscrollincrement 30
    pack configure .userFrame.f3.scrollWin.frame.canvas -fill both -expand true
    global u
    set u .userFrame.f3.scrollWin.frame.canvas.frame
    .userFrame.f3.scrollWin.frame.canvas configure -height 2i

    pack [frame .userFrame.outputFrame] -fill x
    label .userFrame.outputFrame.label -text "Output Filename"
    global outputFile
    set outputFile "/home/helios/IDGROUP1/gainLog/leutl_dataset_001_${time(year)}_${time(month)}_${time(day)}.sdds"
    entry .userFrame.outputFrame.entry -relief sunken -textvariable outputFile
    grid .userFrame.outputFrame.label -column 0 -row 0 -sticky e
    grid .userFrame.outputFrame.entry -column 1 -row 0 -sticky ew
    APSButton .file \
	-parent .userFrame.outputFrame \
	-text "F" \
	-gridPack "-column 2 -row 0" \
	-command SetOutputFile 
    grid columnconfigure .userFrame.outputFrame 1 -weight 1

    APSButton .write \
	-parent .userFrame \
	-text "Write Output File" \
	-command "WriteOutputFile"
}

CreateWidgets
