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

#
# $Log: not supported by cvs2svn $
# Revision 1.26  2011/03/02 22:07:29  shang
# moved the clock shift, P0 phase and acq delay parameters to config file, they will be restored when switch plane.
#
# Revision 1.25  2011/03/01 22:20:31  shang
# committing CY's changes.
#
# Revision 1.24  2009/06/19 19:57:52  shang
# updated the scanClockPhase procedure to disable booster trigger, enable sr trigger before scan, and then enable booster triggers, disable sr triggers after scan.S
#
# Revision 1.23  2009/03/04 20:56:18  shang
# update the scalars file.
#
# Revision 1.22  2009/01/21 23:37:44  shang
# changed the x and y label of the contour plots
#
# Revision 1.21  2008/11/20 16:26:41  shang
# removed "measure ADC delay" button since it is no longer needed.
#
# Revision 1.20  2008/11/05 20:51:03  shang
# merged CY's changes
#
# Revision 1.19  2008/10/06 13:52:37  shang
# modified because the setBoosterClockShift arguments changed.
#
# Revision 1.18  2008/10/01 14:45:14  shang
# changed the archive file time string to be the time at data taken.
#
# Revision 1.17  2008/10/01 13:48:13  shang
# added setting the input signal to SUM before scan ADC delay and restoring the original input after scan, and added text message to before and after clock shift.
#
# Revision 1.16  2008/09/30 23:25:20  shang
# merged CY's changes.
#
# Revision 1.15  2008/08/06 15:09:08  shang
# merged CY's changes: added P0 selection and changed the "adjust clock phase".
#
# Revision 1.14  2008/08/04 18:34:50  shang
# added -scalars option to sddswmonitor, and log/non-log scales to processData, and removed the cut-off frequency, changed by CY.
#
# Revision 1.13  2008/08/01 19:54:06  shang
# merged CY's private version.
#
# Revision 1.12  2008/07/07 20:12:04  shang
# removed fileindex, but generates new file based on the filename.
#
# Revision 1.11  2008/06/16 15:08:57  shang
# it now increases the file name index automatically after the data is being taken.
#
# Revision 1.10  2008/06/13 18:55:18  shang
# made extensive changes per CY's request:a)switched waveform1 to waveform0, waveform1 is for testing. b)added scale options for tune contour plots c)replaced "Switch SUM" button by "Switch input to S" for synchrotron tune measurement, which uses X input with drive off. d)added the input label to the extension of the output file to distinguish the tunes. e)added "adjust clock phase" button to adjust the clock phase to desired value.
#
# Revision 1.9  2008/04/14 19:57:29  shang
# changed the calculation of ADC delay so that it works for any number of samples.
#
# Revision 1.8  2008/04/10 14:26:14  shang
# added "Switch to Sum" button per CY's request
#
# Revision 1.7  2008/04/08 18:38:35  shang
# fixed the calculation of ADC delay
#
# Revision 1.6  2008/04/08 18:25:50  shang
# changed pv names by C.Y.
#
# Revision 1.5  2008/04/04 20:01:14  shang
# Added "Turn On Injection" button and displaying topup count and BTS charge in realtime.
#
# Revision 1.4  2008/04/02 22:13:39  shang
# made more changes per CY's request: changed the PV names and added more buttons.
#
# Revision 1.3  2008/02/06 16:34:31  soliday
# Removed calls to setfacl because it is no longer needed.
#
# Revision 1.2  2008/01/17 16:45:27  soliday
# Updated by putting setfacl command inside of catch statement.
#
# Revision 1.1  2007/12/19 23:19:26  shang
# first version for measuring booster tune with FPGA
#

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 CVSRevisionAuthor "\$Revision: 1.27 $ \$Author: shang $"

set archiveDir /home/helios/oagData/booster/tuneArchive/FPGAdata

set env(EPICS_CA_MAX_ARRAY_BYTES) "3000000"

set xDimMax 127
set xDim 127 
set yDim 1024 
### total valid data time in ms for the booster
set totalTimeMs 222
proc SetStatus {text} {
    global status
    set status "[exec date +%H:%M:%S]: $text"
    update
}


