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

# $Log: not supported by cvs2svn $
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)]
APSStandardSetup

# 
# This script changes the x' and y' steering setpoints for a specified sector
# A filename must be supplied so the script can keep track of the initial values
# of the BPM setpoints.  The caller-specified setpoints are all relative to these
# initial values.
#

set usage "usage: setBMteering -sector <sector> -reference <filename> -withAngle <1|0> -tagList \"xPos yPos \[xSlope ySlope\]\" -valueList \"<mm> <mm> \[<urad> <urad>\]\""
set sector 0
set reference ""
set angle 0
set position 1
set tagList ""
set valueList ""

set args $argv
if {[APSStrictParseArguments {angle position sector reference tagList valueList}] || \
        [llength $tagList]!=[llength $valueList] || ![string length $reference]} {
    puts stderr $usage
    exit 1
}

if {$position && $angle} {
    set knownTagList [list xPos yPos xSlope ySlope]
} elseif $position {
    set knownTagList [list xPos yPos]
} elseif $angle { 
    set knownTagList [list xSlope ySlope]
} else {
    puts stderr "Error: both angle and position are zero!"
    exit 1
}
if {[llength $tagList]!=[llength $knownTagList]} {
    puts stderr "The tag list should be \"$knownTagList\"]"
    exit 1
}

foreach tag $tagList value $valueList {
    if [lsearch -exact $knownTagList $tag]==-1 {
        puts stderr "Error: Unknown tag $tag given.  Known tags are $knownTagList"
        exit 1
    }
    set $tag $value
}

set pvList [list S${sector}B:P4:ms:x:SetpointAO S${sector}B:P4:ms:y:SetpointAO S${sector}B:P3:ms:x:SetpointAO S${sector}B:P3:ms:y:SetpointAO]

set dx 0.0
set dy 0.0
if $position  {
    set dx [expr $xPos/1.0e3]
    set dy [expr $yPos/1.0e3]
}

if {$angle} {
    set dx4 [expr -0.5015 * $xSlope/1e3]
    set dx3 [expr 2.8310 * $xSlope/1e3]
    set dy4 [expr -0.5015 * $ySlope/1e3]
    set dy3 [expr 2.8310 * $ySlope/1e3]
    set deltaList [list [expr $dx+$dx4] [expr $dy+$dy4] [expr $dx + $dx3] [expr $dy + $dy3]]
} else {
    set deltaList [list $dx $dy $dx $dy]
}

if ![file exists $reference] {
    # If $reference doesn't exist, we assume that we are to establish a new
    # reference point. 
    exec sddsmakedataset -pipe=out \
        -column=ControlName,type=string \
        -data=[join $pvList ,] \
        | sddscasr -pipe=in -save $reference
}

set origValList [exec sdds2stream -col=ValueString $reference]
set valueList ""
foreach val $origValList delta $deltaList {
    lappend valueList [expr $val + $delta]
}

exec sddsmakedataset -col=ControlName,type=string -data=[join $pvList ,] \
    -col=ValueString,type=string -data=[join $valueList ,] -pipe=out \
    | sddscasr -pipe=in -restore

# This is probably the right amount of time to wait. Allows for transfer of new setpoint
# to datapool and then convergence of correction.
after 4500
