#!/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)]

set hostname [exec hostname -s]
set applicationName SRLocalImpedanceMeasurement@$hostname
APSApplication . -name $applicationName -version 2 \
    -overview {This application measures and local impedance using orbit bumps and processes the results. Implemented by V. Sajaev}

set status ""
APSScrolledStatus .status -parent .userFrame -textVariable status -width 130 -height 12

#-------------------------------------------------------------------------------------------------------------------
proc PlotRawData {args} {
    global msSuff
    APSParseArguments {rootname bucketList correctOrbitDrift mode}
    switch -exact $mode {
	current {set xCol CorrectorCurrent}
	time {set xCol Time}
    }
    if $correctOrbitDrift {
	foreach bucket $bucketList {
	    exec sddsplot \
		"-topline=Raw orbit measurements -- bucket $bucket" "-title=Orbit drift (slope) removed" \
		-sep=2 -groupby=namestring -graph=sym,vary=subt,fill \
		-col=$xCol,S*P\[34\]*:$msSuff:y $rootname-bucket-$bucket.raw "-leg=spec=Raw data" \
		-col=$xCol,S*P\[34\]*:$msSuff:y $rootname-bucket-$bucket.driftCorrected "-leg=spec=Slope corrected" &
	}
    } else {
	foreach bucket $bucketList {
	    exec sddsplot \
		"-topline=Raw orbit measurements -- bucket $bucket" -graph=sym,vary=subt,fill -sep \
		-col=$xCol,S*P\[34\]*:$msSuff:y $rootname-bucket-$bucket.raw "-leg=spec=Raw data" &
	}
    }
}
#-------------------------------------------------------------------------------------------------------------------
proc PlotSlopes {args} {
    global bucketList
    APSParseArguments {rootname}
    set plotString1 ""
    set plotString2 ""
    set plotString3 ""
    foreach bucket $bucketList {
	append plotString1 " -col=s,Slope -graph=sym,connect $rootname-bucket-$bucket.raw.slopeVsBump.summ -col=s,Slope,SlopeSigma -graph=err $rootname-bucket-$bucket.raw.slopeVsBump.summ \"-topline=Slope (orbit Vs bump) bucket $bucket\" \"-title=No drift correction\" -end "
	append plotString2 " -col=s,Slope -graph=sym,connect $rootname-bucket-$bucket.driftCorrected.slopeVsBump.summ -col=s,Slope,SlopeSigma -graph=err $rootname-bucket-$bucket.driftCorrected.slopeVsBump.summ \"-topline=Slope (orbit Vs bump) bucket $bucket\" \"-title=Bunch 0 drift correction\" -end "
	append plotString3 " -graph=sym,con=subt,vary=subt,fill -col=s,SlopeSigma $rootname-bucket-$bucket.raw.slopeVsBump.summ \"-leg=spec=No drift corr\" -col=s,SlopeSigma $rootname-bucket-$bucket.driftCorrected.slopeVsBump.summ \"-leg=spec=With drift corr\" \"-topline=Comparison of slope fit error\" \"-title=Bucket $bucket\" -end "
    }
    eval exec sddsplot $plotString1 &
    eval exec sddsplot $plotString2 &
    eval exec sddsplot $plotString3 &
}
#-------------------------------------------------------------------------------------------------------------------
proc PlotOrbitDiff {args} {
    APSParseArguments {rootname bucketList nBumps}
    set plotString ""
    for {set i 1} {$i < $nBumps} {incr i} {
	set plotFiles ""
	foreach bucket $bucketList {
	    set filename $rootname-bump-$i-bucket-$bucket.diff
	    lappend plotFiles $filename
	}
	append plotString " -col=BPMName,OrbitDiff $plotFiles \"-topline=Difference between bumps $i and 0\" -end "
    }
    eval exec sddsplot -graph=line,vary \"-leg=file,edit=%@$rootname-bump-@@ 2d %@.diff@@\" \"-title=Raw orbit differences\" \
	$plotString &
    exec sddsplot -graph=line,vary -split=page -sep -same -topline=@PlotTopline -title=@PlotTitle \
	-col=s,Orbit* $rootname.orbit.fit &
}
#---------------------------------------------------------------------------------------------------------------
proc MeasureBumps {args} {
    global msSuff
    set abortVariable ""
    set orbitAveragingSteps 10
    APSParseArguments {alwaysRunDP idNumber bumpCurrentList bucketList measRoot abortVariable bumpConfig bumpType orbitAveragingSteps}

    if [string length $abortVariable] {
        global $abortVariable
        set $abortVariable 0
    }
    # this will prevent BSP-100 iocs from slowing down when there is a partial beam loss.
    APScavput -list=SR:DumpRecorder:Inhibit=1
#    catch {exec mplayer -quiet /home/helios/SR/Music/ipanema.mp3 > /dev/null &} musicPID
#    APSSetVarAndUpdate status "Calming music is launched as pid $musicPID"
    set waitDatapool 3
    set waitOrbit 3
    switch -exact $msSuff {
	msAve {set waitADCdelay 5; set orbMonInterval 1.0}
	ms {set waitADCdelay 2; set orbMonInterval 0.5}
    }
# I had to change family from B:V2 because in V1-V2-V3 set, v2 was small for position bump.
    set corrFamily B:V1
    set idNumber1 [expr $idNumber + 1]
    switch $bumpType {
        AngleBump -
        PositionBump { }
        default {
            APSSetVarAndUpdate status "Bump type $bumpType not recognized."
            return -code error
        }
    }
    set coefficientsDir /home/helios/oagData/sr/orbitControllaw/lattices/default/$bumpConfig
    if ![file exist $coefficientsDir/coefficients] {
        APSSetVarAndUpdate status "Can't find file \"coefficients\" in $coefficientsDir"
        return -code error
    }
    # check whether rootname already exists.
    if [file exists $measRoot-bump-0-bucket-0.sdds] {
        APSSetVarAndUpdate status "File already $measRoot-bump-0-bucket-0.sdds exists. Change rootname."
        return
    }
    #--- Save configuration file:
    exec sddsmakedataset $measRoot.config \
	-col=VariableName,type=string -data=measRoot,idNumber,bumpCurrentList,bucketList,alwaysRunDP,bumpType,msSuff \
	-col=VariableValue,type=string -data=$measRoot,$idNumber,$bumpCurrentList,$bucketList,$alwaysRunDP,$bumpType,$msSuff

    #--- Restore unconditionally the adcDelay of SBPMs. This avoids a lot of problems when the GUI or loops
    #--- are aborted and the sate of the bpms is unknown.
    exec sddsprocess /home/helios/oagData/SCR/snapshots/SBPMs/SBPMs-Preferred.gz -pipe=out \
        -match=col,ControlName=S*:adcDelay \
        | sddscasr -pipe=in -restore
    #--- Make BPM monitor file:
    set pvList ""
    for {set i 1} {$i < 41} {incr i } {
        # removed P1 since it doesn't have a sum PV
	#--- Record both ms and msAve, but since the wait time between steps in the measurements is different for ms vs msAve,
	#--- msAve does not always have good data
	foreach bpmSuff [list A:P2 A:P3 A:P4 B:P5 B:P4 B:P3 B:P2 ] {
	    lappend pvList S${i}${bpmSuff}:msAve:y S${i}${bpmSuff}:ms:y S${i}${bpmSuff}:msAve:sy 
	}
    }
    exec sddsmakedataset bpm.mon -col=ControlName,type=string -data=[join $pvList ,]
    #--- Change epics update rate from 2 sec to 0.5 sec
    exec cavput -list=S -range=beg=1,end=40 -list=A:,B: -list=P3,P4 -list=:ms:y.SCAN=7

    set bumpCurrentPrevious 0
    set bumpCounter 0
    set fileList ""
    set waveformDir /home/helios/oagData/sr/orbitControllaw/waveforms
    if [catch {exec sddsprocess $coefficientsDir/coefficients -pipe=out \
                   -match=col,ControlName=*$corrFamily \
                   | sdds2stream -pipe -col=$bumpType } amplitude] {
        APSSetVarAndUpdate status "Error in determining $corrFamily amplitude of bump coefficients: $amplitude"
        return -code error
    }
    if {$amplitude == 0} {
        APSSetVarAndUpdate status "Error: The coefficient for $corrFamily is zero. Check file $coefficientsDir/coefficients"
        return -code error
    }
    # The reference delta waveform will have a coefficient of 1 A for B:V2
    set tmpRoot /tmp/[APSTmpString]
    if [catch {exec sddsxref $waveformDir/vcorrInfo.sdds $coefficientsDir/coefficients -pipe=out \
                   -match=DeviceName=ControlName -take=$bumpType -fillIn -nowarnings \
                   | sddsprocess -pipe "-redefine=col,Waveform,$bumpType $amplitude /" \
                   | sddsconvert -pipe=in -rename=par,DeltaWaveformPV=WaveformPV \
                   $tmpRoot.reference.delta} result] {
        APSSetVarAndUpdate status "Error in calculating reference delta waveform: $result"
        return -code error
    }
    foreach bumpCurrent $bumpCurrentList {
        APSSetVarAndUpdate status "Checking abort variable $abortVariable..."
        if {[string length $abortVariable] && [set $abortVariable]} {
            APSSetVarAndUpdate status "Abort command seen."
            APSSetVarAndUpdate status "You need to restore the correctors"
            set $abortVariable 0
            return -code ok
        }
        
	#--- Create bump:
	set currentDelta [expr $bumpCurrent - $bumpCurrentPrevious]
	if !$alwaysRunDP {
	    APSSetVarAndUpdate status "Starting datapool and ramping to bump current $bumpCurrent (current step $currentDelta)..."
	    #--- Create bump: Resume datapool:
	    APScavput -list=DP:S:OrbitControlLawYSDDS.SUSP=0 -pend=5
	} else {
	    APSSetVarAndUpdate status "Ramping to bump current $bumpCurrent (current step $currentDelta)..."
	}
	#--- Create bump: Ramp corrector:
        set stepSizeLimit 2
        set steps [format %.0f [expr abs($currentDelta)/$stepSizeLimit + 1]]
        if [catch {exec sddsprocess $tmpRoot.reference.delta $tmpRoot.delta \
                       "-redef=col,Waveform,Waveform $currentDelta * $steps /" \
                   } result ] {
            APSSetVarAndUpdate status "Error in calculating delta waveform from reference delta waveform: $result"
            return -code error
        }
        
        for {set i 1} {$i<=$steps} {incr i} {
            APSSetVarAndUpdate status "Step $i ..."
            if [catch {exec sddswput $tmpRoot.delta -pend=30} result] {
                APSSetVarAndUpdate status "Error ramping V-correctors: $result"
            }
            after 200
        }
        # is three seconds enough?
	after [expr $waitOrbit * 1000]
	if !$alwaysRunDP {
	    #--- Create bump: Suspend datapool:
	    APSSetVarAndUpdate status "Suspend datapool..."
            APScavput -list=DP:S:OrbitControlLawYSDDS.SUSP=1
	}

	#--- Measure orbit at different buckets:
	foreach bucket $bucketList {
            update
            if {[string length $abortVariable] && [set $abortVariable]} {
                APSSetVarAndUpdate status "Abort command seen."
                APSSetVarAndUpdate status "You need to restore the correctors"
                set $abortVariable 0
                return -code ok
            }
	    set filename $measRoot-bump-$bumpCounter-bucket-$bucket.sdds
	    APSSetVarAndUpdate status "Measuring orbit for ADC delay $bucket..."
	    #--- Change adc delay:
	    if [catch {APScavput -list=S -range=begin=1,end=40 -list=A,B -list=:P3,:P4 \
                           -list=:adcDelay=$bucket -delta=factor=1 -pend=5} result ] {
                APSSetVarAndUpdate status "APScavput: $result"
                return -code error $result
            }
	    #--- Force restart of all averaging:
	    if [catch {APScavput -list=S -range=begin=1,end=40 -list=A,B -list=:position:Force=1 -pend=5} result] {
                APSSetVarAndUpdate status "APScavput: $result"
                return -code error $result
	    }

	    after [expr $waitADCdelay * 1000]
	    if [catch {exec sddsmonitor bpm.mon $filename -step=$orbitAveragingSteps -interval=$orbMonInterval} result ] {
                APSSetVarAndUpdate status "sddsmonitor: $result"
                return -code error $result
            }
	    if [catch {exec sddsprocess $filename "-redef=para,BumpCurrent,$bumpCurrent" -nowarning} result ] {
                APSSetVarAndUpdate status "sddsprocess: $result"
                return -code error $result
            }

	    file delete ${filename}~
	    #--- Record bunch current monitor data (old and new):
	    if [catch {exec sddswmonitor $measRoot-bump-$bumpCounter-bucket-$bucket.bunchMonWvfrm -pvnames=BNCHI:BunchCurrentWF,SR1:BCM:BunchI_WF} result ] {
                APSSetVarAndUpdate status "sddswmonitor: $result"
                return -code error $result
            }

	    #--- Change adc delay back:
            # need to restore the delay from SBPMs if something bad happens.
	    if [catch {APScavput -list=S -range=begin=1,end=40 -list=A,B -list=:P3,:P4 \
                           -list=:adcDelay=$bucket -delta=factor=-1 -pend=5} result ] {
                APSSetVarAndUpdate status "APScavput: $result"
                return -code error $result
            }
	    after 500
	    lappend fileList $filename
	}
	
	set bumpCurrentPrevious $bumpCurrent
	incr bumpCounter
    }
    set nBumps $bumpCounter


    APSSetVarAndUpdate status "Done."
#    catch {kill $musicPID}
}
#-------------------------------------------------------------------------------------------------------------------

