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

APSStandardSetup
set CVSRevisionAuthor "\$Revision: 1.23 $ \$Author: xiaoam $"
# $Log: not supported by cvs2svn $
# Revision 1.22  2011/05/30 14:22:29  lemery
# Added a wait time before waiting for ramping to set points.
# Arranged tests for existence of cw and ccw files. Insied the AC mode block
# replaced elseif with if so that both positive and negative set points
# can be set. Removed the block for 0-A setpoint as it was unnecessary.
# Replaced a test for polarity with a switch statement.
#
# Revision 1.21  2011/05/30 11:18:18  lemery
# Changed argument names for plotCouplingData. Simplified the command to plot the filtered data using sddscontour.
#
# Revision 1.20  2011/05/30 10:51:42  lemery
# Untabified and indented.
#
# Revision 1.19  2011/05/30 10:46:24  lemery
# Changed "Coup" to "Coupling" because I read Coup as a french word, which means hit.
#
# Revision 1.18  2011/05/27 13:30:46  lemery
# Added CVS log line to allow logs to be recorded in the file.
#

APSApplication . -name "CPUscanSkewQuads2d" -version $CVSRevisionAuthor \
  -overview "CPUscanSkewQuads2d makes a 2D scans of the CPU skew magnets. Then a 2D interpolation of coupling is made within the scan range. Connect points of coupling same as CPU at zero, this is the result we are seeking. Put result by sddsedit the original correction table."

set CPUCouplingScript {
    &measurement
    control_name=ID04b:set_H_coil.VAL
    column_name=HCoil
    &end
    &measurement
    control_name=ID04b:set_V_coil.VAL
    column_name=VCoil
    &end
    &measurement
    control_name=S:VID1:filteredXemittance
    column_name=emittanceX
    &end
    &measurement
    control_name=S:VID1:filteredYemittance
    column_name=emittanceY
    &end
    &measurement
    control_name=S:VID1:filteredCoupling
    column_name=Coupling
    &end
    &measurement
    control_name=S:VID1:y:fit:cal:sigmaAvgM
    column_name=RawBeamSizeY
    &end
    &measurement
    control_name=S:VID1:x:fit:cal:sigmaAvgM
    column_name=RawBeamSizeX
    &end

    &variable control_name = "ID04b:US_SkewQuadSetpt"
    column_name="rotatedQuad", units="A"
    relative_to_original=0,
    index_number = 0, index_limit = <xpoints>,
    initial_value = <xmin>, final_value = <xmax>,
    reset_to_original = 1
    &end
    &variable control_name = "ID04b:DS_SkewQuadSetpt"
    column_name="rotatedOct", units="A"
    relative_to_original=0,
    index_number = <Mode>, index_limit = <ypoints>,
    initial_value = <ymin>, final_value = <ymax>,
    reset_to_original = 1
    &end
    &execute
    allowed_timeout_errors=10
    post_change_pause=5,
    intermeasurement_pause=0.5,
    ramp_pause = 5,
    rollover_pause=5,
    ramp_steps = 1,
    &end
}

proc MakeCouplingActionWidget {widget args} {
    global CPUCoupling
    set parent ""
    APSParseArguments {parent}
    set w $parent

    APSButton .run1 -parent $w -text Scan-1D -command \
      { \
          catch {CollectCouplingData -mode $mode -scanMode 0} status
          cd $CPUCoupling(logDir)
          update idletasks
      } \
      -contextHelp "1D-Scan skew quad and octupole settings for finding minimum coupling"

    APSButton .run2 -parent $w -text Scan-2D -command \
      { \
          catch {CollectCouplingData -mode $mode -scanMode 1} status
          cd $CPUCoupling(logDir)
          update idletasks
      } \
      -contextHelp "2D-Scan skew quad and octupole settings for finding minimum coupling"

    APSButton .plot0 -parent $w -text "PLOT Single" -command \
      { \
          catch {PlotCouplingData -CPUmode $mode -plotMode single} status
          cd $CPUCoupling(logDir)
          update idletasks
      } \
      -contextHelp "Plot the single page contour plot."

    APSButton .plot1 -parent $w -text "PLOT All" -command \
      { \
          catch {PlotCouplingData -CPUmode $mode -plotMode all} status
          cd $CPUCoupling(logDir)
          update idletasks
      } \
      -contextHelp "Plot all data collected today."
    APSButton .plot2 -parent $w -text "PLOT Single Filtered" -command \
      { \
          catch {PlotCouplingData -CPUmode $mode -plotMode filtered} status
          cd $CPUCoupling(logDir)
          update idletasks
      } \
      -contextHelp "Plot filtered data of each page for processing. Coupling information needed."
    APSButton .reset -parent $w -text "Reset" -command \
      { \
          catch {ResetCPU} status
          update idletasks
      } \
      -contextHelp "Reset CPU to zero."
}

