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

#
# $Log: not supported by cvs2svn $
# Revision 1.22  2000/10/17 21:17:59  soliday
# Added a comment about the scrolled frame.
#
# Revision 1.21  2000/07/05 16:16:27  soliday
# Placed everything inside a scrollable frame so that all monitors can display
# the entire contents of the program.
#
# Revision 1.20  2000/01/04 18:51:52  borland
# Fixed "are you sure" messages for switching to large/small font.
#
# Revision 1.19  1999/11/10 22:01:35  soliday
# Added button for smaller font sizes
#
# Revision 1.18  1999/09/28 16:59:00  emery
# Added argument initialConfig to pre-loaded a configuration
# at start-up.
#
# Revision 1.17  1999/09/13 23:47:02  emery
# Changed ID Xray bpm symbol from X to I.
#
# Revision 1.16  1999/08/13 16:24:21  emery
# Fixed omission of BM Xray bpms "All" button in the printout.
#
# Revision 1.15  1999/08/11 16:38:44  emery
# Added BM Xray bpms.
#
# Revision 1.14  1999/07/01 21:58:04  soliday
# Streamlined the print procedure and added the X1 and X2 columns
#
# Revision 1.13  1999/06/03 22:07:58  borland
# elegant output no longer includes missing elements.
#
# Revision 1.12  1999/06/03 21:56:06  borland
# Added to the file menu an entry that permits dumping a configuration
# as an SDDS file suitable for use with simulation program elegant
# (load_parameters).
#
# Revision 1.11  1999/05/21 19:06:04  borland
# Fixed bug with restart in H/V mode.
#
# Revision 1.10  1999/04/19 18:11:48  borland
# Invokes use of ID P1 and P2 .
#
# Revision 1.9  1998/11/18 21:49:34  soliday
# Added P0 monitors to the printout.
#
# Revision 1.8  1998/09/09 17:18:48  borland
# Default value of includeP0s is now 1.
#
# Revision 1.7  1998/09/03 19:28:42  borland
# Added commandline control of includeP0 mode.
#
# Revision 1.6  1998/08/28 16:39:53  borland
# Added -includeP0s option to APSSRConfigOrbitCorrection call.  Fixed
# bug in v/h switching.
#
# Revision 1.5  1998/08/11 15:38:32  borland
# Print feature added by R. Soliday.
#
# Revision 1.4  1998/05/29 04:15:07  borland
# Added "Are you sure?" query before abort/switch between H and V modes.
#
# Revision 1.3  1998/05/29 04:04:48  borland
# Now supports switching checkbuttons from vertical to horizontal format.
#
# Revision 1.2  1998/01/09 16:50:04  borland
# Made a better window title and added an overview message.
#
#

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

wm geometry . +10+10

set args $argv
set buttonOrientation vertical
set fontSize regular
set includeP0s 1
set includeIDs 1
set includeBMs 1
set initialConfig ""
APSStrictParseArguments {buttonOrientation includeP0s includeIDs includeBMs initialConfig fontSize}
if [info exists env(PRINTER)] {
  set printerName $env(PRINTER)
} else {
  set printerName mcr1
}

APSApplication . -name SROrbitCorrectionConfig -version 1 \
  -overview {This application allows configuration of SR orbit correction.  You may choose the lattice, which monitors and correctors to use, and restrict your choices to only good components.}
if {$fontSize == "small"} {
    option add *font -adobe-courier-medium-r-normal-*-10-*-*-*-*-*-*-*
}
proc ConfirmRestart {args} {
    global win
    set mode vertical
    set includeP0s 1
    set includeIDs 1
    set includeBMs 1
    set fontSize regular
    APSStrictParseArguments {mode includeP0s includeIDs includeBMs fontSize}
    if {[APSMultipleChoice [APSUniqueName .] -question \
           "Are you sure?  Exit and restart in $mode mode?"  \
           -returnList {1 0} -labelList {Yes No}]} { 
        exec SROrbitCorrectionConfig -buttonOrientation $mode -includeP0s $includeP0s \
          -includeIDs $includeIDs -includeBMs $includeBMs -fontSize $fontSize & 
        exit
    }
}