set parent .userFrame
APSFrame .meas -parent $parent -label "Measurements"
set w $parent.meas.frame

APSLabeledEntry .workDir -parent $w \
    -label "Working directory: " \
    -textVariable workDir -width 70 \
    -contextHelp "Directory for measurements and processing."
APSLabeledEntry .measRoot -parent $w \
    -label "Measurement rootname:" \
    -textVariable measRoot -width 40 \
    -contextHelp "Measurement files will have this rootname."
APSButton .measureBumps -parent $w.measRoot -text "Read Config" -size small -command {
    set varList [exec sdds2stream $workDir/$measRoot.config -col=VariableName]
    set valueList [exec sdds2stream $workDir/$measRoot.config -col=VariableValue]
    foreach var $varList value $valueList {set $var $value}
} -contextHelp "Populates variables below with values from file rootname.config."

APSLabeledEntry .idNumber -parent $w \
    -label "ID number:" \
    -textVariable idNumber -width 40 \
    -contextHelp "Number of ID straight section to measure. Do not put a leading zero, as this number is used to match with a lattice element in elegant matrix."
APSLabeledEntry .configBump -parent $w \
    -label "Configuration of the bump:" \
    -textVariable bumpConfig -width 40 \
    -contextHelp "Configuration in /home/helios/oagData/sr/orbitControllaw/lattices/default that contains the file \"coefficients\" for making the angle an dposition bumps."
