#!/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 applicationName SRMaketuneAdjustParamFile
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 "Pair of quad families:" \
	 -textVariable quadFamilyList -width 70
APSLabeledEntry .outputRoot -parent $parent \
	 -label "Output rootname:" \
	 -textVariable outputRoot -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 \
		   -quadFamilyList $quadFamilyList \
		   -outputRoot $outputRoot \
		   -Qx $Qx \
		   -Qy $Qy \
		   -tol $tol
    } result] {
        APSSetVarAndUpdate status "AdjustTunes: $result"
    }
    update idletasks
}  -contextHelp "Adjusts tunes using \$quadFamilyList pai of quads."

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

APSButton .plot1 -parent $parent -text " Plot quads " -command {
    exec sddsplot -graph=symbol,connect \
		  -col=ElementName,ParameterValue -match=col,ElementName=*[lindex $quadFamilyList 0] $outputRoot.param -end \
		  -col=ElementName,ParameterValue -match=col,ElementName=*[lindex $quadFamilyList 1] $outputRoot.param -end  &
    update idletasks
}  -contextHelp "Plots quadrupoles changes."

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

proc AdjustTunes {args} {
    APSParseArguments {lteFile beamline paramFile outputRoot Qx Qy quadFamilyList tol}
    
    catch {file delete $abortFile}
    set command "makeTuneAdjustParamFile \
		   -lteFile $lteFile \
		   -beamline $beamline \
		   -quadFamilyList \"$quadFamilyList\" \
		   -outputRoot $outputRoot \
		   -targetTunes \"$Qx $Qy\" \
		   -tol $tol -removeKnobFiles 1"
    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 quadFamilyList "Q1 Q2"
set beamline RING
set paramFile ""
set outputRoot $wd/tuneAdjust
set Qx 95.17
set Qy 36.17
set tol 0.0001