proc MakeCouplingInputWidget {widget args} {
    global CPUCoupling 
    set parent ""
    APSParseArguments {parent}
    
    APSFrame $widget -parent $parent -label "Input parameters"
    set w $parent$widget.frame

    APSLabeledEntry .logDir -parent $w -width 80 \
      -textVariable CPUCoupling(logDir) \
      -label "Log directory:" \
      -contextHelp "Directory for log file of minimization."
    APSLabeledEntry .comment -parent $w -width 80 \
      -textVariable CPUCoupling(comment) \
      -label "Comment:" \
      -contextHelp "Put comment for experiment."
    APSButton .daily -parent $w.logDir -packOption "-anchor e" \
      -text "daily" -size small \
      -command {set CPUCoupling(logDir) [APSGoToDailyDirectory -subdirectory CPU]}

    APSFrameGrid .fg -parent $w -xList {x1 x2 x3 x4}
    set w0 $w.fg.x1
    APSLabel .skewQuad -parent $w0 -text "SkewQuad (US)"
    APSLabel .skewOct  -parent $w0 -text "SkewOct (DS)"
    set w0 $w.fg.x2
    APSLabeledEntry .skewQuad0 -parent $w0 -width 20 -textVariable CPUCoupling(xmin) \
      -label "Start:" \
      -contextHelp "Start setting point of skewQuad scan"
    APSLabeledEntry .skewOct0 -parent $w0 -width 20 -textVariable CPUCoupling(ymin) \
      -label "Start:" \
      -contextHelp "Start setting point of skewOct scan"
    set w0 $w.fg.x3
    APSLabeledEntry .skewQuad1 -parent $w0 -width 20 -textVariable CPUCoupling(xmax) \
      -label "End:" \
      -contextHelp "End setting point of skewQuad scan"
    APSLabeledEntry .skewOct1 -parent $w0 -width 20 -textVariable CPUCoupling(ymax) \
      -label "End:" \
      -contextHelp "End setting point of skewOct scan"
    set w0 $w.fg.x4
    APSLabeledEntry .skewQuadStep -parent $w0 -width 20 -textVariable CPUCoupling(xpoints) \
      -label "Steps:" \
      -contextHelp "Steps of skewQuad scan"
    APSLabeledEntry .skewOctStep -parent $w0 -width 20 -textVariable CPUCoupling(ypoints) \
      -label "Steps:" \
      -contextHelp "Steps of skewOct scan"

    APSRadioButtonFrame .mode -parent $w -orientation horizontal \
      -label "CPU mode for measuring: " -variable mode \
      -limitPerRow 5 \
      -buttonList {CW CCW H V CW/CCW} \
      -valueList {CW CCW H V AC} \
      -commandList {"catch {setCPUMode CW} status" "catch {setCPUMode CCW} status" \
                      "catch {setCPUMode H} status" "catch {setCPUMode V} status" \
                      "catch {setCPUMode AC} status"} \
      -contextHelp \
      "Choose CPU mode for processing the files. This values is also used to determine whether the current value is sent to the V coil or the H coil. -- For CW CCW and H modes, the current values is sent to the V coil. For V modes, the current is sent to the H coil.\n\nChanging the selection will update the rootname for the snapshot file."

    APSLabeledEntry .current -parent $w -width 80 \
      -textVariable CPUCoupling(mainPVSettings) \
      -label "CPUMainCoilSettings" \
      -contextHelp "CPU main coil settings for doing measurement."
    APSButton .select -parent $w.current -packOption "-anchor e" \
      -text "Select" -size small \
      -command {SelectCPUSettings $mode}
    APSLabeledOutput .setPV -parent $w -label "Set PV: "  -textVariable CPUCoupling(mainPV)

    APSFrameGrid .fg1 -parent $w -xList {x1 x2 x3 x4}
    set w0 $w.fg1.x1
    APSLabel .coupling -parent $w0 -text "Coupling Window:"
    set w0 $w.fg1.x2
    APSLabeledEntry .coupling0 -parent $w0 -width 20 -textVariable coupling0 \
      -label "Center:" \
      -contextHelp "Desired coupling"
    set w0 $w.fg1.x3
    APSLabeledEntry .coupling1 -parent $w0 -width 20 -textVariable couplingLow \
      -label "LowLimit:" \
      -contextHelp "Low limitation"
    set w0 $w.fg1.x4
    APSLabeledEntry .coupling2 -parent $w0 -width 20 -textVariable couplingHigh \
      -label "HighLimit:" \
      -contextHelp "High limitation"

    APSCheckButtonFrame .drytun -parent $w -packOption "-side left" -contextHelp "Perform Dryrun??" \
      -label " " \
      -buttonList {"Dryrun"} -variableList {CPUCoupling(dryrun)}

    APSCheckButtonFrame .sound -parent $w -packOption "-side left" -contextHelp "Do you want sound acknowledgment after scan?" \
      -label " " \
      -buttonList {"Sound"} -variableList {CPUCoupling(sound)}
}

