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

if [info exists env(LOCO_BINDIR)] {
    set locoBinDir $env(LOCO_BINDIR)
} else {
    puts stderr "Error: LOCO_BINDIR environment variable is not defined"
    exit
}
set auto_path [linsert $auto_path 0 $locoBinDir/tclLib]

set hostname [exec hostname]
set applicationName SRAdjustTunes@$hostname
APSApplication . -name $applicationName -version 1 \
    -overview {This application varies Q1 and Q2 families to get required tunes. \
						 Families are varied using coefficients from knob files. Implemented by V. Sajaev}

set status ""
APSScrolledStatus .status -parent .userFrame -textVariable status -width 70 -height 10

#----------------------------------------------------------------------------------------------------------------------------

proc DisableWidgets {args} {
    global sensitiveWidgets
    APSParseArguments {option}
    if {-1 < [lsearch [array names sensitiveWidgets] $option]} {
        foreach widget $sensitiveWidgets($option) {
            $widget configure -state disabled
        }
    }
    return
}
proc EnableWidgets {args} {
    global sensitiveWidgets
    APSParseArguments {option}
    if {-1 < [lsearch [array names sensitiveWidgets] $option]} {
        foreach widget $sensitiveWidgets($option) {
            $widget configure -state normal
        }
    }
    return
}

#----------------------------------------------------------------------------------------------------------------------------

set parent .userFrame
APSLabeledEntry .lteFile -parent $parent \
	 -label "Lattice (.lte) file:" \
	 -textVariable lteFile -width 70
APSLabeledEntry .beamline -parent $parent \
	 -label "Beamline name:" \
	 -textVariable beamline -width 70
APSLabeledEntry .paramFile -parent $parent \
	 -label "Input param file (optional):" \
	 -textVariable paramFile -width 70
APSLabeledEntry .knobFile -parent $parent \
	 -label "Knob file:" \
	 -textVariable knobFile -width 70
APSLabeledEntry .outputFile -parent $parent \
	 -label "Output parameter file:" \
	 -textVariable outputFile -width 70 \
	 -contextHelp "The output parameter file. It is NOT combined with the input parameter file. The correct model will have to contain both files, or the user may combine them manually."
APSLabeledEntry .qx -parent $parent \
	 -label "Required Qx:" \
	 -textVariable Qx -width 20
APSLabeledEntry .qy -parent $parent \
	 -label "Required Qy:" \
	 -textVariable Qy -width 20
APSLabeledEntry .tol -parent $parent \
	 -label "Tolerance:  " \
	 -textVariable tol -width 20

APSButton .calculate -parent $parent -text " Run " -command {
    if {![string length $Qx] || ![string length $Qy]} {
	return -code error "Error: Tune input is empty."
    }
    set abortFile [exec pwd]/tuneAdjust.abort
    if [catch {AdjustTunes \
		   -lteFile $lteFile \
		   -beamline $beamline \
		   -paramFile $paramFile \
		   -knobFile $knobFile \
		   -outputFile $outputFile \
		   -Qx $Qx \
		   -Qy $Qy \
		   -tol $tol \
		   -abortFile $abortFile
    } result] {
        APSSetVarAndUpdate status "AdjustTunes: $result"
    }
    update idletasks
}  -contextHelp "Adjusts tunes using knob file coefficients."

APSButton .plot -parent $parent -text " Plot beta functions " -command {
    exec sddsplot $twiFile -col=s,beta? -sep -layout=1,2 -end $twiFile -col=s,etax &
    update idletasks
}  -contextHelp "Plots beta functions."

APSButton .stop -parent $parent -text " Abort " -command { 
    set abortFile [exec pwd]/tuneAdjust.abort
    exec touch $abortFile
    APSSetVarAndUpdate status "Abort pending..."
} -contextHelp "Aborts whole run."

APSButton .plot1 -parent $parent -text " Plot quads " -command {
    exec sddsplot -graph=symbol,connect \
		  -col=ElementName,ParameterValue -match=col,ElementName=*Q1 $outputFile -end \
		  -col=ElementName,ParameterValue -match=col,ElementName=*Q2 $outputFile -end  &
    update idletasks
}  -contextHelp "Plots quadrupoles."

#---------------------------------------------------------------------------------------------

proc AdjustTunes {args} {
    APSParseArguments {lteFile beamline paramFile outputFile Qx Qy knobFile abortFile tol}
    
    set command "calculateAdjustTunes \
		   -lteFile $lteFile \
		   -beamline $beamline \
		   -knobFile $knobFile \
		   -outputFile $outputFile \
		   -Qx $Qx \
		   -Qy $Qy \
		   -tol $tol"
    if [string length $paramFile] {append command " -paramFile $paramFile "}

    if [catch {APSExecLog .tuneAdjust \
		   -lineLimit 2048 -width 120 \
		   -name "Adjusting tunes..." \
		   -unixCommand $command} pid] {
	APSSetVarAndUpdate status "Error running locoFitting: $pid"
    }
}
    
#---------------------------------------------------------------------------------------------

foreach option [array names sensitiveWidgets] {
    set $option 0
    DisableWidgets -option $option
}

set wd [exec pwd]
set lteFile /home/helios/oagData/sr/lattices/default/aps.lte
set knobFile /home/helios/oagData/sr/knobs/tune/lattices/default/tune.cokn
set beamline RING
set paramFile ""
set outputFile $wd/tuneAdjust.param
set Qx 95.17
set Qy 36.17
set tol 0.001
set twiFile apsTune.twi
