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

#
# $Log: not supported by cvs2svn $
# Revision 1.15  2010/07/09 20:29:48  shang
# added Action menu and "update sr bpm error rms calc ADT" button for updating sr.bpm.error.rmscalc.pv when bpm inUse changes
#
# Revision 1.14  2010/06/28 19:26:04  soliday
# Removed an update command that was occuring before the screen was
# populated.
#
# Revision 1.13  2006/03/14 20:12:55  soliday
# Updated to not set the -display option if running through ssh.
#
# Revision 1.12  2004/07/26 19:14:32  soliday
# Added the ability to use editstring commands for substitution.
#
# Revision 1.11  2003/02/05 19:05:40  shang
# ADT now can be displayed in PC.
#
# Revision 1.10  2002/01/29 17:02:00  borland
# Added option to launch on display 0 or 1.
#
# Revision 1.9  2001/02/19 22:50:14  emery
# Using adthomedirectory option to adt.
#
# Revision 1.8  1999/12/10 21:16:22  emery
# Indented code.
#
# Revision 1.7  1998/07/29 19:43:56  borland
# New version per B. Dolin that works even if run in a directory that
# is write protected.
#
# Revision 1.6  1997/07/28 00:14:20  borland
# When name replacement is used, the name, units, scale factor, and
# logscale setting are changed to avoid confusion.
#
# Revision 1.5  1997/07/28 00:05:46  borland
# Fixed a bug in the last revision (needed -reuse on sddsxref).
#
# Revision 1.4  1997/07/27 19:15:17  borland
# Improved robustness of filtering/replacement.  Now correctly sets the number
# of areas and the area number.
#
# Revision 1.3  1997/07/22 19:47:34  borland
# Made procedure for producing filter frame.  Made filtering more robust
# so ADT won't bomb.
#
# Revision 1.2  1997/07/22 15:18:11  borland
# Latest version.  Mostly cosmetic improvements.
#
# Revision 1.1  1997/07/21 19:52:27  borland
# First version, by B. Dolin.
#
# 

set datapath /home/helios/OAG/oagData/ADTFiles
#set datapath /home/oxygen6/DOLIN/adtFiles

proc SetStatus {text} {
    global status
    set status "$text ([exec date +%H:%M:%S])"
    update
}

set filterList {*}
set filename {None}
set variableString ""
set replacementString "" 
set editString ""
set replaceOn 0


#filters/replaces the selected file and writes the result to tmpFile, then launches ADT to display
proc RunProcessing {args} {
    global status variableString replacementString replaceOn editString
    set display ""
    APSStrictParseArguments {filename wildcard display}
    SetStatus Filtering...
    set tmpFile /tmp/[APSTmpString]
    if [catch {exec sddsprocess -nowarning $filename $tmpFile \
                 -match=column,ControlName=$wildcard \
                 "-test=param,n_rows 0 >"} result] {
        return -code error $result
    }
    set arrays [exec sdds2stream $tmpFile -rows | wc -l]
    if [catch {exec sddsprocess $tmpFile $tmpFile.0 \
                 -redefine=param,ADTNArrays,$arrays,type=short} result] {
        return -code error $result
    }
    if [catch {APSGetSDDSNames -fileName $tmpFile.0 -class parameter}  parameterList] {
        return -code error $parameterList
    }
    if [lsearch -exact $parameterList ADTDisplayArea]!=-1 {
        if [catch {exec sddscollapse $tmpFile.0 -pipe=out \
                     | sddssort -pipe -unique -column=ADTDisplayArea \
                     | sddsprocess -pipe \
                     "-define=column,NewDisplayArea,i_row 1 +,type=short" \
                     | tee ${tmpFile}.areas \
                     | sdds2stream -rows -pipe | token -n=1} areas] {
            return -code error $areas
        }
        if [catch {exec sddscollapse $tmpFile.0 -pipe=out \
                     | sddsxref -pipe ${tmpFile}.areas -equate=ADTDisplayArea -take=NewDisplayArea \
                     -reuse=page,row -nowarning \
                     | sddsbreak -rowlimit=1 -pipe \
                     | sddsprocess -pipe=in ${tmpFile}.areas1 \
                     -process=NewDisplayArea,first,NewDisplayArea 
            exec sddsxref $tmpFile.0 ${tmpFile}.areas1 -pipe=out \
                     -leave=* -transfer=param,NewDisplayArea \
                     | sddsprocess -pipe=in ${tmpFile}.1 \
                     -redefine=parameter,ADTDisplayArea,NewDisplayArea,type=short \
                     -redefine=parameter,ADTNAreas,$areas,type=short
            file rename -force ${tmpFile}.1 $tmpFile} result] {
            return -code error $result
        }
    }
    if {$replaceOn==1} {
        # makes SDDS substitution if the checkbutton is checked
        SetStatus "Making replacements..."
        if {[string length $variableString]} {
            set option1 "-reedit=column,ControlName,9999%/$variableString/$replacementString/"
        } else {
            set option1 ""
        }
        if {[string length $editString]} {
            set option2 "-reedit=column,ControlName,$editString"
        } else {
            set option2 ""
        }
        if {[string length $option1] && [string length $option2]} {
            if {[catch {exec sddsprocess $tmpFile $tmpFile.1 -nowarning \
                          $option1 $option2 \
                          "-reedit=parameter,ADTHeading,9999Di/Edited PV List/" \
                          -reedit=parameter,ADTUnits,9999Di/?/ \
                          -redefine=parameter,ADTScaleFactor,1,type=double \
                          -redefine=parameter,ADTLogScale,0,type=short 
            } result]} {
                return -code error $result
            }
            file rename -force $tmpFile.1 $tmpFile
        } elseif {[string length $option1]} {
            if {[catch {exec sddsprocess $tmpFile $tmpFile.1 -nowarning \
                          $option1 \
                          "-reedit=parameter,ADTHeading,9999Di/Edited PV List/" \
                          -reedit=parameter,ADTUnits,9999Di/?/ \
                          -redefine=parameter,ADTScaleFactor,1,type=double \
                          -redefine=parameter,ADTLogScale,0,type=short 
            } result]} {
                return -code error $result
            }
            file rename -force $tmpFile.1 $tmpFile
        } elseif {[string length $option2]} {
            if {[catch {exec sddsprocess $tmpFile $tmpFile.1 -nowarning \
                          $option2 \
                          "-reedit=parameter,ADTHeading,9999Di/Edited PV List/" \
                          -reedit=parameter,ADTUnits,9999Di/?/ \
                          -redefine=parameter,ADTScaleFactor,1,type=double \
                          -redefine=parameter,ADTLogScale,0,type=short 
            } result]} {
                return -code error $result
            }
            file rename -force $tmpFile.1 $tmpFile
        }
    }
    set adtHomeDir [file dirname $filename]
    global env
    set computer [lindex [split $env(DISPLAY) :] 0]
   # exec adt -display $display -f $tmpFile -a $adtHomeDir &
    if {[info exists env(SSH_CLIENT)]} {
        exec adt -f $tmpFile -a $adtHomeDir &
    } else {
        if {$display == ""} {
            exec adt -f $tmpFile -a $adtHomeDir &
        } else {
            exec adt -display $computer$display -f $tmpFile -a $adtHomeDir &
        }
    }
    SetStatus "Data displayed."
}