APSRadioButtonFrame .bumpType -parent $w \
    -label "Bump type                                        " \
    -variable bumpType -valueList {PositionBump AngleBump} \
    -buttonList {"Position" "Angle"} \
    -orientation horizontal \
    -commandList {{} {}} \
    -contextHelp "Select what kind of bump to generate to probe different part of the imperance."
APSLabeledEntry .bucketList -parent $w \
    -label "List of filled adc buckets:" \
    -textVariable bucketList -width 40 \
    -contextHelp "List of filled buckets ADC buckets that will be measured. If something bad happens to the adc delay values during the measurement you have to recover from the SBPMs file."
APSLabeledEntry .corrList -parent $w \
    -label "Corrector bump current list:" \
    -textVariable bumpCurrentList -width 40 \
    -contextHelp "List of corrector currents that will be used to generate bumps."
APSRadioButtonFrame .dpOn -parent $w \
    -label "Keep datapool running during measurements?       " \
    -variable alwaysRunDP -valueList {1 0} \
    -buttonList {"yes\, run" "no\, suspend"} \
    -orientation horizontal \
    -commandList {{} {}} \
    -contextHelp "Presently, we think it's a bad idea to run it during the measurements, so don't do it."
APSRadioButtonFrame .msSuff -parent $w \
    -label "BPM PV suffix?                                   " \
    -variable msSuff -valueList {msAve ms} \
    -buttonList {msAve ms} \
    -orientation horizontal \
    -commandList {{} {}} \
    -contextHelp "msAve pv type is average over 1 second, ms ps type is average for 0.1 second. Measurement wait times change accordingly."
