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

# $Log: not supported by cvs2svn $
# Revision 1.23  2010/04/21 19:38:54  shang
# added making ID steering links for P0 and P1s.
#
# Revision 1.22  2009/10/13 23:15:29  lemery
# Removed unused code that was commented out last change.
# Removes code for canted undulator correctors, since this is now
# covered by the general processing implemented last time.
#
# Revision 1.21  2009/10/08 20:12:54  sajaev
# Changed how corrector limits are created: from hard-coded to taking them from the corr status file. CU is unchanged till later.
#
# Revision 1.20  2009/10/08 17:21:31  sajaev
# Changed corrector limit from 148 to 147 A to test if this is the place I need to modify.
#
# Revision 1.19  2008/02/06 18:23:35  soliday
# Removed calls to setfacl because it is no longer needed.
#
# Revision 1.18  2007/01/04 21:55:26  shang
# changed the limits of CU correctors from +-3.5 A to +- 5.0 A.
#
# Revision 1.17  2005/09/26 21:56:56  shang
# changed the test value limits of C:H1, C:V1 to 3.5 A.
#
# Revision 1.16  2005/08/26 15:50:48  emery
# Set number singular values to 3 per plane for CU steerin irm.
# (Was only 2, which didn't have the proper mode to actually
# do the steering.)
# Added debugging output files for CU matrix calculations.
# Needs to be tested next run.
#
# Revision 1.15  2005/08/23 17:08:04  emery
# Added asdops to list of users that can generate the files.
# Added comments before the if statement for CU sectors.
#
# Revision 1.14  2005/08/22 20:59:04  emery
# Fixed the same problem in makeLocalSteeringConfigs:
# Fixed the logic of the "if" statement for CU type steering.
# All non-CU cases were skipped. Also when CU matrices is selected,
# the value of lattice variable was not used but the
# value of "default" was used.
#
# Revision 1.13  2005/07/07 21:28:12  emery
# Added users to setfacl command
#
# Revision 1.12  2005/04/06 06:13:00  emery
# Added procedure ComposeMatrix to create a large x-y
# matrix from matrices in x and y only.
# Creates rmFF matrices for CU steering.
# Still need to create a FFdefs file.
#
# Revision 1.11  2005/03/17 20:05:04  emery
# Added canted undulator steering matrices
#
# Revision 1.10  2004/06/13 18:16:09  emery
# added more users to write access to subdirectories, including asdops
#
# Revision 1.9  2003/10/03 23:05:44  emery
# Repalced file mkdir with exec mkdir and added explicit
# setfacl commands to get the right mask and permission
# for subdirectories.
#
# Revision 1.8  2003/10/03 17:02:40  emery
# Changed the way the zero block matrices are created so that different
# sets of H and V correctors are allowed.
#
# Revision 1.7  2002/02/28 00:16:53  emery
# Added creation of dynamic.defs and plain.defs to allow
# switching between using PSCU mode and Diag mode for correctors.
#
# Revision 1.6  2002/02/26 20:52:46  emery
# Added one SFB: too many for the corrector test file.
#
# Revision 1.5  2002/02/26 20:50:04  emery
# Added prefix SFB: to the right control name this time.
#
# Revision 1.4  2002/02/26 20:17:23  emery
# Make corrector PVs in irm of the SFB:* type
#
# Revision 1.3  2001/09/12 02:43:51  emery
# Removed [ ] braces from the lattice argument in the
# usage message to indicate that the lattice argument is
# mandatory.
#
# Revision 1.2  2001/02/02 16:11:28  emery
# Corrected directory where tests file is located.
# Removed extraneous cd $steeringType command where a deeper
# level of directory was created than indented.
#
# Revision 1.1  2000/10/27 02:09:22  emery
# First installation.
#

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 "makeLocalSteeringMatrices -lattice <latticeDir> -steeringType {CUUSP0|CUDSP0|P0|P1|P2|AM|BM|ID}\n  \[-useFreeePathMatrix \[0|1\]\]\n  \[-sourceList <sectorNumberList>\]\nwhere the reference matrix used will be taken from
/home/helios/oagData/sr/orbitControllaw/lattices/<latticeDir>/refMatrices/\[hv\].default\nif useFreePathMatrix is defined, the reference matrix will be\n/home/helios/oagData/sr/orbitControllaw/lattices/<latticeDir>/refMatrices/\[hv\].free.default"