proc makeFilterFrame {widget args} {
    set parent ""
    set filename ""
    APSStrictParseArguments {filename parent} 

    if ![winfo exists $parent$widget] {
        APSFrame $widget -parent $parent -label "Filter: " -packOption "-side left"
    }
    set w $parent$widget.frame
    if [string length $filename] {
        #reads filter information from the datafile's corresponding .filter file and creates radiobuttons
        global datapath filterList
        set filterFile [sdds open $filename.filter]
        set filterList [sdds getColumn $filterFile Filter]
        sdds close $filterFile
    } else {
        set filterList *
    }
    if [winfo exists $w.wild] {
        destroy $w.wild
    }
    if [winfo exists $w.wildEntry] {
        destroy $w.wildEntry
    }
    APSRadioButtonFrame .wild -parent $w -label "Filter:" \
      -variable wildcard -orientation vertical \
      -buttonList "$filterList" -valueList "$filterList" \
      -contextHelp "ADT will show only the data that matches this filter.  Pick one from the list, or type your preference into the entry box below." 
    $w.wild.frame.button1 select
    APSLabeledEntry .wildEntry -parent $w -label Custom: \
      -width 20 -textVariable wildcard \
      -contextHelp "Enter custom filter here, or override with one of the radio buttons."
}

proc ActivateReplaceEntries {widget mode} {
    $widget.frame1.orig.entry config -state $mode
    $widget.frame1.with.entry config -state $mode
    $widget.frame2.edit.entry config -state $mode
}

proc makeReplaceFrame {widget args} {
    set parent ""
    APSStrictParseArguments {parent}
    
    APSFrame $widget \
      -parent $parent \
      -label "Substitution within names" \
      -packOption "-fill x"
    set w $parent$widget.frame
    pack [frame $w.frame1] -side top -fill x
    APSRadioButtonFrame .rb \
      -parent $w.frame1 \
      -label "Do substitution: " \
      -orientation horizontal \
      -buttonList {Yes No} \
      -valueList {1 0} \
      -variable replaceOn \
      -commandList [list "ActivateReplaceEntries $w normal" "ActivateReplaceEntries $w disabled"]
    APSLabeledEntry .orig \
      -parent $w.frame1 \
      -label "   Replace:" \
      -width 20 \
      -textVariable variableString \
      -packOption "-side left" \
      -contextHelp "Enter text to be replaced here" 
    APSLabeledEntry .with \
      -parent $w.frame1 \
      -label "with:" \
      -width 20 \
      -textVariable replacementString \
      -packOption "-side left" \
      -contextHelp "Enter text to substitute here"

    pack [frame $w.frame2] -side top -fill x
    APSLabeledEntry .edit \
      -parent $w.frame2 \
      -label "EditString:" \
      -width 20 \
      -textVariable editString \
      -packOption "-side left" \
      -contextHelp "Enter editstring command here"
    
    global replaceOn
    ActivateReplaceEntries $w disabled
    set replaceOn 0
}

