#!/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.0 $ \$Author: shang $"

set mainStatus ""
proc SetStatus {text} {
    global mainStatus
    set mainStatus "[clock format [clock seconds] -format %H:%M:%S] $text"
    update      

}

proc StartScan {args} {
    set scanType MixerDelay
    APSParseArguments {scanType}
    
    global outputDir interval  description initValue finalValue scanDone pattern
    global MixerDelayInitValue MixerDelayFinalValue SampleDelayInitValue SampleDelayFinalValue
    
    eval global ${scanType}Steps ${scanType}Rootname 
    set rootname [set ${scanType}Rootname]
    set Steps [set ${scanType}Steps]
    set count 1
    set sampleDelayLimit 12.75
    set mixerDelayLimit 6.35
    set xinitValue 0
    set xfinalValue 0
    set yinitValue 0
    set yfinalValue 0
    switch $scanType {
        MixerDelay {
            set initValue $MixerDelayInitValue
            set finalValue $MixerDelayFinalValue
            set stepSize [expr ($finalValue - $initValue)/($Steps - 1.0)]
            if [catch {exec cavget -list=S:tune:hpdl:z:SetDelay2 -printErrors -pend=10 } currValue] {
                return -code error "Error reading mixer delay: $currValue"
            }
            set changed 0
            if {[expr $currValue + $initValue]<0} {
                set initValue [expr $currValue * -1.0]
                incr changed
            }
            if {[expr $currValue + $finalValue]> $mixerDelayLimit} {
                set finalValue [expr $mixerDelayLimit - $currValue]
                incr changed
            }
            if $changed {
                set Steps [format %.0f [expr ($finalValue - $initValue)/$stepSize]]
            }
            set xinitValue $initValue
            set yinitValue $initValue
            set xfinalValue $finalValue
            set yfinalValue $finalValue
        }
        SampleDelay {
            set initValue $SampleDelayInitValue
            set finalValue $SampleDelayFinalValue
            set stepSize [expr ($finalValue - $initValue)/($Steps - 1.0)]
            if [catch {exec cavget -list=S:tune:hpdl: -list=x,y -list=:SetDelay -printErrors -pend=10 } delays] {
                return -code error "Error reading sample delays: $delays"
            }
            set xdelay [lindex $delays 0]
            set ydelay [lindex $delays 1]
            set xinitValue $initValue
            set yinitValue $initValue
            set xfinalValue $finalValue
            set yfinalValue $finalValue
            set changed 0
            if {[expr $xdelay + $initValue]<0} {
                set xinitValue [expr $xdelay * -1.0]
                incr changed
            }
            if {[expr $xdelay + $finalValue]>$sampleDelayLimit} {
                set xfinalValue [expr $sampleDelayLimit - $xdelay]
                incr changed
            }
            if $changed {
                set xsteps [format %.0f [expr ($xfinalValue - $xinitValue)/$stepSize]]
            } else {
                set xsteps $Steps
            }
            set changed 0
            if {[expr $ydelay + $initValue]<0} {
                set yinitValue [expr $ydelay * -1.0]
                incr changed
            }
            if {[expr $ydelay + $finalValue]>$sampleDelayLimit} {
                set yfinalValue [expr $sampleDelayLimit - $ydelay]
                incr changed
            }
            if $changed {
                set ysteps [format %.0f [expr ($yfinalValue - $yinitValue)/$stepSize]]
            } else {
                set ystesp $Steps
            }
            if {$xsteps>$ysteps} {
                set Steps $xsteps
            } else {
                set Steps $ysteps
            }
        }
        Attenuator {
            set initValue 0
            set finalValue [expr $AttenuatorSteps - 1]
        }
        SamplePattern {
            if {$pattern=="single"} {
                ScanSingleSamplePattern
                return
            }
            set initValue 1
            set finalValue $Steps
            set patternFile /home/helios/oagData/par/P0feedback/patternFiles/${pattern}-pattern-scan-start
            SetStatus "loading original pattern..."
            if [catch {exec sddswput $patternFile -pend=30} result] {
                return -code error "Error loading pattern file: $patternFile"
            }
        }
    }
    if ![file exist $outputDir] {
        exec mkdir $outputDir
    }
    set expTemplateFile /home/helios/oagData/sr/P0Feedback/inputFiles/P0FB${scanType}Scan.template.exp
    set expFile $outputDir/${rootname}.exp
    
    if [catch {exec replaceText $expTemplateFile $expFile -orig=<initValue>,<finalValue>,<steps>,<outputDir>,<outputRootname>,<pause>,<count>,<xinitValue>,<xfinalValue>,<yinitValue>,<yfinalValue> \
                 -repl=$initValue,$finalValue,$Steps,$outputDir,$rootname,$interval,$count,$xinitValue,$xfinalValue,$yinitValue,$yfinalValue } result] {
        return -code error "StartScan1: $result"
    }
   
    if [file exist $outputDir/${rootname}.sdds] {
        if [APSYesNoPopUp "${rootname}.sdds already exist, overwrite it?"] {
            exec rm $outputDir/${rootname}.sdds
        } else {
            SetStatus "$outputDir/${rootname}.sdds already exist, scan aborted."
            return
        }
    }
    SetStatus "Start P0Feedback $scanType scan..."
    set scanDone 0
    APSExecLog .expExec -name "Scan P0 Feedback delay" \
      -unixCommand  "sddsexperiment $expFile $outputDir/${rootname}.sdds -verbose" -width 100 \
      -callback "set scanDone done" \
      -cancelCallback "set scanDone cancelled" -abortCallback "set scanDone abort"
    tkwait variable scanDone
    
    if {$scanDone=="done"} {
        SetStatus "Scan done. Postprocesing data..."
        ProcessData -scanType $scanType
    } else {
        SetStatus "Scan $scanDone."
    }
}