proc MakeArchiveWidget {widget args} {
    set parent ""
    APSStrictParseArguments {parent}
    APSFrame $widget -parent $parent -label "Archive" \
      -contextHelp "Controls archiving and review of archived tune data."

    set w $parent$widget.frame

    global startDay startMonth startYear outputDir rootname
    global endDay endMonth endYear
    APSDateTimeAdjEntry .date0 -parent $w \
      -dayVariable startDay -monthVariable startMonth -yearVariable startYear \
      -label "Start Y/M/D: "
    APSDateTimeAdjEntry .date1 -parent $w \
        -dayVariable endDay -monthVariable endMonth -yearVariable endYear \
        -label "End   Y/M/D: "
    APSFrameGrid .grid -parent $w -xList {x1 x2}
    APSLabeledOutput .count -parent $w.grid.x1 -label "Topup Injection Count:" -textVariable TopUpCount \
        -width 30
    APSLabeledOutput .bts -parent $w.grid.x2 -label "BTS charge:" -textVariable BTSCharge \
        -width 30
    if [catch {pv linkw {TopUpCount BTSCharge} \
    {Mt:TopUpTime2Inject.VAL BTS:CM:q.VAL} 30} result] {
        return -code error "Unable to link topup count and bts charge pv.s"
    }
    
    global errorInfo errorCode
    if {[pv umon TopUpCount]!=0 || [pv umon BTSCharge] !=0} {
        return -code error "pv umon error: $errorInfo, $errorCode"
    }
    APSLabeledEntry .dir -parent $w -label "Output Directory:" -textVariable outputDir \
        -width 70
    APSLabeledEntry .filename -parent $w -label "Rootname:" -textVariable rootname \
        -width 70
    global comment
    APSLabeledEntry .comment -parent $w -label "Comment:" -textVariable comment \
        -width 70
    global xstart xend xstart_S xend_S ystart yend ystart_S yend_S clockShifts acqDelay P0select
    set xstart 0.08 
    set xend 0.5
    set xstart_S 0
    set xend_S 0.25
    set ystart 0
    set yend 127
    set ystart_S 0
    set yend_S 127 
    set clockShifts 45 
    set acqDelay 168
    set P0select 0

    APSFrameGrid .gd -parent $w -xList {x1 x2} -yList {y1 y2 y3}
    APSLabeledEntryFrame .x1 -parent $w.gd.x1.y1 -label "X/Y x axis scale(start/end):" -width 10 \
        -variableList {xstart xend} -orientation horizontal 
    APSLabeledEntryFrame .y1 -parent $w.gd.x1.y2 -label "X/Y y axis scale(start/end):" -width 10  \
        -variableList {ystart yend} -orientation horizontal 
    APSLabeledEntryFrame .x2 -parent $w.gd.x2.y1 -label "S x axis scale(start/end):" -width 10  \
        -variableList {xstart_S xend_S} -orientation horizontal 
    APSLabeledEntryFrame .y2 -parent $w.gd.x2.y2 -label "S y axis scale(start/end):" -width 10  \
        -variableList {ystart_S yend_S} -orientation horizontal 
#    APSLabeledEntryFrame .clk -parent $w.gd.x1.y3 -label "sample clock shifts:        " -width 10  \
#	         -variableList {clockShifts} -orientation horizontal
#    APSLabeledEntryFrame .acq -parent $w.gd.x2.y3 -label "acq delay(sample clks):   " -width 10  \
#        -variableList {acqDelay} -orientation horizontal 
#    APSLabeledEntryFrame .pselect -parent $w -label "P0 select (0/180):          " -width 10  \
#        -variableList {P0select} -orientation horizontal
    
    APSButton .view -parent $w -text "Acquire and View Only" -command "saveData -archive 0"
    APSButton .history -parent $w -text "Review Plots" -command \
        "ReviewPlots" -contextHelp \
        "Displays history of tune values between the dates given above."
    APSButton .reproc -parent $w -text "Reprocess" -command \
        "ReviewPlots -reprocess 1" -contextHelp \
        "Peprocess and review data."

    APSButton .archive -parent $w -text "Acquire and Archive" -command "saveData -archive 1" \
        -contextHelp \
        "Saves tune data to the archive area."
    APSButton .review -parent $w -text "Review Achive spectra" -command \
        "ReviewPlots -archive 1" -contextHelp \
        "Reviews archived tune data between the dates given above."
    
    APSFrame .f1 -parent $parent
    set w $parent.f1.frame
    $w configure -bd 0
    APSButton .turn1 -parent $w -text "TurnOn TuneDrive" \
        -command "TurnOnOffTuneDrive -onoff on"
    APSButton .turn2 -parent $w -text "TurnOff TuneDrive" \
	-command "TurnOnOffTuneDrive -onoff off"
    APSButton .ping -parent $w -text "Set Pinger Waveform" \
        -command "SetPingerWaveform"
    APSButton .medm -parent $w -text "Launch MEDM screen" \
	-command "exec /home/helios/BOOSTER/bin/booTune &"
    APSFrame .f2 -parent $parent
    set w $parent.f2.frame
    $w configure -bd 0
    APSButton .turn -parent $w -text "Turn On Injection" \
        -command "TogglePulsedMagnetEnables -location GuntoBoosterExt"
    APSButton .switchx -parent $w -text "Switch input to X" \
	-command "SwitchInput X"
    APSButton .switchy -parent $w -text "Switch input to Y" \
	-command "SwitchInput Y"
    APSButton .switchs -parent $w -text "Switch input to S" \
	-command "SwitchInput S"
    APSButton .adjust -parent $w -text "Scan clock phase" \
        -command "ScanClockPhase"
}