APSLabeledEntry .averaging -parent $w \
    -label "Number of orbits to average:" \
    -textVariable orbitAveragingSteps -width 40 \
    -contextHelp "How many orbits to average. One second per acquisition."

APSButton .measureBumps -parent $w -text "Measure" -command {
    if [catch {MeasureBumps -alwaysRunDP $alwaysRunDP -idNumber $idNumber \
                   -bumpCurrentList $bumpCurrentList -bucketList $bucketList \
                   -measRoot $measRoot -abortVariable AbortBumpScan \
                   -bumpType $bumpType -bumpConfig $bumpConfig \
                   -orbitAveragingSteps $orbitAveragingSteps \
               } result] {
	APSSetVarAndUpdate status "MeasureBumps: $result"
    }
} -contextHelp "Performs orbit bump measurements."
set AbortBumpScan 0
APSButton .abort -parent $w -text Abort -command \
    {APSSetVarAndUpdate status "Aborting..."; set AbortBumpScan 1}

APSFrame .process -parent $parent -label "Processing"
set w $parent.process.frame

set labelList [list "Measurement processing" "Response calculation"]
set commandWidgetList [APSTabFrame .actionTabs -parent $w -width 750 -height 230 \
			   -labelList $labelList -label "" -tabPosition n]
set wTab0 [lindex $commandWidgetList 0]
set w $wTab0

APSLabeledEntry .outputRoot -parent $w \
    -label "Processing output rootname:           " \
    -textVariable outputRoot -width 40 \
    -contextHelp "Processing results will have this rootname."
APSLabeledEntry .badBpms -parent $w \
    -label "List of bad BPMs:" \
    -textVariable badBmpList0 -width 40 \
    -contextHelp "List of bad BPMs known in advance. Program will perform its own analysis too trying to remove as many noisy BPMs as possible."
APSRadioButtonFrame .correctDrift -parent $w \
    -label "Correct for orbit drift?              " \
    -variable correctOrbitDrift -valueList {0 1 2} \
    -buttonList {no "yes-zero bump based" "yes-bunch 0 based"} \
    -orientation horizontal \
    -commandList {{} {} {}} \
    -contextHelp "For zero bump based: looks at orbits with zero corrector current, fits straight line between them, removes the orbit drift based on this line; treats every bump/every bunch separately.\n\nFor bunch 0 based: for every bump, subtracts position of bunch 0 from positions of other bunches; supposedly better."
APSRadioButtonFrame .driftFilter -parent $w \
    -label "Use orbit drift filter?               " \
    -variable useOrbitDriftFilter -valueList {0 1} \
    -buttonList {no yes} \
    -orientation horizontal \
    -commandList {{} {}} \
    -contextHelp "When calculating orbit drifts, declare BPMs bad based on non-smoothness of the drift and removes them."

APSFrameGrid .grid -parent $w -yList {y1 y2 y3}
set w1 $w.grid.y1
set w2 $w.grid.y2
set w3 $w.grid.y3

