#!/usr/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
set CVSRevisionAuthor "\$Author: borland $"

APSApplication . -name ImageReviewer \
  -overview "A GUI for reviewing SDDS image files from the control system."

set status ""
APSScrolledStatus .status -parent .userFrame -textVariable status -height 3 -width 60

proc setStatus {text} {
    APSSetVarAndUpdate status $text
}

proc PickInputFile {args} {
    set lastFile ""
    APSStrictParseArguments {lastFile}
    if [string length $lastFile] {
        set directory [file dir $lastFile]
    } else {
        set directory [pwd]
    }
    set fileName [APSFileSelectDialog [APSUniqueName .] -path $directory -width 40 ]
    if {[catch {exec sddsquery -column $fileName} columnList] || \
          [lsearch -exact $columnList Index]==-1 || \
          [lsearch -exact $columnList VLineName]==-1} {
        setStatus "Invalid file."
        bell
        return $lastFile
    }
    set count 0
    for {set i 0} {$i<484} {incr i} {
        if [lsearch -exact $columnList [format HLine%03ld $i]]==-1 {
            continue
        }
        incr count
    }
    if $count<2 {
        setStatus "Invalid file (too few lines)"
        bell
        return $lastFile
    }
    setStatus "$fileName is a valid image file."
    return $fileName
}

proc ContourPlot {args} {
    set fileName ""
    set yLow 0
    set yHigh 0
    set xLow 0 
    set xHigh 511
    set shades 20
    APSStrictParseArguments {fileName yLow yHigh xLow xHigh shades}

    if ![string length $fileName] {
        setStatus "pick a file"
        return
    }
    if ![file exists $fileName] {
        setStatus "not found: $fileName"
        return
    }
    set availableColumns [APSGetSDDSNames  -fileName $fileName -class column]
    if [expr $shades<10] {
        set shades 10
    }
    set nColumns 0
    if {[expr $yLow<$yHigh]} {
        set columnList ""
        for {set y [expr int($yLow)]} {$y<=$yHigh} {incr y} {
            set name [format HLine%03ld $y]
            if [lsearch -exact $availableColumns $name]==-1 continue
            lappend columnList $name
            incr nColumns
        }
    } else {
        set columnList HLine*
        set nColumns [llength $availableColumns]
    }
    set ySample [expr int($nColumns/20)]
    exec sddscontour -shade=$shades $fileName -column=Index,[join $columnList ,] \
      -scales=$xLow,$xHigh,0,0 -ystrings=edit=%/HLine//,sparse=$ySample -title= -topline=$fileName &
}


proc MakeFileEntryFrame {widget} {
    global inputFile
    set inputFile ""
    APSFrame .input -parent .userFrame -label "Input"
    set w .userFrame.input.frame
    APSLabeledEntry .input -parent $w -width 65 -textVariable inputFile  \
      -label "File: " -contextHelp "Enter or pick an input file."
    APSButton .pick -parent $w -text "Pick file..." \
      -command {set inputFile [PickInputFile -lastFile $inputFile]} \
      -contextHelp "Press to bring up a file selection dialog."
}

proc MakeContourFrame {widget} {
    global xLow xHigh yLow yHigh contourShades

    set xLow 0
    set xHigh 511
    set yLow 0
    set yHigh 483
    APSFrame $widget -parent .userFrame -label "Contour plot"
    set w .userFrame$widget.frame
    APSLabeledEntryFrame .xroi -parent $w -label "horizontal ROI: " \
      -variableList {xLow xHigh} -type integer -width 4 -contextHelp \
      "Enter the limits for the horizontal region of interest." -orientation horizontal
    APSLabeledEntryFrame .yroi -parent $w -label "vertical ROI: " \
    -variableList {yLow yHigh} -type integer -width 4 -contextHelp \
      "Enter the limits for the vertical region of interest." -orientation horizontal
    
    set contourShades 20
    APSLabeledEntry .shades -parent $w -label "Shades for contour plots: " \
      -textVariable contourShades  -width 4
    
    APSButton .contourPlot -parent $w -text "Plot" \
      -command {ContourPlot -fileName $inputFile -xLow $xLow -xHigh $xHigh \
                  -yLow $yLow -yHigh $yHigh -shades $contourShades}
}

proc PlotLineOut {args} {
    set position1 0
    set position2 483
    set fileName ""
    set low 0
    set high 511
    set direction H
    APSStrictParseArguments {position1 position2 fileName low high direction}
    global xHigh yHigh xLow yLow

    switch $direction {
        H {
            set highIndex $xHigh
            set highLine $yHigh
            set lowLine $yLow
        }
        V {
            set highIndex $yHigh
            set highLine $xHigh
            set lowLine $xLow
        }
    }
    if ![string length $fileName] { 
        setStatus "Pick an input file."
        return }
    if ![file exists $fileName] {
        setStatus "Not found: $fileName"
        return }
    set lineList ""
    for {set position $position1} {$position<=$position2} {incr position} {
        if {$position<$lowLine || $position>$highLine} {
            setStatus "Invalid position for $direction lineout.  Must be \[$lowLine, $highLine\]."
            return
        }
        lappend lineList [format %sLine%03ld $direction $position]
    }
    if $low>$high {
        set low 0
        set high 0
    }
    if [string compare $direction "V"]==0 {
        set tmpFile /tmp/[APSTmpString]
        APSAddToTempFileList $tmpFile
        exec sddstranspose $fileName -pipe=out \
          | sddsprocess -pipe=in -define=column,Index,i_row,type=short $tmpFile 
        set fileName $tmpFile
        after 10000 "file delete $tmpFile"
    }
    set lines [llength $lineList]
    if $lines<=10 {
        set sepNum 1
    } else {
        set sepNum [expr int($lines/10)]
        if $sepNum>15 {
            set sepNum 15
        }
    }
    exec sddsplot -column=Index,([join $lineList ,]) -separate=$sepNum -same -legend=edit=%/${direction}Line// \
        $fileName -scale=$low,$high,0,0 -graph=line,vary -ylabel=${direction}Line &
}

proc MakeProfileFrame {widget} {
    APSFrame $widget -parent .userFrame -label "Profiles" 
    set w .userFrame$widget.frame
    global position1 position2

    set position1 0
    set position2 483
    APSLabeledEntry .position1 -parent $w -label "Starting position" -width 4 \
      -textVariable position1 -type integer -contextHelp \
      "Enter the starting index at which to make a profile."
    APSLabeledEntry .position2 -parent $w -label "Ending position" -width 4 \
      -textVariable position2 -type integer -contextHelp \
      "Enter the ending index at which to make a profile."
    APSButton .hline -parent $w -text "Plot H Line-outs" \
      -command {PlotLineOut -position1 $position1 -position2 $position2 \
              -fileName $inputFile -low $xLow -high $xHigh -direction H} 
    APSButton .vline -parent $w -text "Plot V Line-outs" \
      -command {PlotLineOut -position1 $position1 -position2 $position2 \
              -fileName $inputFile -low $yLow -high $yHigh -direction V} 
}

MakeFileEntryFrame .input
MakeContourFrame .contour
MakeProfileFrame .profile