proc ElegantInput {} {
    set filename [APSInfoDialog [APSUniqueName .] -name "Info Dialog" \
                    -infoMessage "Enter filename for creating elegant input file." \
                    -width 60]
    set output(ColumnNames) "ElementName ElementParameter ParameterValue"
    set output(ColumnInfo.ElementName) "type SDDS_STRING"
    set output(ColumnInfo.ElementParameter) "type SDDS_STRING"
    set output(ColumnInfo.ParameterValue) "type SDDS_DOUBLE"
    set missingBPMList [APSGetMissingBPMList]
    set missingCorList {S1A:H3 S39B:H1 S40A:H3 S1A:V3 S39B:V1 S40A:V3}
    for {set sector 1} {$sector<41} {incr sector} {
        foreach BPM [list A:P1 A:P2 A:P3 A:P4 B:P5 B:P4 B:P3 B:P2 B:P1 A:P0 B:P0] {
            set BPMName S${sector}$BPM
            if [lsearch -exact $missingBPMList $BPMName]!=-1 continue
            set nameFlag sconfig$BPMName
            global $nameFlag
            lappend output(Column.ElementName) $BPMName
            lappend output(Column.ElementParameter) WEIGHT
            lappend output(Column.ParameterValue) [set $nameFlag]
        }
        foreach cor {A:H1 A:H2 A:H3 A:H4 B:H4 B:H3 B:H2 B:H1 \
                       A:V1 A:V2 A:V3 A:V4 B:V4 B:V3 B:V2 B:V1} {
            set corName S${sector}$cor
            if [lsearch -exact $missingCorList $corName]!=-1 continue
            set nameFlag sconfig$corName
            global $nameFlag
            lappend output(Column.ElementName) $corName
            lappend output(Column.ElementParameter) STEERING
            lappend output(Column.ParameterValue) [set $nameFlag]
        }
    }
    foreach item {ElementName ElementParameter ParameterValue} {
        set output(Column.$item) [list $output(Column.$item)]
    }
    if [catch {sdds save $filename output} result] {
        return -code error "$result"
    }
}

