#!/bin/sh  
# \
exec oagtclsh "$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)]
APSDebugPath
APSStandardSetup

set usage "usage: computeLatticeParameters \[-debug 1\] \[-localTest 1\] \[-offline 1 -modelName <dirname>\] \[-scrFile <filename>\]"

set args $argv
set debug 0
set localTest 0
set offline 0
set scrFile ""
set modelName ""
APSParseArguments {debug localTest offline scrFile modelName}
if $offline {
    if ![string length $modelName] {
        puts stderr $usage
        exit
    }
}

set scriptDataPath $OAGGlobal(OAGLoggingDirectory)/SRLatticeParameters
if $offline {
    set modelPath $modelName
    if ![file exists $modelPath] {
        puts stderr "Wrong model directory name: $modelPath"
        exit
    }
} else {
    set modelPath $OAGGlobal(SRCalibratedModelsDirectory)/default
}

if $localTest {
    set scriptDataPath .
}

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

proc CalculateChromaticities {args} {
    global debug scriptDataPath modelPath xrefFile BRhoPVName beamEnergy OAGGlobal offline scrFile
    set tmpRoot /tmp/[APSTmpString]-computeLatParam

    if ![string length $scrFile] {
        #--- Making scr-like file with sextupoles...
        if [catch {exec cavget -list=S -range=beg=1,end=40 -list=A:S1,A:S2,A:S3,A:S4,B:S3,B:S2,B:S1 \
                     -list=:CurrentAO -labeled} currentList] {
            return -code error $sextValueList
        }
        set N [llength $currentList]
        if {$N != 560} {return -code error "cavget: Less than 280 sextupoles returned."}
        for {set i 0} {$i <$N} {incr i 2} {
            lappend controlNameList [lindex $currentList $i]
            lappend valueStringList [lindex $currentList [expr $i + 1]]
        }
        exec sddsmakedataset -pipe=out -col=ControlName,type=string -data=[join $controlNameList ,] \
          -col=ValueString,type=string -data=[join $valueStringList ,] \
          -col=ParameterValue,type=double -data=[join $valueStringList ,] \
          | sddsprocess -pipe=in $tmpRoot.sext -print=para,SnapshotDescription,Dummy
        lappend deleteFiles $tmpRoot.sext
        set scrFile $tmpRoot.sext
    }

    #--- Making KnL file from scr file...
    set outputFileDir [file dirname $tmpRoot]
    set outputFileRoot [file tail $tmpRoot]
    if [catch {APSMpMagnetKnLValues -SCRFile $scrFile -xrefFileList $xrefFile \
                 -energy $beamEnergy -BRhoPVName $BRhoPVName \
                 -outputFileDir $outputFileDir \
                 -outputFileRoot $outputFileRoot \
                 -statusCallback "APSSetVarAndUpdate status" \
                 -abortVariable abortRun} result] {
	return -code error "APSMpMagnetKnLValues: $result"
    }
    lappend deleteFiles $tmpRoot.KnL

    #--- Applying sextupole fudge factors (changes X by +0.4 and Y by -0.6 units):
    set allSextFactor 1.0025
    set s2Factor 0.9925
    exec sddsprocess $tmpRoot.KnL $tmpRoot.KnL.1 -nowarning \
	"-scan=col,SextFamily,ElementName,%lf,edit=e 1b 1k a 10d 1y" \
	"-redef=col,ParameterValue,SextFamily 2.0 == ? ParameterValue $s2Factor * : ParameterValue $allSextFactor * \$"
    exec mv $tmpRoot.KnL.1 $tmpRoot.KnL
    lappend deleteFiles $tmpRoot.KnL~

    #--- Make elegant files for chromaticity run:
    set lteFile $modelPath/aps.lte
    if [catch {exec sdds2stream $modelPath/requiredParamFiles.sdds -col=filename} fileList] {
	return -code error "Error reading requiredParamFiles.sdds file: $fileList"
    }
    set paramFileList ""
    foreach filename $fileList {
	lappend paramFileList $modelPath/$filename
    }
    lappend paramFileList $tmpRoot.KnL
    set eleFile $scriptDataPath/computeLatticeParametersTemplate.ele
    set twiFile $tmpRoot.twi
    set beamline RING
    lappend deleteFiles $twiFile

    #--- Running elegant:
    set beamEnergyMeV [expr $beamEnergy * 1e3]
    set elelogFile  $tmpRoot.elelog
    catch {file delete $elelogFile}
    if [catch {exec elegant $eleFile -macro=LTEFILE=$lteFile,BEAMLINE=$beamline,ENERGYMEV=$beamEnergyMeV,PARAMFILELIST=$paramFileList,TWIFILE=$twiFile > $elelogFile} result] {
        return -code error "elegant error (see file $elelogFile): $result"
    }
    lappend deleteFiles $elelogFile
    set chromX [exec sdds2stream $twiFile -para=dnux/dp]
    set chromY [exec sdds2stream $twiFile -para=dnuy/dp]

    if !$debug {eval file delete $deleteFiles}
    return [list $chromX $chromY]
}

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

set BRhoPVName S:BRhoCALC
if [catch {exec cavget -list=$BRhoPVName} Brho] {
    set beamEnergy 7
} else {
    set beamEnergy [exec rpnl "$Brho c_mks * 1e9 /"]
}
set xrefFile /home/helios/oagData/sr/magnets/sext/SSP_xref.sdds

#--- Read sextupoles and calculate chromaticity:
if [catch {CalculateChromaticities} chromList] {
    puts stderr "CalculateChromaticites: $chromList"
    exit 1
}

if {!$offline && !$localTest} {
    #--- Write chromaticity to PVs:
    if [catch {exec cavput -list=SR:CompLatParam: \
                 -list=ChromX=[lindex $chromList 0],ChromY=[lindex $chromList 1] -pend=5} result] {
        puts stderr "Error writing to chromaticity PVs: $result"
        exit 1
    }
} else {
    puts stdout "SR:CompLatParam:ChromX [format %.5f [lindex $chromList 0]] SR:CompLatParam:ChromY [format %.5f [lindex $chromList 1]]"
}

exit 0