proc setCPUMode {mode} {
    global CPUCoupling rootname
    cd $CPUCoupling(logDir)
    set CPUCoupling(mainPVSettings) 0
    switch $mode {
        H {
            set CPUCoupling(mainPV)  "ID04b:set_V_coil.VAL"
            set rootname Hmode
        }
        V {
            set CPUCoupling(mainPV)  "ID04b:set_H_coil.VAL"
            set rootname Vmode
        }
        CW {
            set CPUCoupling(mainPV)  "ID04b:set_H_coil.VAL"
            set rootname CWmode
        }
        CCW {
            set CPUCoupling(mainPV)  "ID04b:set_H_coil.VAL"
            set rootname CCWmode
        }
        AC {
            set CPUCoupling(mainPV)  "ID04b:set_V_coil.VAL"
            set rootname ACmode
        }
    }
    #    ResetCPU
    return
}

proc ResetCPU {} {
    global CPUCorr CPUCoupling

    exec cavput -list=$CPUCoupling(mainPV)=0
    exec cawait -interval=0.5 -waitFor=ID04b:feedback.VAL,sameAs=Ready
    set CPUCorr "0 0 0 0 0 0 0"
    PutCPUDCCorrValues
}

proc SelectCPUSettings {mode} {
    global CPUCoupling

    set root "/home/helios/oagData/"
    switch $mode {
        AC {
            set fileroot $root
            lappend fileroot [lindex [exec caget ID04b:corrFile_7.VAL] 1]
            set filename [join $fileroot ""]
            set setpointList [exec sddsprocess $filename -pipe=out -print=para,value,%4.0f,MainCurrent \
                                | sdds2stream -pipe=in -para=value]
        }
        default {
            set fileroot $root
            lappend fileroot [lindex [exec caget ID04b:corrFile.VAL] 1]
            set filename [join $fileroot ""]
            set setpointList [exec sddsprocess $filename -pipe=out \
                                -match=para,Mode=$mode \
                                "-redef=col,I,I abs" -print=col,value,%4.0f,I \
                                | sddssort -pipe -col=I,increasing \
                                | sdds2stream -pipe=in -col=value]
        }
    }
    set a [join $setpointList " "]
    catch {set CPUCoupling(mainPVSettings)  [APSChooseItemFromList -itemList $a -returnList $a \
                                               -name "Select CPU main coil value to measure" -returnIndices 0 -multiItem 1]} result
}