proc ComposeMatrix {args} {
    set xMatrix ""
    set yMatrix ""
    set output ""
    set commonStringColumn "ControlName"
    APSParseArguments {xMatrix yMatrix output commonStringColumn}
    set tmpfile /tmp/[APSTmpString]
    #  combined matrix:
    #  x-data       y-zero
    #  x-zero       y-data
    #
    foreach plane {h v} coord {x y} otherCoord {y x} {
        # creates a zero matrix for right and left placement.
        if [catch {exec sddsconvert [set ${coord}Matrix] -pipe=out \
                     -retain=col,${commonStringColumn} \
                     | sddsxref -pipe [set ${otherCoord}Matrix] -noWarning \
                     -take=S* \
                     | sddsprocess -pipe=in $tmpfile.${otherCoord}.zero \
                     -redefine=col,%s,0,select=S* \
                 } result ] {
            return -code error "ComposeMatrix(0): $result"
        }
#        APSAddToTmpFileList -ID CombineMatrices -fileList $tmpfile.${coord}.zero
    }
    if [catch {exec sddscombine $xMatrix $tmpfile.x.zero $tmpfile.x.half -overWrite -merge
        exec sddscombine $yMatrix $tmpfile.y.zero $tmpfile.y.half -overWrite -merge
        exec sddsxref $tmpfile.x.half $tmpfile.y.half $output \
                 -match=${commonStringColumn} -take=S* -nowarning \
             } result ] {
        return -code error "ComposeMatrix(1): $result"
    }
#    APSAddToTmpFileList -ID CombineMatrices -fileList "$tmpfile.x.half $tmpfile.y.half"
#    APSDeleteTmpFileList -ID CombineMatrice
    return
}