set Xxdrive 134
set Xydrive 154
set Yxdrive 134
set Yydrive 0
set SUMxdrive 120
set SUMydrive 20
proc TurnOnOffTuneDrive {args} {
    set onoff ""
    set xdrive ""
    set ydrive ""
    APSParseArguments {onoff xdrive ydrive}
    global Xxdrive Xydrive Yxdrive Yydrive SUMxdrive SUMydrive
    SetStatus "turn $onoff tune drive ..." 
    if {(![string length $xdrive] || ![string length $ydrive]) && $onoff=="on"} {
        if [catch {exec cavget -list=B:TUNE:HP_1366A_P0_MBBO -pend=20} plane] {
            return -code error "Error turning on booster tune drive1: $plane"
        }
        if {$plane=="OFF" || $plane=="SPARE"} {
            SetStatus "drive is not being turned on.\nPlease select a plane X/Y/S on booster tune measurement multiplexer first before turn it on."
            return
        }
        set xdrive [set ${plane}xdrive]
        set ydrive [set ${plane}ydrive]
    }
    set onPVList [list B:DG1:aDelaySetAO=4.5e-7 \
                    B:DG1:bDelaySetAO=2.0e-6 \
                    B:DG1:cDelaySetAO=7.0e-7 \
                    B:DG1:dDelaySetAO=2.0e-6 \
                    B:DG1:trigModeSetMO=1 \
                    B:DG1:aOutputModeSetMO=0 \
                    B:DG1:cOutputModeSetMO=0 \
                    B:DG1:aOutputZSetBO=0 \
                    B:DG1:cOutputZSetBO=0 \
                    B:DG1:aOutputAmpSetAO=1 \
                    B:DG1:cOutputAmpSetAO=1 \
                    B:DG1:aOutputOffsetSetAO=0.0 \
                    B:DG1:cOutputOffsetSetAO=0.0 \
                    B:DG1:trigInputAmpSetAO=1.0 \
                    BOOTUNE:XAXIS:MATRE200SetVoltage=$xdrive \
                    BOOTUNE:YAXIS:MATRE200SetVoltage=$ydrive ]
    if {$onoff=="on"} {
        if [catch {exec cavput -pend=30 -list=[join $onPVList ,] } result] {
            return -code error "Error turning on booster tune drive: $result"
        }
    } else {
        if [catch {exec cavput -pend=30 \
                     -list=BOOTUNE:XAXIS:MATRE200SetVoltage=0,BOOTUNE:YAXIS:MATRE200SetVoltage=0 } result] {
            return -code error "Error turning off booster tune drive: $result"
        }
    }
    after 2000
    SetStatus "done."
}