proc CollectCouplingData {args} {
    APSParseArguments {mode scanMode}
    global CPUCoupling rootname CPUCouplingScript CPUCorr

    cd $CPUCoupling(logDir)
    exec mkdir -p $rootname
    cd $rootname
    set outID [open skew.exp w]
    puts $outID $CPUCouplingScript
    close $outID

    #   set S:VID1 averaging
    if !$CPUCoupling(dryrun) {
        exec cavput -list=S:VID1:numToAvgC=30
    }

    # Set desired CPU running conditions here. Then run scan 
    switch $mode {
        H {
            exec cavput -list=ID04b:DesiredMode.VAL=3
        }
        V {
            exec cavput -list=ID04b:DesiredMode.VAL=2
        }
        CW {
            exec cavput -list=ID04b:DesiredMode.VAL=0
        }
        CCW {
            exec cavput -list=ID04b:DesiredMode.VAL=1
        }
        AC {
            exec cavput -list=ID04b:DesiredMode.VAL=4
        }
    }
    foreach setpoint $CPUCoupling(mainPVSettings) {

        set root [format "%04ld" $setpoint]
        set polarity ""
        if $CPUCoupling(dryrun) {
            SetStatus "exec cavput -list=$CPUCoupling(mainPV)=$setpoint"           
        } else {
            exec cavput -list=$CPUCoupling(mainPV)=$setpoint
            after 1000
            SetStatus "Waiting for ramping to set point $setpoint..."
            exec cawait -interval=0.5 -waitFor=ID04b:feedback.VAL,sameAs=Ready
        }
        
        switch $mode {
            AC {
                # prepare to do measurement with negative polarity then positive polarity
                set flagN [file exists skew$root.cw]
                set flagP [file exists skew$root.ccw]
                # Do scan for negative polarity or for zero set point.
                if {!$flagN} {
                    # Ensure negative polarity
                    if {!$CPUCoupling(dryrun)} {
                        if {$setpoint} {
                            exec cavput -list=ID04b:timer=2
                            after 6000
                            exec cavput -list=ID04b:timer=10
                            after 2000
                            exec cawait -interval=0.5 -waitFor=ID04b:V_coil.VAL,below=-1
                        }
                        exec cavput -list=ID04b:timer=1000
                        set polarity Negative
                    }
                    set output skew$root.cw
                    set runDone 0
                    # These procedures operate on the global variable CPUCorr
                    GetCPUDCCorrValues -mode $mode -polarity $polarity -mainCurrent $setpoint
                    PutCPUDCCorrValues    

                    set value0 [lindex $CPUCorr 6]
                    if {[expr $value0+$CPUCoupling(xmax)]>10} {
                        set xmax0 10
                        set xmin0 [expr 10 - $CPUCoupling(xmax) + $CPUCoupling(xmin)]
                    } elseif {[expr $value0+$CPUCoupling(xmin)]<-10} {
                        set xmax0 [expr -10 + $CPUCoupling(xmax) - $CPUCoupling(xmin)]
                        set xmin0 -10
                    } else {
                        set xmax0 [expr $value0 +$CPUCoupling(xmax)]
                        set xmin0 [expr $value0 +$CPUCoupling(xmin)]
                    }
                    set value0 [lindex $CPUCorr 5]
                    if {[expr $value0+$CPUCoupling(ymax)]>10} {
                        set ymax0 10
                        set ymin0 [expr 10 - $CPUCoupling(ymax) + $CPUCoupling(ymin)]
                    } elseif {[expr $value0+$CPUCoupling(ymin)]<-10} {
                        set ymax0 [expr -10 + $CPUCoupling(ymax) - $CPUCoupling(ymin)]
                        set ymin0 -10
                    } else {
                        set ymax0 [expr $value0 +$CPUCoupling(ymax)]
                        set ymin0 [expr $value0 +$CPUCoupling(ymin)]
                    }
                    set command "sddsexperiment skew.exp -verbose \"-comment=$CPUCoupling(comment)\" \
                                            -macro=xmin=$xmin0,xmax=$xmax0,xpoints=$CPUCoupling(xpoints),ymin=$ymin0,ymax=$ymax0,ypoints=$CPUCoupling(ypoints),Mode=$scanMode"
                    if $CPUCoupling(dryrun) {
                        set command "$command -dryrun"
                    }
                    SetStatus $command

                    APSExecLog .expExec -name "Experiment Log" \
                      -unixCommand  "$command $output " -width 100 \
                      -callback "set runDone 1" -cancelCallback "set runDone 2" -abortCallback "set runDone 2"
                    tkwait variable runDone
                    PutCPUDCCorrValues
                    if {$setpoint == 0} {
                        exec cp skew$root.cw skew$root.ccw
                    }
                    exec cavput -list=ID04b:timer=2
                }
                set flagP [file exists skew$root.ccw]
                # Dont do 0 A for positive polarity. It's been done for negative polarity.
                if {$setpoint !=0 && !$flagP} {
                    # Ensure positive polarity
                    if !$CPUCoupling(dryrun) {
                        exec cavput -list=ID04b:timer=2
                        after 6000
                        exec cavput -list=ID04b:timer=10
                        after 2000
                        exec cawait -interval=0.5 -waitFor=ID04b:V_coil.VAL,above=1
                        exec cavput -list=ID04b:timer=1000
                        set polarity Positive
                    }
                    set output skew$root.ccw
                    set runDone 0
                    GetCPUDCCorrValues -mode $mode -polarity $polarity -mainCurrent $setpoint
                    PutCPUDCCorrValues    

                    set value0 [lindex $CPUCorr 6]
                    if {[expr $value0+$CPUCoupling(xmax)]>10} {
                        set xmax0 10
                        set xmin0 [expr 10 - $CPUCoupling(xmax) + $CPUCoupling(xmin)]
                    } elseif {[expr $value0+$CPUCoupling(xmin)]<-10} {
                        set xmax0 [expr -10 + $CPUCoupling(xmax) - $CPUCoupling(xmin)]
                        set xmin0 -10
                    } else {
                        set xmax0 [expr $value0 +$CPUCoupling(xmax)]
                        set xmin0 [expr $value0 +$CPUCoupling(xmin)]
                    }
                    set value0 [lindex $CPUCorr 5]
                    if {[expr $value0+$CPUCoupling(ymax)]>10} {
                        set ymax0 10
                        set ymin0 [expr 10 - $CPUCoupling(ymax) + $CPUCoupling(ymin)]
                    } elseif {[expr $value0+$CPUCoupling(ymin)]<-10} {
                        set ymax0 [expr -10 + $CPUCoupling(ymax) - $CPUCoupling(ymin)]
                        set ymin0 -10
                    } else {
                        set ymax0 [expr $value0 +$CPUCoupling(ymax)]
                        set ymin0 [expr $value0 +$CPUCoupling(ymin)]
                    }
                    set command "sddsexperiment skew.exp -verbose \"-comment=$CPUCoupling(comment)\" \
                                                -macro=xmin=$xmin0,xmax=$xmax0,xpoints=$CPUCoupling(xpoints),ymin=$ymin0,ymax=$ymax0,ypoints=$CPUCoupling(ypoints),Mode=$scanMode"
                    if $CPUCoupling(dryrun) {
                        set command "$command -dryrun"
                    }
                    SetStatus $command

                    APSExecLog .expExec -name "Experiment Log" \
                      -unixCommand  "$command $output " -width 100 \
                      -callback "set runDone 1" -cancelCallback "set runDone 2" -abortCallback "set runDone 2"
                    tkwait variable runDone
                    PutCPUDCCorrValues
                    exec cavput -list=ID04b:timer=2
                }
            }
            default { # DC modes
                if {![file exists skew$root]} {
                    set output "skew$root"
                    set runDone 0
                    GetCPUDCCorrValues -mode $mode -polarity $polarity -mainCurrent $setpoint
                    PutCPUDCCorrValues    

                    set value0 [lindex $CPUCorr 6]
                    # xmin xmax ymin ymax refer to the skew quad limits.
                    if {[expr $value0+$CPUCoupling(xmax)]>10} {
                        set xmax0 10
                        set xmin0 [expr 10 - $CPUCoupling(xmax) + $CPUCoupling(xmin)]
                    } elseif {[expr $value0+$CPUCoupling(xmin)]<-10} {
                        set xmax0 [expr -10 + $CPUCoupling(xmax) - $CPUCoupling(xmin)]
                        set xmin0 -10
                    } else {
                        set xmax0 [expr $value0 +$CPUCoupling(xmax)]
                        set xmin0 [expr $value0 +$CPUCoupling(xmin)]
                    }
                    set value0 [lindex $CPUCorr 5]
                    if {[expr $value0+$CPUCoupling(ymax)]>10} {
                        set ymax0 10
                        set ymin0 [expr 10 - $CPUCoupling(ymax) + $CPUCoupling(ymin)]
                    } elseif {[expr $value0+$CPUCoupling(ymin)]<-10} {
                        set ymax0 [expr -10 + $CPUCoupling(ymax) - $CPUCoupling(ymin)]
                        set ymin0 -10
                    } else {
                        set ymax0 [expr $value0 +$CPUCoupling(ymax)]
                        set ymin0 [expr $value0 +$CPUCoupling(ymin)]
                    }
                    set command "sddsexperiment skew.exp -verbose \"-comment=$CPUCoupling(comment)\" \
                    -macro=xmin=$xmin0,xmax=$xmax0,xpoints=$CPUCoupling(xpoints),ymin=$ymin0,ymax=$ymax0,ypoints=$CPUCoupling(ypoints),Mode=$scanMode"
                    if $CPUCoupling(dryrun) {
                        set command "$command -dryrun"
                    }
                    SetStatus $command

                    APSExecLog .expExec -name "Experiment Log" \
                      -unixCommand  "$command $output " -width 100 \
                      -callback "set runDone 1" -cancelCallback "set runDone 2" -abortCallback "set runDone 2"
                    tkwait variable runDone
                    PutCPUDCCorrValues
                }
            }
        }
    }
    
    if $CPUCoupling(sound) {
        global tcl_platform
        if {$tcl_platform(os) == "SunOS"} {
            exec audioplay -v 70 /usr/local/oag/sounds/game_over.au
        } else {
            exec play -q -v .7 /usr/local/oag/sounds/game_over.au
        }
    }
    # Update message to status window.
    cd $CPUCoupling(logDir)
    SetStatus "Collecting done."
    return
}