proc MakeSectorMatrix {args} {
    set sector ""
    set steeringType ""
    APSParseArguments {sector steeringType}
    
    global refLatticeDir targetDir twissFile
    
    set controllawDir $targetDir/${steeringType}s/[format %02ld ${sector}]$steeringType
    set tmpRoot /tmp/[APSTmpString]
    set p1s 11.0
    set p2s 18.0
    set S0 0
    if {$steeringType=="BM"} {
        if [catch {exec sddsprocess $twissFile -pipe=out -match=col,ElementName=S${sector}B:M \
                     | sddsprocess -pipe -process=s,first,BMsourceStart \
                     | sdds2stream -pipe -par=BMsourceStart } S0] {
            return -code "Error obtaining BM source start point of $sector sector: $S0"
        }
    } else {
        if [catch {exec sddsprocess /home/helios/oagData/sr/IDs/sectors.sdds -filter=col,Sector,$sector,$sector \
                     $tmpRoot.$sector.distance } result] {
            #return -code error "MakeSectorMatrix0: $result"
            #not exist in the xray bpm files
            set p1distance 16.35
            set p2distance 20.09
        } else {
            set p1distance [exec sdds2stream -col=P1Distance $tmpRoot.$sector.distance]
            set p2distance [exec sdds2stream -col=P2Distance $tmpRoot.$sector.distance]
        }
    }
    
    foreach Plane {H V} plane {h v} coord {x y} {
        if [catch {exec sddsprocess $controllawDir/irm -pipe=out -match=col,ControlName=*${Plane}* \
                     | sddsconvert -pipe -retain=col,ControlName \
                     | sddsxref -pipe $twissFile -match=ControlName=ElementName -take=s -nowarnings \
                     | sddsprocess -pipe=in $tmpRoot.$plane.1 -process=s,first,s0 -process=s,last,s1 } result] {
            return -code error "MakeSectorMatrix1: $result"
        }
        set s0 [exec sdds2stream -par=s0 $tmpRoot.$plane.1]
        set s1 [exec sdds2stream -par=s1 $tmpRoot.$plane.1]
        set corrList [exec sdds2stream -col=ControlName $tmpRoot.$plane.1]
        #create corrector range error file
        set corrNameList ""
        set corrValueList ""
        foreach corr $corrList {
            lappend corrNameList ${corr}:RangeErrorCALC.HIHI
            lappend corrValueList 50
            lappend corrNameList ${corr}:RangeErrorCALC.LOLO
            lappend corrValueList -50
        }
        if [catch {exec sddsmakedataset -col=CorrName,type=string -data=[join $corrList ,] $controllawDir/$plane.corrName } result] {
            return -code error $result
        }

        if [catch {exec sddsmakedataset -pipe=out -col=ControlName,type=string -data=[join $corrNameList ,] \
                     -col=ValueString,type=string -data=[join $corrValueList ,] \
                     | tee $controllawDir/$plane.corr.range \
                     | sddscasr -pipe=in -save $controllawDir/$plane.corr.range.orig } result] {
            return -code error "Error getting corrector rangeError values: $result"
        }

        set ${plane}corrList($sector) $corrList
       
        if [catch {exec sddsprocess $twissFile -pipe=out -filter=col,s,$s0,$s1 -match=col,ElementType=MONI \
                     | tee $tmpRoot.$sector.bpms \
                     | sdds2stream -pipe -col=ElementName } bpmList] {
            return -code error "MakeSectorMatrix2: error getting in bound bpms for $sector: $bpmList"
        }
        set sList [exec sdds2stream -col=s $tmpRoot.$sector.bpms]
        set equationCmd ""
        set xrayBPMList ""
        set xrayBPMEqnList ""
        set i1 -1
        set i2 -1
        set p1 ""
        set p2 ""
        switch $steeringType {
            BM {
                if {$plane=="v"} {
                    set xrayBPMList [APSGetBMXRayBPMList -plane $plane]
                    set xrayBPMEqnList [APSGetBMXRayEqnList -plane $plane]
                    set p1 S${sector}BM:P1
                    set p2 S${sector}BM:P2
                }
            }
            default {
                set xrayBPMList [APSGetIDXRayBPMList -plane $plane]
                set xrayBPMEqnList [APSGetIDXRayEqnList -plane $plane]
                if {$steeringType=="CUUSP0"} {
                    set p1 S${sector}ID:P1
                    set p2 ""
                } elseif {$steeringType=="CUDSP0"} {
                    set p1 ""
                    set p2 S${sector}ID:P2
                } else {
                    set p1 S${sector}ID:P1
                    set p2 S${sector}ID:P2
                }
            }            

        }
        if [string length $p1] {
            set i1 [lsearch -exact $xrayBPMList $p1]
        }
        if [string length $p2] {
            set i2 [lsearch -exact $xrayBPMList $p2]
        }
        if {$i1>=0} {
            if ![string length $equationCmd] {
                lappend equationCmd sddsprocess -pipe
            }
            lappend bpmList $p1
            set eq1 [lindex $xrayBPMEqnList $i1]
            lappend equationCmd "-define=column,$p1,$eq1"
            if {$steeringType=="BM"} {
                lappend sList [expr $S0 + $p1s]
            } else {
                lappend sList [expr $sector * 27.6 + $p1distance]
            }
        }
        if {$i2>=0} {
            if ![string length $equationCmd] {
                lappend equationCmd sddsprocess -pipe
            }
            lappend bpmList $p2
            set eq2 [lindex $xrayBPMEqnList $i2]
            lappend equationCmd "-define=column,$p2,$eq2"
            if {$steeringType=="BM"} {
                lappend sList [expr $S0 + $p2s]
            } else {
                lappend sList [expr $sector * 27.6 + $p2distance]
            }
        }
        set refMatrix $refLatticeDir/${plane}.default
        
        set opt ""
        set pvList ""
        set pvList1 ""
        if [catch {exec sddsmakedataset -col=BPMName,type=string -data=[join $bpmList ,] \
                     -col=s,type=double -data=[join $sList ,] \
                     $tmpRoot.$sector.s } result] {
             return -code error "Making sector matrix3a: $result"
        }
        foreach bpm $bpmList {
            lappend pvList ${bpm}:ms:${coord}:SetpointAO
            lappend pvList1 ${bpm}:ms:${coord}:SetpointAO
            if ![string length $opt] {
                set opt -match=col,BPMName=$bpm
            } else {
                append opt ,BPMName=$bpm,|
            }
        }
        if [string length $equationCmd] {
            if [catch {eval exec sddstranspose $refMatrix -pipe=out \
                         | $equationCmd \
                         | sddstranspose -pipe \
                         -newColumnNames=OldColumnNames -oldColumnNames=BPMName \
                         | sddsprocess -pipe $opt \
                         | sddsconvert -pipe -del=col,s \
                         | sddsxref -pipe $tmpRoot.$sector.s -match=BPMName -nowarnings -take=s \
                         | sddssort -pipe -col=s \
                         | sddsconvert -pipe=in -retain=col,BPMName,[join $corrList ,] \
                         $controllawDir/$plane.steering.rm } result] {
                return -code error "Making sector matrix3a: $result"
            }
        } else {
            if [catch {eval exec sddsprocess $refMatrix -pipe=out $opt \
                         | sddsconvert -pipe -del=col,s \
                         | sddsxref -pipe $tmpRoot.$sector.s -match=BPMName -nowarnings -take=s \
                         | sddssort -pipe -col=s \
                         | sddsconvert -pipe=in -retain=col,BPMName,[join $corrList ,] \
                         $controllawDir/$plane.steering.rm } result] {
                return -code error "Making sector matrix3b: $result"
            }
        }
    }
    set tmpFiles [glob $tmpRoot.*]
    APSAddToTmpFileList -ID steering -fileList $tmpFiles
}