proc ScanSingleSamplePattern {args} {
    global outputDir SamplePatternRootname interval scanDone
    #need to do two scans for single pattern
    #first scan 24 singlets for 18 steps, then scan with single pattern for 24 steps
    set patternFile /home/helios/oagData/par/P0feedback/patternFiles/24singlets-pattern-scan-start
    set steps 18
    set expTemplateFile /home/helios/oagData/sr/P0Feedback/inputFiles/P0FBSamplePatternScan.template.exp
    set count 1
    set initValue 1
    set finalValue $steps
    set rootname $SamplePatternRootname
    set scanType SamplePattern
    set expFile $outputDir/${rootname}A.exp
    set rootname $SamplePatternRootname
    if ![file exist $outputDir] {
        exec mkdir $outputDir
    }
    if [catch {exec replaceText $expTemplateFile $expFile -orig=<initValue>,<finalValue>,<steps>,<outputDir>,<outputRootname>,<pause>,<count> \
                 -repl=$initValue,$finalValue,$steps,$outputDir,${rootname}A,$interval,$count } result] {
        return -code error "ScanSingleSamplePattern1: $result"
    }
    SetStatus "Start P0Feedback single sample pattern scan: step1 -- scan with 24singlets first..."
    set scanDone 0
    if [catch {exec sddswput $patternFile -pend=30} result] {
        return -code error "Error loading pattern file: $patternFile"
    }
    if [file exist $outputDir/${rootname}A.sdds] {
        if [APSYesNoPopUp "$outputDir/${rootname}A.sdds already exist, overwrite it?"] {
            exec rm $outputDir/${rootname}A.sdds
        } else {
            SetStatus "$outputDir/${rootname}A.sdds already exist, scan aborted."
            return
        }
    }
    APSExecLog .expExec -name "Scan P0 Feedback delay" \
      -unixCommand  "sddsexperiment $expFile $outputDir/${rootname}A.sdds -verbose" -width 100 \
      -callback "set scanDone done" \
      -cancelCallback "set scanDone cancelled" -abortCallback "set scanDone abort"
    tkwait variable scanDone
    if [catch {exec sddswput $patternFile -pend=30} result] {
        return -code error "Error loading pattern file: $patternFile"
    }
    if {$scanDone=="done"} {
        SetStatus "Postprocesing data..."
        ProcessData -scanType $scanType -step A -loadSingle 1 -auto 1
    } else {
        return -code error "scan $scanDone."
    }
    set steps 24
    set count 18
    set finalValue $steps
    set expFile $outputDir/${rootname}B.exp
    
    if [catch {exec replaceText $expTemplateFile $expFile -orig=<initValue>,<finalValue>,<steps>,<outputDir>,<outputRootname>,<pause>,<count> \
                 -repl=$initValue,$finalValue,$steps,$outputDir,${rootname}B,$interval,$count } result] {
        return -code error "ScanSingleSamplePattern1: $result"
    }
    SetStatus "Start P0Feedback $scanType scan: step2 -- scan with single pattern..."
    set scanDone 0
    APSExecLog .expExec -name "Scan P0 Feedback delay" \
      -unixCommand  "sddsexperiment $expFile $outputDir/${rootname}B.sdds -verbose" -width 100 \
      -callback "set scanDone done" \
      -cancelCallback "set scanDone cancelled" -abortaCallback "set scanDone abort"
    tkwait variable scanDone
    
    if {$scanDone=="done"} {
        SetStatus "Scan done. Postprocesing data..."
        ProcessData -scanType $scanType -step B
    } else {
        SetStatus "Scan $scanDone."
    }
}