proc GetCPUDCCorrValues {args} {
    APSParseArguments {mode polarity mainCurrent}
    global CPUCorr
    SetStatus "Mode=$mode Polarity=$polarity MainCurrent=$mainCurrent"

    set CPUCorr "0 0 0 0 0 0 0"
    set root "/home/helios/oagData/"
    set tmpfile /tmp/[APSTmpString]

    switch $mode {
        AC {
            switch $polarity {
                Positive {set suffix Pos}
                Negative {set suffix Neg}
                default {
                    SetStatus "GetCPUDCCorrValues: Problem with variable polarity: $polarity "
                    return -code error
                }
            }
            for {set i 1} {$i<8} {incr i} {
                set fileroot $root
                lappend fileroot [lindex [exec caget ID04b:corrFile_$i.VAL] 1]
                set filename [join $fileroot ""]
                exec sddsprocess $filename -pipe=out -del=para,DCPos,DCNeg \
                  | sddsprocess -pipe \
                  -proc=CurrentPos,last,DCPos -proc=CurrentNeg,last,DCNeg \
                  | sddscollapse -pipe \
                  | sddsinterp -pipe=in  $tmpfile.1 \
                  -columns=MainCurrent,DC* -atValues=$mainCurrent
                set j [expr $i-1]
                lset CPUCorr $j [format %4.2f [exec sdds2stream -col=DC$suffix $tmpfile.1]]
            }
        }
        default {
            set fileroot $root
            lappend fileroot [lindex [exec caget ID04b:corrFile.VAL] 1]
            set filename [join $fileroot ""]
            exec sddsprocess $filename -pipe=out "-redef=col,I,I abs" \
              | sddsinterp -pipe -columns=I,* -atValues=$mainCurrent \
              | sddsprocess -pipe=in $tmpfile.1 -match=para,Mode=$mode
            lset CPUCorr 0 [format %4.2f [exec sdds2stream -col=Vcorr2 $tmpfile.1]]           
            lset CPUCorr 1 [format %4.2f [exec sdds2stream -col=Hcorr2 $tmpfile.1]]           
            lset CPUCorr 2 [format %4.2f [exec sdds2stream -col=Hcorr1 $tmpfile.1]]           
            lset CPUCorr 3 [format %4.2f [exec sdds2stream -col=Vcorr1 $tmpfile.1]]           
            lset CPUCorr 4 [format %4.2f [exec sdds2stream -col=NormalQuad $tmpfile.1]]
            lset CPUCorr 5 [format %4.2f [exec sdds2stream -col=RotatedOct $tmpfile.1]]
            lset CPUCorr 6 [format %4.2f [exec sdds2stream -col=RotatedQuad $tmpfile.1]]
        }
    }
    file delete -force $tmpfile.1
    return
}