set startDelay 0
set endDelay 0
set intervalMs 2.0
proc SetPingerWaveform {args} {
    global startDelay endDelay interval response  totalTimeMs intervalMs 
    
    set response 0
    APSDialogBox .diag -name "Timing parameters" -okCommand "set response 1"  \
	-cancelCommand "set response cancel"
    APSLabeledEntry .start -parent .diag.userFrame -label "Total time (ms, < 226):" \
	-textVariable totalTimeMs  -width 20
    APSLabeledEntry .interval -parent .diag.userFrame -label "interval (ms, > 1.5):" \
	-textVariable intervalMs -width 20
    tkwait variable response
    if {$response=="cancel"} {
	SetStatus "set pinger waveform was cancelled."
	return
    }
    SetStatus "set pinger waveform ..."
    if [catch {exec /home/helios/PAR/bin/makePingerPattern $intervalMs $totalTimeMs} strResult] {
	SetStatus "set pinger timing failed: $strResult"
	return
    }
    if [catch { exec caput -m  B:tune:pinger:controlSetWF $strResult } result] {
	SetStatus "set pinger waveform failed: $result"
	return
    }
    SetStatus "done."
}

proc SwitchInput {plane} {
    global Xxdrive Xydrive Yxdrive Yydrive Sxdrive Sydrive
    SetStatus "Switching to $plane ..."
    global inputChannel
    set inputChannel $plane
    switch $plane {
        S {
            set plane SUM
            set xdrive 0
            set ydrive 0
            set onoff off
            
        }
        X {
            set xdrive $Xxdrive
            set ydrive $Xydrive
            set onoff on
        }
        Y {
            set xdrive $Yxdrive
            set ydrive $Yydrive
            set onoff on
        }
        default {
            set xdrive 0
            set ydrive 0
            set onoff off
        }
    }
    if [catch { TurnOnOffTuneDrive -xdrive $xdrive -ydrive $ydrive -onoff $onoff} result] {
        SetStatus "Error in turnOnOffTuneDrive: $result"
        return
    }
    if [catch {exec cavput -list=B:TUNE:HP_1366A_P0_MBBO=$plane,BOOTUNE:XAXIS:MATRE200SetVoltage=$xdrive,BOOTUNE:YAXIS:MATRE200SetVoltage=$ydrive } result] {
        SetStatus "Unable to switch to $plane plane: $result"
        return
    }
    if [catch {exec cavput -list=BOOTUNE:XAXIS:MATRE200SW=1,BOOTUNE:YAXIS:MATRE200SW=1 -pend=20} result] {
        SetStatus "Unable to set  BOOTUNE:XAXIS:MATRE200SW  and BOOTUNE:YAXIS:MATRE200SW to 1: $result"
        return
    }
    #load tune parameters
    if {$plane!="S"} {
	if [catch {exec sddscasr -restore \
		       /home/helios/oagData/booster/tuneArchive/inputFiles/tuneconfig.[string tolower $plane] -pend=30} result] {
	    SetStatus "Error in loading tune parameters for $plane plane: $result"
	    return 
	}
    }
    after 2000
    SetStatus "done"
}