set args $argv
set lattice ""
set steeringType ""
set sourceList ""
set useFreePathMatrix 0
APSStrictParseArguments {lattice steeringType sourceList useFreePathMatrix}

if ![string length $lattice] {
    puts stderr $usage
    exit
}
if ![string length $steeringType] {
    puts stderr $usage
    exit
}
set twissFile /home/helios/oagData/sr/lattices/$lattice/aps.twi 
set refLatticeDir /home/helios/oagData/sr/orbitControllaw/lattices/${lattice}/refMatrices
set configDir /home/helios/oagData/sr/localSteering/configs
set targetDir /home/helios/oagData/sr/localSteering/lattices/${lattice}
cd $targetDir
set ext default
if $useFreePathMatrix {
    set ext free.default
}

# For canted undulator configurations. These configuration use P0 steering.
set CUdataDir /home/helios/oagData/sr/XAXSTF
if [catch {exec sddsprocess $CUdataDir/sectors.sdds -pipe=out \
             -filter=col,CUflag,1,1 "-filter=col,Sector,7,7,!" \
             | sdds2stream -pipe -col=Sector} CUlist] {
    return -code error "$CUlist"
}

set CUlist 

switch -regexp $steeringType {
    CUUSP0|CUDSP0|P0|P1|P2|AM|BM|ID {
        if ![file exists ${steeringType}s] {
            if [catch {exec mkdir -p ${steeringType}s} result] {
                puts stderr $result
                exit
            }
        }
    }
    default {
        puts stderr "makeLocalSteeringMatrices: Invalid source type: $steeringType\n$usage"
        exit
    }
}

if ![string length $sourceList] {
    switch $steeringType {
        ID -
        P0 -
        P1 {
            set sourceList [exec sdds2stream -col=Sector /home/helios/oagData/sr/IDs/sectors.sdds]
        }
        BM {
            set sourceList [exec sdds2stream -col=Sector /home/helios/oagData/sr/BMs/sectors.sdds]
        }
        default {
            #for CUUSP0|CUDSP0
            set sourceList $CUlist
        }
    }
}

#check modification times of the BMStatus/config.sdds against 
#sr/localSteering/configs/<XX>/<sector><XX>/config.x/y
set bpmStatusModifiedTime [file mtime /home/helios/oagData/sr/BPMStatus/config.sdds]

