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

# $Log: not supported by cvs2svn $
# Revision 1.12  2005/01/14 17:46:11  emery
# Moved procedure APSMpKnLValues (formerly known as KnLValues) to
# the library APSMpMagnetSetpoints.tcl. Changed argument name
# xrefFile to xrefFileList in various procedure
# calls to explicitly show that a list of files may be passed.
#
# Revision 1.11  2005/01/13 21:22:46  emery
# Replaced array variable KnlValues with SRKnlValues and
# BoosterKnlValues which work for each beamline tab.
# This maintains file selection for each tab when the tabs are switched.
# Also renamed the procedure KnLValues to APSMpKnLValues for future
# moving to a tcl library.
# Added argument BRhoPVName to APSMpKnLValues.
#
# Revision 1.10  2005/01/13 20:30:57  emery
# Implemented tab widget for choice between SR and BTS beamline.
# Reworked KnLValues procedure to have arguments that are similar
# to those of procedure setpoints in application setpoints.
#
# Revision 1.9  2004/08/03 23:29:17  emery
# Added double column ParameterValue (equal to Kn) to the output file.
# The string column ElementParameter is also present in the output
# file. Its value is imported from the xref file which had to be updated
# with the fixed values for each magnet (i.e. K1, K2, or ANGLE).
#
# Revision 1.8  2004/08/03 21:42:48  emery
# Made changes that will make extension to other SCR systems and
# beamlines easier. Added variables for magnet filters.
# Use sddsinterpset instead of sddsinterp.
# Removed some unused variable.
# Removed copy of APSAddSCRDialog and related procedures
# in order to rely on original procedures in
# library file mplib/leutl/switch.tcl
# Kept local version of APSAddSCRDialogCallback
# so that global variable outputFileRoot can be
# updated when selecting a SCR file.
# Removed standardize file-related buttons and procedures.
# These are effectively replaced by SR pem procedures.
# Removed Stop button.
#
# Revision 1.7  2002/04/12 20:44:35  emery
# Added Kn calculation of V. Sajaev.
#
# Revision 1.6  2002/01/29 16:35:32  borland
# Embedded old versions of SCR procedures to restore function after upgrade of
# those procedures.
#
# Revision 1.5  2001/02/17 00:08:31  emery
# Corrected daily directory button definition, and make
# sure that the daily directory button is placed next to the
# directory entry slot.
#
# Revision 1.4  2000/01/19 09:22:33  emery
# Replaced standardization template with new one
# in /home/helios/oagData/sr/magnetConditioning/template.std
#
# Revision 1.3  2000/01/19 05:06:16  emery
# Initially disable the stop button.
#
# Revision 1.2  2000/01/19 03:59:28  emery
# Added APSListSCRMatchSetArray1 which
# allows file selected from a box. Added make standardization buttons.
#
# Revision 1.1  1999/08/31 03:24:46  emery
# First installation. Converts a SCR file to a file of KnL values.
#

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 CVSRevisionAuthor "\$Author: borland $"

APSApplication . -name KnLValues \
  -overview "KnLValues converts a SCR file to a file of KnL values."