proc ProcessData {args} {
    set scanType ""
    set step ""
    set loadSingle 0
    set auto 0
    APSParseArguments {scanType step loadSingle auto}
    global ${scanType}Rootname outputDir wfAveXtarget wfAveYtarget

    set rootname [set ${scanType}Rootname]$step
    cd $outputDir
    set tmpRoot /tmp/[APSTmpString]
    
    switch $scanType {
        MixerDelay {
            set files [glob ${rootname}-???]
            if ![llength $files] {
                return -code error "No files found for $rootname ."
            }
            if [catch {eval exec sddscombine $files -pipe=out \
                         | sddsprocess -pipe  \
                         \"-redefine=par,Step,i_page,type=long\" \
                         \"-process=S:P0FB:scope:gtr:waveform0,average,wfXave1\" \
                         \"-process=S:P0FB:scope:gtr:waveform1,ave,wfYave1\" \
                         | sddsprocess -pipe \"-redefine=par,wfXave,wfXave1 abs\" \
                         \"-redefine=par,wfYave,wfYave1 abs\" \
                         | sddscollapse -pipe \
                         | sddsprocess -pipe -process=wfXave,max,xDelay,position,functionOf=S:tune:hpdl:z:GetDelay1 \
                         -process=wfYave,max,yDelay,position,functionOf=S:tune:hpdl:z:GetDelay2 \
                         | sddsprocess -pipe=in ${rootname}.sdds.proc \
                         \"-redefine=par,xDelayMax,xDelay 3.175 - abs 1.42 < ? xDelay : xDelay 3.175 < ? xDelay 2.84 + : xDelay 2.84 - $ $ \" \
                         \"-redefine=par,yDelayMax,yDelay 3.175 - abs 1.42 < ? yDelay : yDelay 3.175 < ? yDelay 2.84 + : yDelay 2.84 - $ $ \" } result] {
                return -code error "Error processing mixer delay: $result"
            }
            set xDelay [format %.2f [exec sdds2stream -par=xDelayMax ${rootname}.sdds.proc]]
            set yDelay [format %.2f [exec sdds2stream -par=yDelayMax ${rootname}.sdds.proc]]
            exec sddsplot -sep -col=S:tune:hpdl:z:GetDelay1,wfXave -col=S:tune:hpdl:z:GetDelay2,wfYave ${rootname}.sdds.proc &
            SetStatus "The best mixer delay found: xdelay=$xDelay, ydelay=$yDelay"
            if [APSYesNoPopUp "Do you want set the mixer delay to x=$xDelay, and y=$yDelay now?"] {
                if [catch {exec cavput -list=S:tune:hpdl:z:SetDelay1=$xDelay,S:tune:hpdl:z:SetDelay2=$yDelay -pend=20} result] {
                    return -code error "Error setting mixer delays: $result"
                }
                SetStatus "mixer delay was set to xdelay=$xDelay, ydelay=$yDelay"
            }
        }
        SampleDelay {
            set files [glob ${rootname}-???]
            if ![llength $files] {
                return -code error "No files found for $rootname ."
            }
            if [catch {eval exec sddscombine $files -pipe=out \
                         | sddsprocess -pipe \
                         "-redefine=par,Step,i_page,type=long" \
                         \"-process=S:P0FB:scope:gtr:waveform0,ave,wfXave1\" \
                         \"-process=S:P0FB:scope:gtr:waveform1,ave,wfYave1\" \
                         | sddsprocess -pipe \"-redefine=par,wfXave,wfXave1 abs\" \
                         \"-redefine=par,wfYave,wfYave1 abs\" \
                         | sddscollapse -pipe \
                         | sddsprocess -pipe=in ${rootname}.sdds.proc \
                         -process=wfXave,max,xDelay,position,functionOf=S:tune:hpdl:x:GetDelay \
                         -process=wfYave,max,yDelay,position,functionOf=S:tune:hpdl:y:GetDelay } result] {
                return -code error "Error processing sample delay: $result"
            }
            set xDelay [format %.2f [exec sdds2stream -par=xDelay ${rootname}.sdds.proc]]
            set yDelay [format %.2f [exec sdds2stream -par=yDelay ${rootname}.sdds.proc]]
            exec sddsplot -sep -col=S:tune:hpdl:x:GetDelay,wfXave -col=S:tune:hpdl:y:GetDelay,wfYave ${rootname}.sdds.proc &
            SetStatus "The best mixer delay found: xdelay=$xDelay, ydelay=$yDelay"
            if [APSYesNoPopUp "Do you want set the sample delay to x=$xDelay, and y=$yDelay now?"] {
                if [catch {exec cavput -list=S:tune:hpdl:x:SetDelay=$xDelay,S:tune:hpdl:y:SetDelay=$yDelay -pend=20} result] {
                    return -code error "Error setting mixer delays: $result"
                }
                SetStatus "sample delay was set to xdelay=$xDelay, ydelay=$yDelay"
            }
            
        }
        Attenuator {
            set  files [glob ${rootname}-???]
            if ![llength $files] {
                return -code error "No files found for $rootname ."
            }
            if [catch {eval exec sddscombine $files  -pipe=out \
                         | sddsprocess -pipe \
                         "-redefine=par,Step,i_page,type=long" \
                         \"-process=S:P0FB:scope:gtr:waveform0,ave,wfXave\" \
                         \"-process=S:P0FB:scope:gtr:waveform1,ave,wfYave\" \
                         | sddscollapse -pipe \
                         | sddsprocess -pipe=in -process=*ave,max,%sMax ${rootname}.sdds.combine } result] {
                 return -code error "Error processing attenuator scan1: $result"
            }
            if [catch {exec sddsprocess ${rootname}.sdds.combine -pipe=out \
                         | sddsprocess -pipe "-redefine=col,xProc,wfXave $wfAveXtarget - sqr" \
                         | sddsprocess -pipe=in -process=xProc,min,xAtt,functionOf=C0:P0FB:SumAttSet.A,position \
                         -process=xProc,min,xTarget \
                         ${rootname}.sdds.x.proc } result] {
                return -code error "Error processing attenuator scan for x att: $result"
            }
            set xatt [format %.0f [exec sdds2stream -par=xAtt ${rootname}.sdds.x.proc]]
            if [catch {exec sddsprocess ${rootname}.sdds.combine -pipe=out \
                         | sddsprocess -pipe "-redefine=col,yProc,wfXave $wfAveYtarget - sqr" \
                         | sddsprocess -pipe=in -process=yProc,min,yAtt,functionOf=C1:P0FB:SumAttSet.A,position \
                         -process=yProc,min,yTarget \
                         ${rootname}.sdds.y.proc } result] {
                return -code error "Error processing attenuator scan for y att: $result"
            }
            set yatt [format %.0f [exec sdds2stream -par=yAtt ${rootname}.sdds.y.proc]]
            exec sddsplot -mode=y=log -col=C0:P0FB:SumAttSet.A,xProc ${rootname}.sdds.x.proc -par=xAtt,xTarget -grap=sym,scale=3,sub=1 ${rootname}.sdds.x.proc &
            exec sddsplot -mode=y=log -col=C1:P0FB:SumAttSet.A,yProc ${rootname}.sdds.y.proc -par=yAtt,yTarget -grap=sym,scale=3,sub=1 ${rootname}.sdds.y.proc &
            
            SetStatus "The target attenuator found: xattenuator=$xatt, yattenuator=$yatt"
            if [APSYesNoPopUp "Do you want set attenuator to x=$xatt, and y=$yatt now?"] {
                if [catch {exec cavput -list=C0:P0FB:SumAttSet.A=$xatt,C1:P0FB:SumAttSet.A=$yatt -pend=20} result] {
                    return -code error "Error setting mixer delays: $result"
                }
                SetStatus "attenuator was set to x=$xatt, y=$yatt"
            }
            
        }
        SamplePattern {
            set  files [glob ${rootname}-???]
            if ![llength $files] {
                return -code error "No files found for $rootname ."
            }
            if [catch {eval exec sddscombine $files  -pipe=out \
                         | sddsprocess -pipe \
                         "-redefine=par,Step,i_page,type=long" \
                         \"-process=S:P0FB:scope:gtr:waveform0,ave,xAve\" \
                         | sddsprocess -pipe \"-redefine=par,xAve,xAve abs\" \
                         | sddscollapse -pipe \
                         | sddsprocess -pipe \
                         -scan=col,Index,Filename,${rootname}-%ld,type=long \
                         | sddsprocess -process=xAve,max,MaxIndex,position,functionOf=Index -pipe=in \
                         $rootname.proc } result] {
                return -code error "Error processing Sample Pattern scan: $result"
            }
            set maxIndex [format %.0f [exec sdds2stream -par=MaxIndex $rootname.proc]]
            exec sddsplot -col=Index,xAve $rootname.proc &
            
            if {$auto || [APSYesNoPopUp "Do you want to load the sample pattern of $maxIndex (which produced the maximum signal) now?"]} {
                if $loadSingle {
                    #load single pattern instead of 24
                    set loadFile1 ${rootname}PatternCtrl-[format %03d $maxIndex]
                    if [catch {exec sddsprocess $loadFile1 -process=Waveform,max,maxIndex,pos,functionOf=Index -pipe=out \
                                 | sddsprocess -pipe=in $loadFile1.single \
                                 "-redefine=col,Waveform,Index maxIndex - -1 > Index maxIndex - 5 < && ? Waveform : 0  $ " } result] {
                        return -code error "Error converting to single pattern: $result"
                    }
                    set loadFile $loadFile1.single
                } else {
                    set loadFile ${rootname}PatternCtrl-[format %03d $maxIndex]
                }
                if [catch {exec sddswput $loadFile -pend=20} result] {
                    return -code error "Error loading $loadFile : $result"
                }
                SetStatus "SamplePattern $loadFile was loaded."
                SetStatus "Please check if P0Feedback waveform has strong signal."
            }
        }
    }

}

proc PostProcessFile {args} {
    set directory ""
    set rootname ""
    APSParseArguments {directory rootname}
    set file $directory/${rootname}.sdds
    if ![file exist $file] {
        return -code error "$file does not exist."
    }
    set $directory
    set files [glob ${rootname}-*]
    #$rootname-* files are generated at each experiment step for the waveform pvs by sddswmonitor
    foreach file $files {
        set step [scan $file ${rootname}-%ld]
        if [catch {expr $step /2} result] {
            SetStatus "Invalid filename -- $file"
        } else {
            if [catch {exec sddsprocess -nowarn $file -redefine=par,Step,$step,type=long} result] {
                return -code error "Error in defining Step parameter for $file: $result"
            }
        }
    }

}

proc ScanSamplePhase {args} {
    global Fault0 Fault180 scanTime abortPhase
    set Fault0 0
    set Fault180 0
    
    if [catch {exec cavget -list=S:P0FB:ClockFaultMI.B2 -pend=10 -printErrors} error] {
        SetStatus "Error reading P0 status: $error"
        return
    }
    if $error {
        SetStatus "clear P0 sampling sync error ..."
        #clear error
        if [catch {exec cavput -list=S:P0FB:ClockFaultClrLO=15 -pend=10 } result] {
            SetStatus "Error clearing P0 sync error: $result"
            return
        }
    }
    foreach deg {0 180} {
        SetStatus "Set P0 sampling to $deg deg..."
        if [catch {exec cavput -list=S:P0FB:pinger:P0select=$deg -pend=30} result] {
            SetStatus "Error seting P0 phase to 0 deg: $result"
            return
        }
        set timeout [expr [clock seconds] + $scanTime]
        set var Fault$deg
        SetStatus "waiting for $scanTime seconds
..."
        while {[clock seconds]<$timeout} {
            if $abortPhase {
                set abortPhase 0
                SetStatus "Phase scan was aborted."
                return
            }
            if [catch {APScavget -list=S:P0FB:ClockFaultMI.B2 -pend=10 -printErrors} error] {
                SetStatus "Error reading P0 status: $error"
                return
            }
            if $error {
                incr $var
                SetStatus "clear P0 sampling sync error ..."
                #clear error
                if [catch {exec cavput -list=S:P0FB:ClockFaultClrLO=15 -pend=10 } result] {
                    SetStatus "Error clearing P0 sync error: $result"
                    return
                }
            }
            after 1000
            update
        }
    }
    SetStatus "0 degree fault counts: $Fault0"
    SetStatus "180 degree fault counts: $Fault180"
    if {$Fault0<$Fault180} {
        set deg 0
    } elseif {$Fault180<$Fault0} {
        set deg 180
    } else {
        SetStatus "both 0 and 180 degree fault counts are $Fault0."
        return
    }
    SetStatus "Set P0 phase to $deg degree..."
    if [catch {exec cavput -list=S:P0FB:pinger:P0select=$deg -pend=10} result] {
        SetStatus "Error set P0 phase to $deg: $result"
        return
    }
    if [catch {exec cavput -list=S:P0FB:ClockFaultClrLO=15 -pend=10 } result] {
        SetStatus "Error clearing P0 sync error: $result"
        return
    }
    SetStatus "done."
}


APSApplication . -name P0FBScan -version $CVSRevisionAuthor \
      -overview {scan P0Feedback mixer delay}

APSScrolledStatus .status -parent .userFrame -textVariable mainStatus -width 100 \
      -withButtons 1

set outputDir [APSGoToDailyDirectory -subdirectory P0FBScan]
set rootname MixerDelay
set Steps 40
set interval 1
set description ""
set initValue -4.0
set finalValue 4.0
set width 25

APSLabeledEntry .dir -parent .userFrame -label "Output Directory: " -textVariable outputDir -packOption "-fill x -expand 1" \
  -width 80
APSButton .daily -parent .userFrame.dir -size small -text "daily" \
  -command "set outputDir [APSGoToDailyDirectory -subdirectory P0FBScan]" -packOption "-side right"
APSLabeledEntry .desc -parent .userFrame -label "Experiment Description: " -textVariable description \
  -packOption "-fill x -expand 1" -width 80

set wList [APSTabFrame .tab -parent .userFrame -label "" -labelList {Attentuator SampleDelay MixerDelay SamplePhase} \
  -width 800 -height 150]
set p1 [lindex $wList 0]
set p2 [lindex $wList 1]
set p3 [lindex $wList 2]
set p4 [lindex $wList 3]
#set p4 [lindex $wList 3]




#p1 -- attenuator 
set AttenuatorSteps 32
set AttenuatorRootname Attentuator00
set wfAveXtarget 2000
set wfAveYtarget 2000
APSLabeledEntry .root -parent $p1 -label "Output rootname:" -textVariable AttenuatorRootname -width 70
APSLabeledEntry .stets -parent $p1 -label "Steps: " -textVariable AttenuatorSteps -width 70
APSLabeledEntry .xtarget -parent $p1 -label "Waveform average x target:" -textVariable wfAveXtarget -width 70
APSLabeledEntry .ytarget -parent $p1 -label "Waveform average y target:" -textVariable wfAveYtarget -width 70
APSButton .scan -parent $p1 -text "Start Scan" -command "StartScan -scanType Attenuator"
APSButton .process -parent $p1 -text "Process Data" -command "ProcessData -scanType Attenuator"



#P3 -- sample delay
APSFrameGrid .grid -parent $p2 -xList {x1 x2}
set w1 $p2.grid.x1
set w2 $p2.grid.x2
set SampleDelaySteps 41
set SampleDelayRootname SampleDelay00
set SampleDelayInitValue -8
set SampleDelayFinalValue 8
APSLabeledEntry .stets -parent $w1 -label "Steps: " -textVariable SampleDelaySteps -width $width
APSLabeledEntry .interval -parent $w2 -label "Interval (seconds): " -textVariable interval -width $width
APSLabeledEntry .init -parent $w1 -label "Delay Scan Start Value: " -textVariable SampleDelayInitValue -width $width
APSLabeledEntry .final -parent $w2 -label "Delay Scan Stop Value: " -textVariable SampleDelayFinalValue -width $width
APSLabeledEntry .root -parent $w1 -label "Output rootname:" -textVariable SampleDelayRootname -width $width
APSButton .scan -parent $p2 -text "Start Scan" -command "StartScan -scanType SampleDelay"
APSButton .process -parent $p2 -text "Process Data" -command "ProcessData -scanType SampleDelay"


#mixerdelay
APSFrameGrid .grid -parent $p3 -xList {x1 x2}
set w1 $p3.grid.x1
set w2 $p3.grid.x2
set MixerDelaySteps 31
set MixerDelayRootname MixerDelay00
set MixerDelayInitValue -4
set MixerDelayFinalValue 4
APSLabeledEntry .stets -parent $w1 -label "Steps: " -textVariable MixerDelaySteps -width $width
APSLabeledEntry .interval -parent $w2 -label "Interval (seconds): " -textVariable interval -width $width
APSLabeledEntry .init -parent $w1 -label "Delay Scan Start Value: " -textVariable MixerDelayInitValue -width $width
APSLabeledEntry .final -parent $w2 -label "Delay Scan Stop Value: " -textVariable MixerDelayFinalValue -width $width
APSLabeledEntry .root -parent $w1 -label "Output rootname:" -textVariable MixerDelayRootname -width $width
APSButton .scan -parent $p3 -text "Start Scan" -command "StartScan -scanType MixerDelay"
APSButton .process -parent $p3 -text "Process Data" -command "ProcessData -scanType MixerDelay"

#sample phase scan
set Fault0 0
set Fault180 0
#scan 5 minutes
set scanTime 120 
set abortPhase 0
APSLabeledEntry .time -parent $p4 -label "Wait Time (seconds):" -textVariable scanTime -width 20
APSLabeledOutput .fault0 -parent $p4 -label "0 deg faults:" -textVariable Fault0 -width 20
APSLabeledOutput .fault1 -parent $p4 -label "180 deg faults:" -textVariable Fault180 -width 20
APSButton .start -parent $p4 -text "Start Scan" -command "ScanSamplePhase"
APSButton .abort -parent $p4 -text "Abort" -command "set abortPahse 1"