foreach i $sourceList {
    set i1 [expr $i + 1]
    if [expr $i1 == 41] {
        set i1 1
    }
    # Skips the loop for the CU type if the sector doesn't have CU undulator or 
    # magnets.
    if {[regexp {CU} $steeringType] && -1 == [lsearch $CUlist $i]} {
        continue
    }
    set subDir ${steeringType}s/[format %02ld $i]${steeringType}
    if {$steeringType=="ID"} {
        if ![file exist $subDir] {
            puts stderr "makeLocalSteeringMatrices: $subDir does not exist! should create the link (P0 or P1) first for ID $i first."
            exit 1
        }
        set linkDir [file readlink $subDir]
        if [regexp {P1} $linkDir] {
            set subConfigDir P1s/[format %02ld $i]P1
        } else {
            set subConfigDir P0s/[format %02ld $i]P0
        }
    } else {
        set subConfigDir $subDir
    }
    if ![file exists $subDir] {
        if [catch {exec mkdir -p $subDir} result ] {
            puts stderr "makeLocalSteeringMatrices: $result"
            exit
        }
        #        if [catch {exec /home/helios/OAG/bin/setFACL-oagPlus sr,emery,shang,borland,asdops,sajaev,schroedr $subDir} result ] {
        #            puts stderr "makeLocalSteeringMatrices: $result"
        #            exit
        #        }
    }
    
    # clean subdirectory
    catch {eval file delete [glob -nocomplain $subDir/*]}
    foreach plane {h v} {
        switch $plane {
            h {
                set coord x
                set otherPlane V
            }
            v {
                set coord y
                set otherPlane H
            }
            default {}
        }
        if [catch {exec sddsprocess ${configDir}/$subConfigDir/config.${coord} -pipe=out \
                     -nowarning \
                     -match=parameter,NameType=CorrectorNames \
                     | sdds2stream -pipe -column=Name} correctorNames] {
            return -code error "makeLocalSteeringMatrices(0): $correctorNames"
        }
        if [catch {exec sddsprocess ${configDir}/$subConfigDir/config.${coord} -pipe=out \
                     -nowarning \
                     -match=parameter,NameType=MonitorNames \
                     | sdds2stream -pipe -column=Name} monitorNames] {
            return -code error "makeLocalSteeringMatrices(1): $monitorNames"
        }
        set monitorNameMatchOption ""
        foreach item $monitorNames {
            if [string length $monitorNameMatchOption] {
                set monitorNameMatchOption "$monitorNameMatchOption,BPMName=$item,|"
            } else {
                set monitorNameMatchOption "-match=column,BPMName=$item"
            }
        }
        # add to bpm device name the coordinate used.
        if [regexp CU $steeringType] {
            set SVDOption -largestSingularValues=3
        } else {
            set SVDOption -largestSingularValues=4
        }
        if [catch {exec sddsconvert ${refLatticeDir}/${plane}.$ext -pipe=out \
                     -dele=para,* \
                     -retain=column,BPMName,[join $correctorNames ,] \
                     | sddsprocess -pipe $monitorNameMatchOption \
                     -nowarning \
                     | tee $subDir/rm.${coord} \
                     | sddspseudoinverse -pipe \
                     -oldColumnNames=ControlName \
                     -vmatrix=$subDir/v.${coord} \
                     -umatrix=$subDir/u.${coord} \
                     $SVDOption \
                     | sddsconvert -pipe=in $subDir/irm.${coord} \
                     -editname=col,S*,ei/:${coord}/ \
                 } result ] {
            return -code error "makeLocalSteeringMatrices(2): $result"
        }
        if [catch {exec sdds2stream $subDir/irm.${coord} \
                     -para=ConditionNumber} ConditionNumber($plane)] {
            return -code error "makeLocalSteeringMatrices(2a): $result"
        }
    }

    # combine two planes of matrices into one large matrix, filling in with zeroes.
    if [catch {ComposeMatrix -xMatrix $subDir/irm.x -yMatrix $subDir/irm.y -output $subDir/irm \
             } result] {
        return -code error "makeLocalSteeringMatrices(3): $result"
    }
    
    if [catch {exec sddsconvert $subDir/irm.x -nowarnings -edit=col,*:x,%/:x// 
        exec sddsconvert $subDir/irm.y -nowarnings -edit=col,*:y,%/:y// } result] {
        return -code error "makeLocalSteeringMatrices(3a): $result" 
    }
        
    APSAddToTmpFileList -ID localMatrices -fileList "$subDir/irm.x~ $subDir/irm.y~"

    # check ConditionNumber for > 1e10 which would be an indication
    # of a problem, or missing bpm
    set conditionLimit 1e10
    if {$ConditionNumber(h) > $conditionLimit && \
          $ConditionNumber(v) > $conditionLimit} {
        exec echo "Problem with condition number of matrix, so no files are kept." > $subDir/README
        # simply go to next source point.
        continue
    }

    # make bpm part of definitions files
    if [catch {exec sddsprocess ${configDir}/$subConfigDir/config.x $subDir/defs.bpm.x \
                 -match=col,Name=S*P* -noWarning \
                 -edit=col,SymbolicName,Name,ei/:x/ \
                 -edit=col,ControlName,Name,ei/:msAve:x:ErrorCC/ 
        exec sddsprocess ${configDir}/$subConfigDir/config.y $subDir/defs.bpm.y \
                 -match=col,Name=S*P* -noWarning \
                 -edit=col,SymbolicName,Name,ei/:y/ \
                 -edit=col,ControlName,Name,ei/:msAve:y:ErrorCC/
        exec sddscombine $subDir/defs.bpm.x $subDir/defs.bpm.y $subDir/defs.bpm \
                 -merge -overWrite\
             } result ] {
        return -code error "makeLocalSteeringMatrices(5): $result"
    }
    APSAddToTmpFileList -ID localMatrices -fileList "$subDir/defs.bpm.x $subDir/defs.bpm.y $subDir/defs.bpm"
    # make corr part of definitions files
    if [catch {exec sddsprocess ${configDir}/$subConfigDir/config.x $subDir/defs.corr.x \
                 -match=col,Name=S*H* -noWarning \
                 -print=col,SymbolicName,%s,Name 
        exec sddsprocess ${configDir}/$subConfigDir/config.y $subDir/defs.corr.y \
                 -match=col,Name=S*V* -noWarning \
                 -print=col,SymbolicName,%s,Name \
             } result ] {
        return -code error "makeLocalSteeringMatrices(6): $result"
    }
    APSAddToTmpFileList -ID localMatrices -fileList "$subDir/defs.corr.x $subDir/defs.corr.y"
    if [catch {exec sddscombine $subDir/defs.corr.x $subDir/defs.corr.y -pipe=out -merge \
                 | sddsprocess -pipe=in $subDir/defs.pscu.corr \
                 -edit=col,ControlName,Name,ei/:CurrentAO/  
        exec sddscombine $subDir/defs.corr.x $subDir/defs.corr.y -pipe=out -merge \
                 | sddsprocess -pipe=in $subDir/defs.diag.corr \
                 -edit=col,ControlName,Name,i/SFB:/ei/:CurrentAO/  \
             } result ] {
        return -code error "makeLocalSteeringMatrices(7): $result"
    }
    APSAddToTmpFileList -ID localMatrices -fileList "$subDir/defs.diag.corr $subDir/defs.pscu.corr"
    if [catch {exec sddscombine $subDir/defs.bpm $subDir/defs.pscu.corr \
                 $subDir/plain.defs -merge -overWrite \
                 -dele=para,* -retain=col,SymbolicName,ControlName 
        exec sddscombine $subDir/defs.bpm $subDir/defs.diag.corr \
                 $subDir/dynamic.defs -merge -overWrite \
                 -dele=para,* -retain=col,SymbolicName,ControlName \
             } result ] {
        return -code error "makeLocalSteeringMatrices(8): $result"
    }
    set corrStatusFile $subDir/status.corr
    exec sddscombine /home/helios/oagData/sr/HCorrectorStatus/config.sdds \
      /home/helios/oagData/sr/VCorrectorStatus/config.sdds \
      $corrStatusFile -merge -overWrite
    APSAddToTmpFileList -ID localMatrices -fileList $corrStatusFile
    if [catch {exec sddsconvert $subDir/defs.pscu.corr -pipe=out \
		   -retain=col,Name,ControlName \
		   | sddsxref -pipe $corrStatusFile -match=Name=DeviceName -take=CorrectorLimit \
		   | sddsprocess -pipe -print=col,ControlUnits,A \
		   "-define=col,MinimumValue,-1  CorrectorLimit *" \
		   "-define=col,MaximumValue,CorrectorLimit" \
		   | sddsconvert -pipe=in $subDir/ctests -del=col,CorrectorLimit,Name} result] {
        return -code error "makeLocalSteeringMatrices(9): $result"
    }

    APSAddToTmpFileList -ID localMatrices -fileList $subDir/ctests
    if [catch {exec sddsprocess $subDir/defs.bpm $subDir/btests \
                 -retain=col,ControlName \
                 -print=col,ControlUnits,mm \
                 -define=col,MinimumValue,-2 \
                 -define=col,MaximumValue,2 \
             } result ] {
        return -code error "makeLocalSteeringMatrices(10): $result"
    }
    APSAddToTmpFileList -ID localMatrices -fileList $subDir/btests
    if [catch {exec sddscombine $subDir/ctests $subDir/btests \
                 $configDir/extraPVs.test \
                 $subDir/tests -merge -overWrite \
                 -delete=para,* \
             } result ] {
        return -code error "makeLocalSteeringMatrices(11): $result"
    }
    # make rmFF for CU local steering
    if [regexp {CU} $steeringType] {
        set globalMainDir /home/helios/oagData/sr/orbitControllaw/
        set localMainDir /home/helios/oagData/sr/localSteering/
        set RTFBMainDir /home/helios/oagData/sr/rtfeedback/
        set outputRoot ${steeringType}s/[format %02ld $i]${steeringType}
        foreach plane {h v} coord {x y} {
            # rootname is abritrary here.
            if [catch {APSSRGenerateOrbCorrFiles -rootname hconfig -generate 1 \
                         -configFile $localMainDir/configs/$outputRoot/config.${coord} \
                         -plane ${plane} \
                         -referenceMatrix $globalMainDir/lattices/${lattice}/refMatrices/$plane.$ext \
                         -outputRoot $localMainDir/lattices/${lattice}/$outputRoot \
                         -compensationConfigFile $RTFBMainDir/lattices/default/${plane}.default/config \
                     } result ] {
                return -code error "makeLocalSteeringMatrices(12): $result"
            }
            if [catch {exec sddsprocess $localMainDir/lattices/${lattice}/$outputRoot/rmFF \
                         $localMainDir/lattices/${lattice}/$outputRoot/rmFF.${coord} \
                         -reedit=col,BPMName,ei/:${coord}/ \
                     } result ] {
                return -code error "makeLocalSteeringMatrices(13): $result"
            }
            file delete $localMainDir/lattices/${lattice}/$outputRoot/rmFF
        }
        if [catch {ComposeMatrix -xMatrix $localMainDir/lattices/${lattice}/$outputRoot/rmFF.x \
                     -yMatrix $localMainDir/lattices/${lattice}/$outputRoot/rmFF.y \
                     -output $localMainDir/lattices/${lattice}/$outputRoot/rmFF \
                     -commonStringColumn BPMName \
                 } result] {
            return -code error "makeLocalSteeringMatrices(14): $result"
        }
    }
    APSDeleteTmpFileList -ID localMatrices
    #make new steering matrices here
    if [catch {MakeSectorMatrix -sector $i -steeringType $steeringType } result] {
        puts stderr "Error in making $steeringType matrix for sector $sector: $result"
        exit 1
    }
}

#make ID steering links
if {$steeringType=="P0" || $steeringType=="P1"} {
    exec makeIDSteeringLinks -lattice $lattice
}


exit

# Local Variables:
# mode: tcl
# indent-tabs-mode: nil
# End:
