proc APSGenerateLinacElegantParameters {args} {
    set apsLinacMagnetsDir /home/helios/oagData/linac/magnets/
    set latticeDir /home/helios/oagData/linac/lattices/

    set gun RG2
    set gunMomentum 2.8
    set BCMomentum 150.0
    set postL4Momentum [expr 150+(425-150)/2.0]
    set postL5Momentum 425.0
    set input ""
    set output ""
    if {[APSStrictParseArguments {gun gunMomentum BCMomentum postL4Momentum postL5Momentum input output}] || \
          ![string length $input] || ![string length $output]} {
        return -code error "APSGenerateLinacElegantParameters 1: Invalid arguments $argv"
    }

    if ![file exists $input] {
        return -code error "APSGenerateLinacElegantParameters 2: not found: $input"
    }
    if [file exists $output] {
        return -code error "APSGenerateLinacElegantParameters 3: file in use: $output"
    }
    set inputColumnList [APSGetSDDSNames -fileName $input]
    foreach requiredColumn {DeviceName Current} {
        if [lsearch -exact $inputColumnList $requiredColumn]==-1 {
            return -code error "APSGenerateLinacElegantParameters 4: $input lacks column $requiredColumn"
        }
    }
    
    set gunList [list RG1 RG2]
    if [lsearch -exact $gunList $gun]==-1 {
        return -code error "APSGenerateLinacElegantParameters 5: Invalid gun $gun. Valid choices: [join $gunList ,]"
    }
    set beamline ${gun}AndAll
    foreach position {gun BC postL4 postL5} {
        set momentum [set ${position}Momentum]
        if [expr $momentum<=0] {
            return -code error "APSGenerateLinacElegantParameters 6: ${position}Momentum is invalid ($momentum)"
        }
    }

    if ![file exists $latticeDir/linacMomentumProfileForParameterGeneration.ele] {
        return -code error "APSGenerateLinacElegantParameters 7: not found: $latticeDir/momentumProfile.ele"
    }

    set tmpRoot /tmp/[APSTmpString]
    if {[catch {exec elegant $latticeDir/linacMomentumProfileForParameterGeneration.ele \
                  -macro=latticeFile=$latticeDir/lattice-2025-0121.lte,beamline=$beamline \
                  -macro=latticeDir=$latticeDir \
                  -macro=p0=$gunMomentum,pPostL2=$BCMomentum,pPostL4=$postL4Momentum,pPostL5=$postL5Momentum \
                  -macro=rootname=$tmpRoot} result] || ![file exists $tmpRoot.done]} {
        return -code error "APSGenerateLinacElegantParameters 8: $result"
    }

    set partsList ""
    # Special handling for alpha magnets if present
    if [catch {exec sddsprocess $input -pipe=out -match=col,DeviceName=*LFA* -nowarning \
                 | sddsxref -pipe $apsLinacMagnetsDir/crossReference.sdds -match=DeviceName -take=ElementName -nowarning \
                 | sddsxref -pipe $tmpRoot.cen -match=ElementName -take=pCentral -nowarning \
                 | sddsprocess -pipe=in $tmpRoot.alpha1 -nowarning \
                 "-print=column,ExcitationFile,$apsLinacMagnetsDir/%s.excitation,ElementName"} result] {
        return -code error "APSGenerateLinacElegantParameters 9: $result"
    }
    if [expr [exec sdds2stream -rows=bare $tmpRoot.alpha1]!=0] {
        if [catch {exec sddsinterpset $tmpRoot.alpha1 -pipe=out \
                 -data=fileColumn=ExcitationFile,interpolate=B1,functionOf=Current,column=Current \
                 | sddsprocess -pipe=in -nowarning $tmpRoot.alpha \
                 -print=col,ElementParameter,X_MAX \
                 "-define=col,ParameterValue,pCentral B1 / sqrt 0.0750498 *"} result] {
            return -code error "APSGenerateLinacElegantParameters 10: $result"
        }
        lappend partsList $tmpRoot.alpha
    }
    file delete $tmpRoot.alpha1

    if [catch {exec sddsprocess $tmpRoot.paramOpt $tmpRoot.rfParam -match=col,ElementType=RFCA} result] {
        return -code error "APSGenerateLinacElegantParameters 11: $result"
    }
    lappend partsList $tmpRoot.rfParam

    if [catch {exec sddsprocess $tmpRoot.paramOpt -pipe=out -match=col,ElementType=*QUAD \
                 -match=col,ElementParameter=L \
                 | sddsbreak -pipe -change=ElementName \
                 | sddsprocess -pipe -process=ParameterValue,count,NSlices \
                 -process=ParameterValue,sum,LSum -process=ElementName,first,%s \
                 | sddscollapse -pipe=in $tmpRoot.lengths} result] {
        return -code error "APSGenerateLinacElegantParameters 12: $result"
    }

    if [catch {exec sddsprocess $tmpRoot.paramOpt -pipe=out \
                 -match=col,ElementType=*QUAD -match=col,ElementParameter=L \
                 | sddsxref -pipe $tmpRoot.cen -match=ElementName -take=pCentral \
                 | sddsbreak -pipe -change=ElementName \
                 | sddsprocess -pipe -process=pCentral,ave,%sAve -process=ElementName,first,%s \
                 | sddscollapse -pipe \
                 | sddsxref -pipe $apsLinacMagnetsDir/crossReference.sdds -match=ElementName \
                 -take=DeviceName,Sign -nowarning \
                 | sddsxref -pipe $input -nowarning -match=DeviceName -take=Current \
                 | sddsxref -pipe $tmpRoot.lengths -match=ElementName -take=LSum \
                 | sddsprocess -pipe \
                 "-print=column,ExcitationFile,$apsLinacMagnetsDir/%s.excitation,ElementName" \
                 | sddsinterpset -pipe \
                 -data=fileColumn=ExcitationFile,interpolate=IntegratedStrength,functionOf=Current,column=Current \
                 | sddsprocess -pipe=in $tmpRoot.K1 \
                 -print=column,ElementParameter,K1 \
                 "-define=column,H,pCentralAve mev * 1e6 * c_mks /,units=T*m" \
                 "-define=col,ParameterValue,IntegratedStrength H / LSum / Sign *"} result] {
        return -code error "APSGenerateLinacElegantParameters 13: $result"
    }
    lappend partsList $tmpRoot.K1

    if [catch {eval exec sddscombine $partsList -merge -pipe=out \
                 -retain=col,pCentral*,ElementName,ElementParameter,ParameterValue,Current,ExcitationFile,IntegratedStrength \
                 | sddsprocess -pipe=in $output \
                 "{-match=col,ElementParameter=FIDUCIAL,!,ElementParameter=BODY_FOCUS_MODEL,!,&}"} result] {
        return -code error "APSGenerateLinacElegantParameters 14: $result"
    }

    eval file delete -force [glob $tmpRoot.*] 
}