proc UpdateSRBPMrmsCalcADT {args} {
    SetStatus "updating sr bpm error rms calc ADT ..."
    if [catch {exec createSRBPMrmsCalcADT} result] {
        SetStatus "Error in updating sr bpm error rms calc ADT: $result"
        APSAlertBox .errorpvrms -errorMessage "Error in updating sr bpm error rms calc ADT: $result"
        return
    }
    SetStatus "done."
}
proc UpdateSRBPMRTFBADT {args} {
    SetStatus "updating sr rtfb  bpm error ..."
    if [catch {exec createSRBPM_RTFB_ADT} result] {
        SetStatus "Error in updating sr rtfb bpm error ADT: $result"
        APSAlertBox .errorpvrms -errorMessage "Error in updating sr rtfb bpm error ADT: $result"
        return
    }
    SetStatus "done."
}

APSApplication . \
  -name ADTFilter \
  -version 1.0 \
  -overview "Allows user to filter data before being displayed by ADT"

set status Ready...
APSScrolledStatus .status \
  -parent .userFrame \
  -textVariable status \
  -packOption "-fill both -expand true"

APSLabeledEntry .filename \
  -parent .userFrame \
  -label File: \
  -width 55 \
  -textVariable filename \
  -contextHelp "Enter file name here" \
  -packOption "-fill x"
pack configure .userFrame.filename.entry -expand true

makeReplaceFrame .replace -parent .userFrame
makeFilterFrame .filter -parent .userFrame

APSFrame .run \
  -parent .userFrame \
  -packOption "-side left -anchor sw -fill x -expand true"
set w .userFrame.run.frame


proc IsRedhat7 {args} {
    set fid [open /etc/redhat-release r]
    set line [gets $fid]
    close $fid
    if {([string first "Red Hat" $line] != -1) && ([string first "release 7" $line] != -1)} {
        return 1
    }
    return 0
}
proc IsRedhat8 {args} {
    set fid [open /etc/redhat-release r]
    set line [gets $fid]
    close $fid
    if {([string first "Red Hat" $line] != -1) && ([string first "release 8" $line] != -1)} {
        return 1
    }
    return 0
}

if {([IsRedhat7] != 1) && ([IsRedhat8] != 1)} { 
APSButton .run1 \
  -parent $w \
  -text "Run ADT Display 1" \
  -packOption "-side bottom -fill x" -command \
  {RunProcessing -filename $filename -wildcard $wildcard -display :0.1} \
  -contextHelp "Display filtered file with ADT"
APSButton .run0 \
  -parent $w \
  -text "Run ADT Display 0" \
  -packOption "-side bottom -fill x" -command \
  {RunProcessing -filename $filename -wildcard $wildcard -display :0.0} \
  -contextHelp "Display filtered file with ADT"
} else {
APSButton .run1 \
  -parent $w \
  -text "Run ADT" \
  -packOption "-side bottom -fill x" -command \
  {RunProcessing -filename $filename -wildcard $wildcard} \
  -contextHelp "Display filtered file with ADT"

}

APSMenubarAddMenu .system \
  -parent .menu \
  -text System \
  -contextHelp "Select APS system"
set systemsDir [lsort [glob $datapath/*]]
set systemsNum [llength $systemsDir]
set systemsCounter 0
#creates the system menu structure
while {$systemsCounter<$systemsNum} {
    set system [lindex "$systemsDir" $systemsCounter]
    menu .menu.system.menu.$system
    .menu.system.menu add cascade \
      -label [file tail $system] \
      -menu .menu.system.menu.$system
    set fileDir [lsort [glob $system/*.pv]]
    set fileNum [llength $fileDir]
    set fileCounter 0
    while {$fileCounter<$fileNum} {
        #creates the file lists within the system menus
        set data [lindex "$fileDir" $fileCounter]
        .menu.system.menu.$system add command \
          -label [file tail $data] -command \
          "set filename $data; makeFilterFrame .filter -parent .userFrame -filename $data"
        incr fileCounter
    }
    incr systemsCounter
}
APSMenubarAddMenu .action \
  -parent .menu \
  -text Action \
  -contextHelp "Action buttons"
.menu.action.menu add command \
          -label "update sr bpm error rms calc ADT" -command \
          "UpdateSRBPMrmsCalcADT"
.menu.action.menu add command \
          -label "update rtfb bpm error ADT" -command \
          "UpdateSRBPMRTFBADT"

set status "If your computer has only one display, \n\"Run ADT display 1\" won't work for you"