proc MakeInputFrame {widget args} {
    set parent ""

    global energy 
    global outputFileDir outputFileRoot outputFile 
    global beamlineSelection daysPast
    # these are array names for the separate SCR file selection.
    global BoosterKnLValues SRKnLValues
    
    APSStrictParseArguments {parent}
    
    APSFrame $widget -parent $parent -label "Input parameters"
    set w $parent$widget.frame

    set widgetList [APSTabFrame .beamlines -parent $w -label "" \
                      -labelList "SR BTS" -width 1000 -height 500  \
                      -commandList {{defaultFiles -beamline SR} {defaultFiles -beamline BTS}} ]
    $w.beamlines.frame configure -relief flat
    pack $w.beamlines -side top
    $w.beamlines.frame.tn select 0
    lappend SensitiveWidgetList $w.beamlines.frame.tn
    set windex 0
    
    # SR frame
    set tabwidget [lindex $widgetList $windex]
    incr windex
    APSFrame .sr -parent $tabwidget \
      -label ""  -contextHelp "Frame which specifies data for SR beamline"
    set w $tabwidget.sr.frame

    # The value of system argument in this call gets transfered to 
    # the argumnet machine in APSAddSCRDialogCallback.
    APSAddSCRDialog .scr -parent $w -system SR \
      -arrayName SRKnLValues \
      -defaultFile $SRKnLValues(ShortFilename)

    set tabwidget [lindex $widgetList $windex]
    incr windex
    set w $tabwidget.bts.frame
    APSFrame .bts -parent $tabwidget \
      -label ""  -contextHelp "Frame which specifies data for BTS beamline"

    APSAddSCRDialog .scr -parent $w -system Booster \
      -arrayName BoosterKnLValues \
      -defaultFile $BoosterKnLValues(ShortFilename)

    set w $parent$widget.frame
    APSCheckButtonFrame .magnetType -parent $w -orientation horizontal \
      -label "Magnet Set: " -variableList {doQuads doSexts doBends doSkew} \
      -buttonList {Q S B Skew} \
      -allNone 1 \
      -contextHelp "Choose which set of magnets to calculate"

    APSLabeledEntry .energy -parent $w -label "Energy (GeV): " \
      -textVariable energy \
      -contextHelp "Enter the energy in GeV."
    
    APSFrame .saveData -parent $w -label "Save data" \
      -contextHelp "Frame to specify the location of calculated data."
    
    APSLabeledEntry .outputFileDir -parent $w.saveData.frame -label "directory: " \
      -textVariable outputFileDir -width 70 \
      -contextHelp "Directory for lattice file."
    
    APSButton .daily -parent $w.saveData.frame.outputFileDir -packOption "-anchor e" \
      -text "daily"  -size small \
      -command {set outputFileDir [APSGoToDailyDirectory]}

    APSLabeledEntry .outputFileRoot -parent $w.saveData.frame -label "root: " \
      -textVariable outputFileRoot -width 70 \
      -contextHelp "Root name for lattice file."

    return
}


proc SetStatus {text} {
    global status
    set status $text
}

set status "Working."
APSScrolledStatus .status -parent .userFrame -textVariable status -width 90

# determines file lists for variables xrefFile and templateFile when
# the tab is selected.  Lists are required because of the different
# types of magnets.
proc defaultFiles {args} {
    global beamline xrefFile templateFile  magnetType filePath BRhoPVName
    global doQuads doSexts doBends
    global machine
    APSStrictParseArguments {beamline}
    set xrefFile($beamline) ""
    set templateFile($beamline) ""
    switch $beamline {
        SR {
            set machine SR
            set BRhoPVName S:BRhoCALC
            set directory /home/helios/oagData/controlFiles/SR
            set templateDir /home/helios/oagData/sr/magnetConditioning/templates
            if $doQuads {
                lappend xrefFile($beamline) $directory/SQ_xref.sdds
                lappend templateFile($beamline) $templateDir/SQ_stand.sdds
            }
            if $doSexts {
                lappend xrefFile($beamline) $directory/SS_xref.sdds
                lappend templateFile($beamline) $templateDir/SS_stand.sdds
            }
            if $doBends {
                lappend xrefFile($beamline) $directory/SB_xref.sdds
                lappend templateFile($beamline) $templateDir/SB_stand.sdds
            }
        }
        BTS {
            set machine Booster
            set BRhoPVName S:BRhoCALC
            set directory /home/helios/oagData/controlFiles/BTS/magnetData
            set templateDir /home/helios/oagData/BTS/magnetConditioning/templates
            if $doQuads {
                lappend xrefFile($beamline) $directory/BTSQ_xref.sdds
                lappend templateFile($beamline) $templateDir/BTSQ_standardize.sdds
            }
            if $doBends {
                lappend xrefFile($beamline) $directory/BTSB_xref.sdds
                lappend templateFile($beamline) $templateDir/BTSB_standardize.sdds
            }
        }
    }
    set status "Beamline switched to $beamline."
    return
}