APSButton .processCurrents -parent $w1 -text "Process currents" -command {
    set command "/home/oxygen/SAJAEV/APPS/LocalImpedanceBump/calibration -inputRoot $measRoot -outputRoot $workDir/$outputRoot.current -bumpNumber [llength $bumpCurrentList] -bucketList \"$bucketList\""
    APSSetVarAndUpdate status $command
    if [catch {APSExecLog .calibration -lineLimit 2048 -width 120 -name "Local impedance run window" \
		   -unixCommand "$command"} pid] {
	APSSetVarAndUpdate status "Error running calibration: $pid"
    }
} -contextHelp "Calculates beam current for every bucket and every bump using calibration of sum signals. All BPMs are averaged. Takes a while. Creates files *.current.*"

APSButton .processBumps -parent $w1 -text "Process bumps" -command {
    APSSetVarAndUpdate status " "
    switch -exact $bumpType {
	PositionBump {set ItoOrbitmm $ItoOrbitmmPos}
	AngleBump {set ItoOrbitmm $ItoOrbitmmAng}
    }
    set command  "/home/oxygen/SAJAEV/oag/apps/src/tcltkapp/oagapp/processLocalImpedanceBumps -workDir $workDir -measRoot $measRoot \
                 -outputRoot $outputRoot -bucketList \"$bucketList\" -rmFile $rmFile -bumpType $bumpType \
		 -idNumber $idNumber -bumpCurrentList \"$bumpCurrentList\" -ItoOrbitmm $ItoOrbitmm -msSuff $msSuff -badBpmList0 \"$badBpmList0\" \
		 -correctOrbitDrift $correctOrbitDrift -useOrbitDriftFilter $useOrbitDriftFilter"
    APSSetVarAndUpdate status $command
    if [catch {APSExecLog .calibration -lineLimit 2048 -width 125 -name "Local impedance run window" \
		   -unixCommand "$command"} pid] {
	APSSetVarAndUpdate status "Error running calibration: $pid"
    }
} -contextHelp "Performs full processing."

APSButton .plotRaw1 -parent $w2 -text "Plot raw data\nvs bump" -command {
    if [catch {PlotRawData -rootname $workDir/$outputRoot -bucketList $bucketList \
		   -correctOrbitDrift $correctOrbitDrift -mode current} result] {
	APSSetVarAndUpdate status "PlotRawData: $result"
    }
} -contextHelp "Plots raw data vs corrector current with and without orbit drift subtraction."

APSButton .plotRaw2 -parent $w2 -text "Plot raw data\nvs time" -command {
    if [catch {PlotRawData -rootname $workDir/$outputRoot -bucketList $bucketList \
		   -correctOrbitDrift $correctOrbitDrift -mode time} result] {
	APSSetVarAndUpdate status "PlotRawData: $result"
    }
} -contextHelp "Plots raw data vs time with and without orbit drift subtraction."

APSButton .plotDiff -parent $w2 -text "Plot orbit differences" -command {
    set nBumps [llength $bumpCurrentList]
    if [catch {PlotOrbitDiff -rootname $workDir/$outputRoot -bucketList $bucketList -nBumps $nBumps} result] {
	APSSetVarAndUpdate status "PlotOrbitDiff: $result"
    }
} -contextHelp "Plots raw data with and without orbit drift subtraction."

APSButton .plotSum -parent $w2 -text "Plot kick summary" -command {
    set plotString ""
    set filename $workDir/$outputRoot.summary
    foreach bucket $bucketList {
	append plotString " -col=BumpAmplitude,KickPerMA $filename -filter=col,BucketNumber,$bucket,$bucket \"-leg=spec=Bucket $bucket\" "
    }
    eval exec sddsplot -graph=sym,con=subt,vary=subt $plotString -axes &
} -contextHelp "Plots raw data with and without orbit drift subtraction."