proc PutCPUDCCorrValues {} {
    global CPUCorr CPUCoupling
    set CPUCorrPV "ID04b:DS_VertCorrSetpt ID04b:DS_HorCorrSetpt ID04b:US_HorCorrSetpt ID04b:US_VertCorrSetpt ID04b:DS_NormalQuadSetpt ID04b:DS_SkewQuadSetpt ID04b:US_SkewQuadSetpt"
    foreach PV $CPUCorrPV value $CPUCorr {
        if {$value>10} {
            return -code error "Maximum corrector value is 10. Read $value for $PV"
        }
        if $CPUCoupling(dryrun) {
            SetStatus "$PV=$value"
        } else {
            exec cavput -list=$PV=$value
        }
    }
    after 2000
    return
}

proc PlotCouplingData {args} {
    APSParseArguments {CPUmode plotMode}
    global CPUCoupling rootname coupling0 couplingLow couplingHigh
    cd $CPUCoupling(logDir)
    cd $rootname
    switch $CPUmode {
        AC {
            set fileList [lsort [glob skew\[0-9\]???.*cw]]
        }
        default {
            set fileList [lsort [glob skew\[0-9\]???]]
        }
    }
    set couplingFileList ""
    foreach file $fileList {
        lappend couplingFileList $file.coup.2d
        if ![file exists $file.coup.2d] {
            exec sdds2dinterpolate $file $file.coup.2d \
              -dep=Coupling -independentColumn=xcol=rotatedOct,ycol=rotatedQuad \
              -outDimen=xdim=200,ydim=200
        }
        if {[string match $plotMode single] && [string match *$CPUCoupling(mainPVSettings)* $file]} {
            exec sddscontour $file.coup.2d -quant=Coupling -shades=128 &  
        }
    }

    switch $plotMode {
        all {
            if ![file exists all.coup.2d] {
                eval exec sddscombine $couplingFileList all.coup.2d
            }
            exec sddscontour all.coup.2d -quant=Coupling -shades=128  -topline=@Filename &
        }
        
        filtered {
            set file0 [lindex $fileList 0]
            if {![file exist $file0.coup.2d] || [string match 0000 $file0.coup.2d]} {
                return -code error "Reference file doesn't exist"
            }
            
            set limit [exec sddsprocess $file0.coup.2d -pipe=out \
                         -filt=col,rotatedOct,-0.1,0.1 -filt=col,rotatedQuad,-0.1,0.1 \
                         | sddsprocess -pipe -proc=Coupling,ave,c0 \
                         "-def=para,c1,c0 0.99 *" "-def=para,c2,c0 1.01 *" \
                         | sdds2stream -pipe -para=c0,c1,c2]
            set coupling0 [lindex $limit 0]
            set couplingLow [lindex $limit 1] 
            set couplingHigh [lindex $limit 2]

#            exec sddscontour all.coup.2d -quant=Coupling -shades=16,$couplingLow,$couplingHigh -topline=@Filename &
            foreach file $fileList {
                exec sddsplot -grap=sym,vary=sub,type=2,fill,scale=2 \
                  -col=rotatedQuad,rotatedOct -split=col=Coupling -order=spec \
                  -filt=col,Coupling,$couplingLow,$couplingHigh $file.coup.2d \
                  -topl=$file &  
            }
        }
    }
    SetStatus "Plotting done."     
    return
}

proc SetStatus {text} {
    APSSetVarAndUpdate status $text
    update
}

set CPUCoupling(logDir) [pwd]
set CPUCoupling(comment) ""
set CPUCoupling(xmin) -4.0
set CPUCoupling(xmax)  4.0
set CPUCoupling(ymin) -4.0
set CPUCoupling(ymax)  4.0
set CPUCoupling(xpoints) 5
set CPUCoupling(ypoints) 5
set CPUCoupling(dryrun) 0
set CPUCoupling(sound) 0
set CPUCoupling(mainPVSettings) 0
set CPUCorr "0 0 0 0 0 0 0"
set mode CW
set coupling0 0
set couplingLow 0
set couplingHigh 0

setCPUMode $mode 

set status "Working."
APSScrolledStatus .status -parent .userFrame -textVariable status -packOption "-expand yes -fill both"
MakeCouplingInputWidget .input -parent .userFrame
MakeCouplingActionWidget .action -parent .userFrame
set status "Ready."

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