set doQuads 1
set doSexts 1
set doSkew 0
# doBends doesn't work yet because there is one power supply 
# but 80 different dipole elements.
set doBends 0
set energy 7 
set outputFileDir .
set outputFileRoot ""
set statusCallback ""
set abortVariable ""
set SRKnLValues(ShortFilename) ""
set SRKnLValues(Filename) ""
set BoosterKnLValues(ShortFilename) ""
set BoosterKnLValues(Filename) ""

MakeInputFrame .input -parent .userFrame
set status "Ready."
update

# L. Emery modified the tcl procedure APSAddSCRDialogCallback
# from library mplib/leutl/switch.tcl to
# add actions to the callback. This procedure has to be located
# after the call to MakeInputFrame because the mplib/leutl/switch.tcl 
# file is first sourced during within MakeInputFrame.
proc APSAddSCRDialogCallback {arrayName machine} {
    global $arrayName apsSCRSnapDir status 
    global outputFileRoot
    if [set ${arrayName}(FileNotFound)] {
        set status "File not found!"
        update
        return
    }
    set name [set ${arrayName}(Filename)]
    set descrip [set ${arrayName}(Description)]
    set snapDir $apsSCRSnapDir/$machine
    if ![file exists $snapDir/$name] {
        if [file exists $snapDir/${name}.gz] {
            set name ${name}.gz
        } else {
            set status "File not found!"
            update
            return
        }
    }
    set ${arrayName}(ShortFilename) $name
    set ${arrayName}(Filename) $snapDir/$name
    set outputFileRoot [file root $name]
}

proc GenerateSkews {args} {
    APSParseArguments {SCRFile energy outputFileDir outputFileRoot statusCallback}
    #--- From SROpticsCorrection:
    set calibration0 82.7
    set calibration1 660
    set energyScaling [expr $energy / 7.0]

    exec sddsprocess $SCRFile $outputFileDir/$outputFileRoot.QS \
	-match=col,ControlName=*QS:CurrentAO -scan=col,Value,ValueString,%lf \
	"-redef=col,ParameterValue,Value $calibration0 / $energyScaling /" \
	"-edit=col,ElementName,ControlName,%@:CurrentAO@@"
    exec sddsprocess $SCRFile $outputFileDir/$outputFileRoot.QS4 \
	-match=col,ControlName=*QS4:CurrentAO -scan=col,Value,ValueString,%lf \
	"-redef=col,ParameterValue,Value $calibration1 / $energyScaling /" \
	"-edit=col,ElementName,ControlName,%@:CurrentAO@@"
    exec sddscombine $outputFileDir/$outputFileRoot.QS $outputFileDir/$outputFileRoot.QS4 -pipe=out -merge \
	| sddsconvert -pipe -retain=col,ElementName,ParameterValue \
	| sddsprocess -pipe=in $outputFileDir/$outputFileRoot.skew -print=col,ElementParameter,K1 \
	-redef=col,ElementOccurence,1,type=long
    file delete $outputFileDir/$outputFileRoot.QS $outputFileDir/$outputFileRoot.QS4
}

# variables used by the button definition below
# and changed by the tab widget switching.
set machine SR
set beamline SR

APSButton .calculate -parent .userFrame -text Calculate -command \
  { \
      APSDisableButton .userFrame.calculate.button 
      if {$doQuads || $doSexts} {
	  catch {
	      defaultFiles -beamline $beamline
	      APSMpMagnetKnLValues -SCRFile [set ${machine}KnLValues(Filename)] \
		  -xrefFileList $xrefFile($beamline) \
		  -energy $energy  -BRhoPVName $BRhoPVName \
		  -outputFileDir $outputFileDir \
		  -outputFileRoot $outputFileRoot \
		  -statusCallback "APSSetVarAndUpdate status" \
		  -abortVariable abortRun} status
	  update idletasks
      }
      if $doSkew {
	  if [catch {GenerateSkews -SCRFile [set ${machine}KnLValues(Filename)] \
			 -energy $energy \
			 -outputFileDir $outputFileDir \
			 -outputFileRoot $outputFileRoot \
			 -statusCallback "APSSetVarAndUpdate status"} result] {
	      APSSetVarAndUpdate status "GenerateSkews: $result"
	  }
      }
	  
      APSEnableButton .userFrame.calculate.button
  }

set outputFileRoot test