proc Measure {args} {
    set outputFile ""
    set commandline 0
    APSParseArguments {outputFile commandline}
    
    global clockShifts acqDelay P0select   
    
   
    if !$commandline {
        SetStatus "1. set auto restart to no on tunePlots.adl (B:tune:fftAvg:gtr:autoRestart) "
    }
    if [catch {exec cavput -list=B:tune:fftAvg:gtr:autoRestart=0} result] {
        return -code error $result
    }
    APSWaitWithUpdate -waitSeconds 2 -updateInterval 1
    if !$commandline {
        SetStatus "2. disarm and arm the acquisition the FftWaterfallPlots.adl (B:tune:fftAvg:gtr:arm)"
    }
    
    if [catch {exec cavput -list=B:tune:fftAvg:gtr:arm=1} result] {
        return -code error $result
    }
    APSWaitWithUpdate -waitSeconds 2 -updateInterval 1
    if !$commandline {
        SetStatus "4. take data..."
    }
    global env xDim yDim
    set env(EPICS_CA_MAX_ARRAY_BYTES) 3000000
    set interval [expr 1.0 / 2048.0]
    APSWaitWithUpdate -waitSeconds 5 -updateInterval 1
    set timeStr [clock format [clock seconds] -format %Y-%j-%m%d:%H%M%S]
    if [catch {exec sddswmonitor -erase -pvnames=B:tune:fftAvg:gtr:waveform0  \
                   -xparameter=name=x,dimension=$xDim,interval=1,minimum=0 \
                   -yparameter=name=y,dimension=$yDim,interval=$interval,minimum=0 \
		   "-scalars=/home/helios/BOOSTER/tuneMeasurement/tuneScalars.mon" \
                   $outputFile } result] {
        return -code error $result
    }
    if !$commandline {
        SetStatus "5a: collect tune peak data..."
        if [catch {exec cavput -list=B:tune:peak:gtr:arm=1 -pend=10 } result] {
            return -code error "Error arming tune: $result"
        }
        after 1000
        if [catch {exec sddswmonitor -erase -pvnames=B:tune:peak:gtr:waveform0,B:tune:peak:gtr:waveform1,B:tune:peak:gtr:waveform2 \
                     -steps=1 -interval=1.0 $outputFile.peak } result] {
            return -code error "error collecting tune peak data: $result"
        }
    }
    if !$commandline {
        set plot 1
    } else {
        set plot 0
    }
    if !$commandline {
	SetStatus "5. process data."
    }
    if [catch {ProcessData -filename $outputFile -plot $plot} result] {
        return -code error $result
    }
    if !$commandline {
        SetStatus "done."
    }
    return $timeStr
}

proc saveData {args} {
    set archive 0
    APSParseArguments {archive}
    
    global archiveDir outputDir rootname 
     
    global inputChannel 
    if ![info exist inputChannel] {
        if [catch {exec cavget -list=B:TUNE:HP_1366A_P0_MBBO } inputChannel] {
            return -code error $input
        }
    }
    
    set filename ${rootname}-${inputChannel}.0000 
    set newfilename [APSNextGenerationedName -name $filename -separator . -directory $outputDir -newFile 1] 
    
    if [catch {Measure -outputFile $outputDir/$newfilename} timeStr] {
        return -code error $timeStr
    }
    if $archive {
        if [APSYesNoPopUp "Archive this data?"] {
            set filename1 $archiveDir/${timeStr}.$inputChannel
            exec cp $outputDir/$newfilename $filename1
        }
    }
}

proc ReviewPlots {args} {
    set archive 0
    set reprocess 0
    APSParseArguments {archive reprocess}
    
    global outputDir archiveDir xstart xend ystart yend xstart_S xend_S ystart_S yend_S
    if $archive {
        set dir $archiveDir
    } else {
        set dir $outputDir
    }
   # set filename [APSFileSelectDialog [APSUniqueName .] -width 100 -listDir $dir -reverseSort 1 -listFilter *.???? -pattern *.????]
    set files [glob -nocomplain $dir/*.\[0-9\]\[0-9\]\[0-9\]\[0-9\]]
    
    if ![string length $files] {
        return
    }
    global filename
    set filename ""
    APSScrolledListWindow .select -name "Select file" \
	-label "Select File" \
	-itemList $files  -selectionVar filename
    tkwait variable filename
    if ![string length $filename] {
        return -code error "No file chosen!"
    }
    if {[regexp {\.S} $filename] || [regexp {\-S} $filename]} {
        exec sddscontour $filename -swapxy -quantity=BooTune -shade \
	-scale=$xstart_S,$xend_S,$ystart_S,$yend_S -ylabel=tune \
	-xlabel=traces -title=filename &
    } else {
	if {[regexp {\.X} $filename] || [regexp {\-X} $filename]} {
	    set xlabel xtune
	} elseif {[regexp {\.Y} $filename] || [regexp {\-Y} $filename]} {
	    set xlabel ytune
	} else {
	    set xlabel tune
	}
        exec sddscontour $filename -swapxy -quantity=BooTune -shade \
	-scale=$xstart,$xend,$ystart,$yend -xlabel=traces \
	-ylabel=$xlabel -title=filename &
        if $reprocess {
            catch {exec rm $filename.peak.proc}
        }
        if ![file exist $filename.peak.proc] {
            #re-processing data
            set ns 204
            set nseq [expr 1024 - $ns]
            set bseq [expr 0.5/2014.0 * $ns]
            set tmpRoot /tmp/[APSTmpString]                                           
            if [catch {exec sddssequence $tmpRoot.1 -def=tune -sequence=begin=$bseq,number=$nseq,delta=0.00048828125
                exec sddssequence $tmpRoot.2 -def=time,units=ms -sequence=begin=0,number=128,delta=1.75
                exec sddsbreak $filename -row=1024 -pipe=out \
                         | sddsprocess -pipe -clip=$ns,0 \
                         | sddsxref $tmpRoot.1 -take=tune -pipe -nowarn \
                         | sddsprocess -pipe -process=BooTune,max,$xlabel,position,functionOf=tune \
                         | sddscollapse -pipe \
                         | sddsxref $tmpRoot.2 -take=time -pipe \
                         | sddsprocess -pipe \
                         -filter=col,$xlabel,0.2482,0.2500,! \
                         | sddsoutlier -pipe=in -col=$xlabel $filename.peak.proc  } result] {
                return -code error $result
            }
        }
        exec sddsplot -col=time,${xlabel} $filename.peak.proc  -grap=sym,fill,scale=1.5 -title=$filename.peak.proc &
    }
}



proc ProcessData {args} {
    global xDim xDimMax yDim totalTimeMs comment env intervalMs
    set filename ""
    set plot 1
    APSParseArguments {filename plot}
    set intervalMs 1.5
    #    set interval 2
    #    if {$interval<=1.5} {
    #        return -code error "The tune timing interval is <=1.5!"
    #    }
    #    set dim [format %.0f [expr $totalTimeMs / $interval]]
    #    if { $dim > $xDimMax } {
    #    	set dim $xDimMax 
    #	}
    set dim 128
    set cutoff [expr $dim * $yDim - 1]
    set xDim $dim
    set fftFormat [exec sdds2stream -para=B:tune:crosspointControl.B3 $filename] 
    if {$fftFormat ==  0} {
        if [catch {exec sddsprocess $filename $filename.1 -nowarnings \
                     "-reprint=par,Description,[APSMakeSafeQualifierString $comment]($env(USER))" \
                     "-redefine=col,BooTune,B:tune:fftAvg:gtr:waveform0" \
                     -redefine=para,xDimension,$xDim,type=long \
                     -redefine=para,yDimension,$yDim,type=long } result] {
            return -code error $result
        }
    } else {
        if [catch {exec sddsprocess $filename $filename.1 -nowarnings \
                     "-reprint=par,Description,[APSMakeSafeQualifierString $comment]($env(USER))" \
                     "-redefine=col,BooTune,2 B:tune:fftAvg:gtr:waveform0 1024 / pow" \
                     -redefine=para,xDimension,$xDim,type=long \
                     -redefine=para,yDimension,$yDim,type=long } result] {
            return -code error $result
        }
    }
    if {[regexp {\.X} $filename] || [regexp {\-X} $filename]} {
        set xlabel xtune
    } elseif  {[regexp {\.Y} $filename] || [regexp {\-Y} $filename]} {
        set xlabel ytune
    } else {
        set xlabel tune
    }
    exec mv $filename.1 $filename
    if $plot {
        global xstart ystart xend yend xstart_S xend_S ystart_S yend_S 
        if {[regexp {\.S} $filename] || [regexp {\-S} $filename]} {
            exec sddscontour $filename  -swapxy -quantity=BooTune -shade  -scale=$xstart_S,$xend_S,$ystart_S,$yend_S  -title=filename -ylabel=tune -xlabel=traces &
        } else {
            exec sddscontour $filename  -swapxy -quantity=BooTune -shade=100 -scale=$xstart,$xend,$ystart,$yend -title=filename -xlabel=traces -ylabel=$xlabel &
        }
    }
    set ns 204
    set nseq [expr 1024 - $ns]
    set bseq [expr 0.5/2014.0 * $ns]
    set tmpRoot /tmp/[APSTmpString]                                           
    if [catch {exec sddssequence $tmpRoot.1 -def=tune -sequence=begin=$bseq,number=$nseq,delta=0.00048828125
        exec sddssequence $tmpRoot.2 -def=time,units=ms -sequence=begin=0,number=128,delta=1.75
        exec sddsbreak $filename -row=1024 -pipe=out \
                 | sddsprocess -pipe -clip=$ns,0 \
                 | sddsxref $tmpRoot.1 -take=tune -pipe -nowarn \
                 | sddsprocess -pipe -process=BooTune,max,$xlabel,position,functionOf=tune \
                 | sddscollapse -pipe \
                 | sddsxref $tmpRoot.2 -take=time -pipe \
                 | sddsprocess -pipe \
                 -filter=col,$xlabel,0.2482,0.2500,! \
                 | sddsoutlier -pipe=in -col=$xlabel $filename.peak.proc  } result] {
        return -code error $result
    }
    exec sddsplot -col=time,${xlabel} $filename.peak.proc &
}

set clockPhase 15
proc ScanClockPhase {args} {
    global clockPhase diagresponse acqDelay P0select clockShifts
    ### switch to sum for scanning and set the extra delay to 200 ms.--CY
  
    SwitchInput S
    if [catch {exec cavput -list=B:tune:boosterInjTriggerEV.OUT -list=0,3,9 -list==0 -pend=10} result] {
        return -code error "Unable to disable booster triggers: $result"
    }
    if [catch {exec cavput -list=B:tune:storageInjTriggerEV.OUT -list=0,3,9 -list==1 -pend=10 } result] {
        return -code error "Unable to enable sr triggers: $result"
    }
    
    SetStatus "Start clock phase scan..."
    if [catch {exec cavput -list=B:tune:adc:gtr:numberPTE=200 -pend=20} result] {
        return -code error "Unable to start clock scan2: $result"
    }
    if [catch {exec  cavput -list=B:tune:ClockScanStartBO=1 -pend=20} result] {
        return -code error "Unable to start clock scan2: $result"
    }
    ### add 20 seconds waiting for the scanning to completed. 
    SetStatus "Wait for 20 seconds...."
    APSWaitWithUpdate -waitSeconds 20 -updateInterval 1
    if [catch {exec cavput -list=B:tune:boosterInjTriggerEV.OUT -list=0,3,9 -list==1 -pend=10} result] {
        return -code error "Unable to disable booster triggers: $result"
    }
    if [catch {exec cavput -list=B:tune:storageInjTriggerEV.OUT -list=0,3,9 -list==0 -pend=10 } result] {
        return -code error "Unable to enable sr triggers: $result"
    }
    SetStatus "done."
}

set comment "No comment" 
set rootname booTune
set outputFile ""
set system Booster
set args $argv 
APSParseArguments {outputFile system}
set outputDir [APSGoToDailyDirectory -subdirectory ${system}Tune]
if ![string length $outputFile] {
    APSApplication . -name BoosterFPGAMeasureTunes -version $CVSRevisionAuthor \
        -overview {Helps with booster tune measurement setup and data collection.}
    
    set status Working...
    APSScrolledStatus .status -parent .userFrame -textVariable status \
        -width 60 -height 6
    update
    
    MakeArchiveWidget .data -parent .userFrame
} else {
    wm withdraw .
    if [catch {Measure -outputFile $outputFile -commandline 1} result] {
        puts stderr $result
        exit 1
    } else {
        exit 0
    }
}