proc Print {} {
    global printerName buttonOrientation apsScriptUser includeBMs includeIDs includeP0s
    APSSetVarAndUpdate sconfigConfigStatus Printing
    set output "Printed by $apsScriptUser on [clock format [clock seconds]]\n\n"
    set letterList "A A A A B B B B B"
    set numberList "1 2 3 4 5 4 3 2 1"
    if {$includeP0s} {
        set letterList "A $letterList B"
        set numberList "0 $numberList 0"
    }
    if {$includeBMs} {
        set letterList "$letterList D D"
        set numberList "$numberList 1 2"
    }
    if {$includeIDs} {
        set letterList "$letterList I I"
        set numberList "$numberList 1 2"
    }
    if {[string compare $buttonOrientation vertical]==0} {
        set w $win.config.top.but.frame
        set title "      Monitors   "
        if {$includeP0s} {
            set title "  $title  "
        }
        if {$includeIDs} {
            set title "  $title  "
        }
        if {$includeBMs} {
            set title "  $title  "
        }
        append output "    $title         H Correctors          V Correctors\n"
        append output "    $letterList       A A A A B B B B       A A A A B B B B\n"
        append output "    $numberList       1 2 3 4 4 3 2 1       1 2 3 4 4 3 2 1"

        if {$includeIDs} {
            set letterList [lrange $letterList 0 [expr [llength $letterList] - 3]]
            set numberList [lrange $numberList 0 [expr [llength $numberList] - 3]]
        }
        if {$includeBMs} {
            set letterList [lrange $letterList 0 [expr [llength $letterList] - 3]]
            set numberList [lrange $numberList 0 [expr [llength $numberList] - 3]]
        }

        for {set checkBoxRow 1} {$checkBoxRow<41} {incr checkBoxRow} {
            append output [format "\n %2d " $checkBoxRow]
            append output [getCheckboxValues -letterList $letterList \
                             -numberList $numberList -plane P -row $checkBoxRow]
            if {$includeBMs} {
                append output [getCheckboxValue -checkVar ${checkBoxRow}BM:P1]
                append output [getCheckboxValue -checkVar ${checkBoxRow}BM:P2]
            }    
            if {$includeIDs} {
                append output [getCheckboxValue -checkVar ${checkBoxRow}ID:P1]
                append output [getCheckboxValue -checkVar ${checkBoxRow}ID:P2]
            }    
            foreach plane "H V" {
                append output [format "   %2d " $checkBoxRow]
                append output [getCheckboxValues -letterList "A A A A B B B B" \
                                 -numberList "1 2 3 4 4 3 2 1" -plane $plane -row $checkBoxRow]
            }
        }
        append output "\nALL "
        append output [getCheckboxValues -letterList $letterList \
                         -numberList $numberList -plane P -row ""]
        if {$includeBMs} {
            append output [getCheckboxValue -checkVar BM:P1]
            append output [getCheckboxValue -checkVar BM:P2]
        }
        if {$includeIDs} {
            append output [getCheckboxValue -checkVar ID:P1]
            append output [getCheckboxValue -checkVar ID:P2]
        }    
        foreach plane "H V" {
            append output "  ALL "
            append output [getCheckboxValues -letterList "A A A A B B B B" \
                             -numberList "1 2 3 4 4 3 2 1" -plane $plane -row ""]
        }
    } else {
        if {$includeIDs} {
            set letterList [lrange $letterList 0 [expr [llength $letterList] - 3]]
            set numberList [lrange $numberList 0 [expr [llength $numberList] - 3]]
        }
        if {$includeBMs} {
            set letterList [lrange $letterList 0 [expr [llength $letterList] - 3]]
            set numberList [lrange $numberList 0 [expr [llength $numberList] - 3]]
        }
        set output2    "                     1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 l\n"
        append output2 "   1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 l"
        append output [format "%48s\n%84s\n%s" Monitors A $output2]
        append output [CheckboxHor -letterList $letterList -numberList $numberList -plane P]
        if {$includeBMs} {
            append output [CheckboxHor -itemList "BM:P1 BM:P2" \
                             -letterList "D D" -numberList "1 2" -plane P]
        }    
        if {$includeIDs} {
            append output [CheckboxHor -itemList "ID:P1 ID:P2" \
                             -letterList "X X" -numberList "1 2" -plane P]
        }    
        foreach plane "H V" {
            append output [format "\n\n%50s\n%84s\n%s" "$plane Correctors" A $output2]
            append output [CheckboxHor -letterList "A A A A B B B B" -numberList "1 2 3 4 4 3 2 1" -plane $plane]
        }
    }
    global sconfigReadDescription sconfigReadFile
    append output [format "\n\n%-15s%s" Config: $sconfigReadFile]
    append output [format "\n%-15s%s" Description: $sconfigReadDescription]
    set fileName /tmp/[APSTmpString]
    APSAddToTempFileList $fileName
    set fileId [open $fileName w 0600]
    puts $fileId $output
    close $fileId
    exec cat $fileName | lpr -P$printerName
    APSSetVarAndUpdate sconfigConfigStatus Done
}

proc getCheckboxValues {args} {
    APSStrictParseArguments {letterList numberList plane row}
    foreach letter $letterList number $numberList {
        set checkVar sconfigS${row}${letter}:$plane${number}
        global $checkVar
        if {[set $checkVar]==1} {
            append output "x "
        } else {
            append output [format "%c " 183]
        }
    }
    return $output
}

proc getCheckboxValue {args} {
    APSStrictParseArguments {checkVar}
    set checkVar sconfigS$checkVar
    global $checkVar
    if {[set $checkVar]==1} {
        set output "x "
    } else {
        set output [format "%c " 183]
    }
    return $output
}

proc CheckboxHor {args} {
    set output ""
    set itemList ""
    APSStrictParseArguments {letterList numberList plane itemList}
    foreach letter $letterList number $numberList itemName $itemList {
        set item ${letter}${number}
        append output [format "\n%2s " $item]
        set item ${letter}:${plane}${number}
        if {[llength $itemName]} {
            set item $itemName
        }
        for {set checkBoxColumn 1} {$checkBoxColumn<41} {incr checkBoxColumn} {
            set checkVar sconfigS$checkBoxColumn$item
            global $checkVar
            if {[set $checkVar]==1} {
                append output "x "
            } else {
                append output [format "%c " 183]
            }
        }
        set checkVar sconfigS${item}
        global $checkVar
        if {[set $checkVar]==1} {
            append output "x "
        } else {
            append output [format "%c " 183]
        }
    }
    return $output
}

proc printDialog {} {
    set printDialog [APSUniqueName .]
    toplevel $printDialog
    wm title $printDialog "Print Dialog"
    global printerName
    APSLabeledEntry .enterPrinter -parent $printDialog -label Printer -textVariable printerName
    APSButton .startPrinting -parent $printDialog -text Print -command "Print;destroy $printDialog"
    APSButton .cancelPrinting -parent $printDialog -text Cancel -command "destroy $printDialog"
}

APSMenubarAddMenu .program -parent .menu -text Programs -contextHelp "Run related programs"
if [string compare $buttonOrientation vertical]==0 {
    .menu.program.menu add command -label "Horizontal version" -command \
      "ConfirmRestart -mode horizontal -includeP0s $includeP0s -includeIDs $includeIDs -includeBMs $includeBMs -fontSize $fontSize"
} else {
    .menu.program.menu add command -label "Vertical version" -command \
      "ConfirmRestart -mode vertical -includeP0s $includeP0s -includeIDs $includeIDs -includeBMs $includeBMs -fontSize $fontSize"
}
if {$fontSize == "small"} {
    .menu.program.menu add command -label "Larger font size" -command \
	"ConfirmRestart -mode large-font -includeP0s $includeP0s -includeIDs $includeIDs -includeBMs $includeBMs"
} else {
    .menu.program.menu add command -label "Smaller font size" -command \
	"ConfirmRestart -mode small-font -includeP0s $includeP0s -includeIDs $includeIDs -includeBMs $includeBMs -fontSize small"
}
.menu.file.menu insert 1 command -label "Make elegant file..." -command "ElegantInput"
.menu.file.menu insert 1 command -label "Print..." -command "printDialog"


if [catch {package require Iwidgets} result] {
    if [catch {package require iWidgets} result] {
        package require iwidgets
    }
}
iwidgets::scrolledframe .userFrame.sf -hscrollmode dynamic -vscrollmode dynamic
pack .userFrame.sf -fill both -expand true
set win [.userFrame.sf childsite]


set rootname sconfig
APSSRConfigOrbitCorrection .config -parent $win -rootname $rootname \
  -fileFrame 1 -buttonOrientation $buttonOrientation -includeP0s $includeP0s \
  -includeIDs $includeIDs -includeBMs $includeBMs

if [string length $initialConfig] {
    set ${rootname}ReadFile $initialConfig
    eval APSReadOrbitCorrectionConfig -rootname $rootname -filename \$${rootname}MainDir/\$${rootname}LatSubDir/\$${rootname}Lattice/\$${rootname}ReadFile/config -logic replace -includeP0s $includeP0s -includeIDs $includeIDs -includeBMs $includeBMs
    }


tkwait visibility $win
set sfinfo(size) [[string range $win 0 [expr [string last . $win] - 1]] cget -scrollregion]

#If the frame underneath the scrolled frame is larger then the screen,
#set the scrolled frame a little bit smaller then the screen.
#Otherwise set the scrolled frame to the same dimensions as the frame
#underneath.
if {[lindex $sfinfo(size) 2] > [winfo screenwidth .]} {
    .userFrame.sf configure -width [expr [winfo screenwidth .] - 30]
} else {
    .userFrame.sf configure -width [lindex $sfinfo(size) 2]
}
if {[lindex $sfinfo(size) 3] > [winfo screenheight .]} {
    .userFrame.sf configure -height [expr [winfo screenheight .] - 90]
} else {
    .userFrame.sf configure -height [lindex $sfinfo(size) 3]
} 