APSButton .plotSlopes -parent $w3 -text "Plot orbit vs bump slopes" -command {
    if [catch {PlotSlopes -rootname $workDir/$outputRoot} result] {
	APSSetVarAndUpdate status "PlotSlopes: $result"
    }
} -contextHelp "Plots slopes of orbit vs bump for different buckets. With and without drift subtraction."

set wTab1 [lindex $commandWidgetList 1]
set w $wTab1

APSLabeledEntry .lteFile -parent $w \
    -label "LTE file name: " \
    -textVariable lteFile -width 65 \
    -contextHelp "LTE file for response calculation."
APSLabeledEntry .paramFile -parent $w \
    -label "Parameter file: " \
    -textVariable paramFile -width 65 \
    -contextHelp "Parameter file for response calculation. Could be empty."
APSLabeledEntry .idNumber -parent $w \
    -label "ID number:" \
    -textVariable idNumberRM -width 40 \
    -contextHelp "Number of ID straight section. Do not put a leading zero, as this number is used to match with a lattice element in elegant matrix."
APSLabeledEntry .rmFile -parent $w \
    -label "Output: Response file: " \
    -textVariable rmFile -width 65 \
    -contextHelp "Name of the resulting response file. Contains responses for one ID only."
APSButton .calcRM -parent $w -text "Calculate response" -command {
    APSSetVarAndUpdate status " "
    if [string length $paramFile] {set paramFileString " -paramFile $paramFile "} else {set paramFileString ""}
    set command  "/home/oxygen/SAJAEV/oag/apps/src/tcltkapp/oagapp/processLocalImpedanceBumps -mode calcResponse -workDir $workDir -lteFile $lteFile \
                 $paramFileString -rmFile $rmFile -idNumber $idNumberRM"
    APSSetVarAndUpdate status $command
    if [catch {APSExecLog .calibration -lineLimit 2048 -width 125 -name "Local impedance run window" \
		   -unixCommand "$command"} pid] {
	APSSetVarAndUpdate status "Error running calibration: $pid"
    }
} -contextHelp "Calculates orbit responses for a particular ID."


#--- This was for the old bump configuration:
# set ItoOrbitmm [expr 1.2 / 50]
#--- New position bump:
set ItoOrbitmmPos [expr 0.83 / 20]
#--- New angle bump:
set ItoOrbitmmAng [expr 1.05 / 60]



#set rmFile /home/oxygen/SAJAEV/APPS/LocalImpedanceBump/test.flvrm
set rmFile ID04-localImpResponse.rm
set lteFile $OAGGlobal(SRLatticesDirectory)/default/aps.lte
set paramFile /home/oxygen/SAJAEV/APPS/LocalImpedanceBump/tuneAdjust-rhb.param
set measRoot ID04-1
set idNumber 4
set idNumberRM 4
set bucketList [list 0 81 162 243]
set bumpCurrentList [list 0  -20 0 20  0]
set outputRoot test1
set badBpmList0 ""
set correctOrbitDrift 2
set useOrbitDriftFilter 1
set workDir [pwd]
set alwaysRunDP 0
set bumpType PositionBump
# for local bump coefficients
set bumpConfig v.2015-1201.03     
# for global orbit correction
set specialConfig v.2015-1201.09  
set orbitAveragingSteps 10
set msSuff msAve
APSSetVarAndUpdate status \
"==== Preparation sequence before the measurement:\n\
Read file /home/helios/SR/procedures/HowToMeasureLocalImpedance or use the following, which is only a summary:
0) Fill triangular pattern \n\
1) Correct both planes with defaultDP \n\
2) Abort datapool \n\
3) Change bpm triggering \"single bunch y only WITH commutation.\" \n\
4) Transfer rf bpms orbit error to offset (do both planes for completeness). It is strictly the offset that is changed.\n\
5) Save setpoints and offsets.\n\
6) Enter new setpoint and offset in SROrbitControllaw reference files.\n\
7) Launch $specialConfig (special for ID04) in datapool with 5 A max. corrector step.\n"

update

# Local Variables:
# mode: tcl
# End:
