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

set CVSRevisionAuthor "\$Revision: 1.0 $ \$Author: shang $"
set args $argv
set Plane x
set Plot 0
set SetupScope 0
set GUI 1
set args $argv

set width 40
set centerFreq ""
set span ""
set averageNum ""
set sourceLevel ""
set outputDir [APSGoToDailyDirectory -subdirectory parTuneVSA]
set monitorFile /home/helios/oagData/par/vsaTuneArchive/parVsaTraceKickers.mon
set chirp PCH
set uniform UNIF
set range -25
set verbose 0
set RFOnOff ON
set description ""
set setupScope 0
set help 0
set plane x
set rootname parTune
#set varList {centerFreq span averageNum average sourceLevel outputOn  freqPoints resolution chirp uniform range repeatOn}
#set commandList {FREQ:CENT FREQ:SPAN AVER:COUNT AVER:STAT SOUR:VOLT OUTP SENSE:SWE:POIN BAND SOUR:FUNC WIND:GATE VOLT1:RANG AVER:TCON}
#set changeParList {centerFreq span averageNum sourceLevel range resolution}
set varList {centerFreq span averageNum average sourceLevel outputOn  freqPoints  chirp uniform range repeatOn}
set commandList {FREQ:CENT FREQ:SPAN AVER:COUNT AVER:STAT SOUR:VOLT OUTP SENSE:SWE:POIN  SOUR:FUNC WIND:GATE VOLT1:RANG AVER:TCON}
set changeParList {centerFreq span averageNum sourceLevel range}

APSParseArguments {plane plot setupScope GUI description verbose rootname range help}

if $help {
    puts "PARTuneMeasurementVSA \[-GUI <1|0> -verbose <1|0> -plane <x|y> -plot <1|0> -verbose <1|0> -description <string> -rootname <string>\]"
    puts "All the options are optional, if no arguments provided, a GUI will be brought up."
    exit 0
}

if !$GUI {
    wm withdraw .
}

proc SetStatus {text} {
    global status GUI verbose
    set status "[exec date]: $text"
    if {!$GUI && $verbose} {
	puts "[exec date]: $text"
    }
    update
}

foreach var {centerFreq span averageNum sourceLevel average outputOn} {
    set $var ""
}

proc SetSingleSetting {args} {
    set var ""
    set plane ""
    APSParseArguments {var plane}
    
    global varList commandList $var ${var}Readback
    if [string length $plane] {
	global $var.$plane
	set $var [set $var.$plane]
    }
    
    set index [lsearch -exact $varList $var]
    set comm [lindex $commandList $index]
    SetStatus "change(3) $comm to [set $var] ..."
    if [catch {exec hpSocketSend hpvecpar "${comm} [set $var]" } result] {
        return -code error "Error setting $comm to [set $var] : $result"
    }
    APSWaitWithUpdate -waitSeconds 1
    if [catch {exec hpSocketSend hpvecpar "${comm}?" } result] {
        return -code error "Error reading $comm : $result"
    }
    set ${var}Readback $result
    SetStatus "done."
}

proc ReadSetSettings {args} {
    set set 0
    APSParseArguments {set}
    global centerFreq span averageNum average sourceLevel outputOn repeatOn varList commandList
    eval global $varList

   # set commandList {FREQ:CENT FREQ:SPAN AVER:COUNT AVER:STAT SOUR:VOLT OUTP AVER:TCON}
    #set varList {centerFreq span averageNum average sourceLevel outputOn repeatOn }
    if ![regexp "DBM" $sourceLevel] {
        set sourceLevel ${sourceLevel}DBM
    }
    if $set {
        SetStatus "Setting parameters..."
        foreach comm $commandList var $varList {
            global ${var}Last
            SetStatus "change(1) $comm to [set $var] ..."
            if [catch {exec hpSocketSend hpvecpar "${comm} [set $var]" } result] {
                return -code error "Error setting $comm to [set $var] : $result"
            }
            after 1000
            if [catch {exec hpSocketSend hpvecpar "${comm}?" } result] {
                return -code error "Error reading $comm : $result"
            }
            global ${var}Readback
            set ${var}Readback $result
	   # puts "$var [set $var] [set ${var}Readback]"
        }
    } else {
        SetStatus "Reading..."
        foreach comm $commandList var $varList {
            if [catch {exec hpSocketSend hpvecpar "${comm}?" } result] {
                return -code error "Error reading $comm : $result"
            }
	    if {$var=="repeatOn"} {
		#read it again
		after 1000
		if [catch {exec hpSocketSend hpvecpar "${comm}?" } result] {
		    return -code error "Error reading $comm : $result"
		}
	    }
            global ${var}Readback
            set ${var}Readback $result
           # SetStatus "$comm $result $result"
	  #  puts "$comm $var $result"
	    
        }
	#source type has to chirp (PCH), can not be SIN (fixed sin)
	set chirp PCH
    }
    SetStatus "done."
}

proc ChangeRadioButton {args} {
    set var ""
    APSParseArguments {var}
    global $var ${var}Readback
    if {$var == "average" } {
        set comm AVER:STAT
    } elseif {$var == "outputOn"} {
        set comm OUTP
    } else {
        set comm AVER:TCON
    }
    SetStatus "change(2) $comm to [set $var] ..."
    if [catch {exec hpSocketSend hpvecpar "${comm} [set $var]" } result] {
        return -code error "Error setting $comm to [set $var] : $result"
    }
    after 1000
    if [catch {exec hpSocketSend hpvecpar "${comm}?" } result] {
        return -code error "Error reading $comm : $result"
    }
    set ${var}Readback $result
    SetStatus "done."
}

proc RecallConfiguration {args} {
    set configDir /home/helios/oagData/par/vsaTuneArchive
    global configFile
    set fileList [glob $configDir/*.sta -nocomplain]
    if ![llength $fileList] {
        SetStatus "no config files found at $configDir."
        return
    }
    set configFile [APSChooseItemFromList -name "Select a config file" \
                       -multiItem 0  \
                       -returnList $fileList \
                       -itemList $fileList \
                       -contextHelp "Select one of config files" ]
    SetStatus "$configFile chosen"
    if [catch {exec hpVecRestore -unit par -filename $configFile \
             } result ] {
        return -code error "RecallConfig: $result"
    }
    SetStatus "$configFile restored. (wait 30 seconds before measuring tunes.)"
}

set setup 1
proc GetWaveformData {args} {
    set setup 1
    set plane ""
    set rootname ""
    set plot 1
    APSParseArguments {setup rootname plane plot}
    
    global averageNumReadback outputDir monitorFile description Plane tcycle first
    global repeatOnReadback outputOnReadback repeatOn outputOn RFOnOff waitTimeAfterSetup
    if ![string length $plane] {
	if ![string length $Plane] {
	    SetStatus "plane is not selected, please select a plane first!"
	    return
	}
        set plane $Plane
    }
    if $setup {
        SetPars -plane $plane
	SetStatus "wait $waitTimeAfterSetup seconds after setting VSA parameters..."
	APSWaitWithUpdate -waitSeconds $waitTimeAfterSetup -updateInterval 1
    }
    
    cd $outputDir
    
    set tmpRoot /tmp/[APSTmpString]
    if ![string length $rootname] {
        set rootname [clock format [clock seconds] -format %Y-%j-%m%d.%H%M%S]
    }
    set filename $outputDir/$rootname.${plane}tune
    if [catch {exec sddsmonitor -step=1 $monitorFile $tmpRoot.scalars 
        exec sddsexpand $tmpRoot.scalars $tmpRoot.par } result] {
        return -code error "Error reading pvs in $monitorFile: $result"
    }
   # if $setup {
        # AVER:TCON NORM ensures that averaging is normal, i.e. not repeating.
    SetStatus "Collecting waveform data for $plane plane ..."
    if {$plane=="s"} {
	set outputOn OFF
	set outputOnReadback +0
    } else {
	set outputOn $RFOnOff
	switch $RFOnOff {
	    ON {
		set outputOnReadback +1
	    }
	    OFF {
		set outputOnReadback +0
	    }
	}
    }
    SetStatus "outputOn: $outputOn"
    if [catch {exec hpSocketSend hpvecpar \
		   "OUTP $outputOn" -pause=0.1 \
		   "AVER:TCON NORM" -pause=0.1 "PAUS" -pause=0.1 \
		   "AVER:COUN $averageNumReadback" -pause=0.1 \
		   "ABOR;*WAI"\
	       } result] {
	return -code error "error setting up booster vsa: $result"
    }
    
   # set repeatOn NORM
   # set repeatOnReadback NORM
    set waitTime [format %.0f [expr 0.5 * $averageNumReadback +2]]
    SetStatus "Waiting $waitTime seconds ..."
    APSWaitWithUpdate -waitSeconds $waitTime -updateInterval 1
    set operationCondition 1
    set timeout [expr [clock seconds] + 30]
    SetStatus "Waiting for HP VSA to acquire data"
    while {[clock seconds]<$timeout} {
            set operationCondition [exec hpSocketSend hpvecpar \
					"STAT:OPER:COND?"]
	set opt [scan $operationCondition %ld]
	if {$opt ==32 || $opt == 56 || $opt==0 } {
	    break
	}
	after 2000
    }
    set operationCondition [exec hpSocketSend hpvecpar \
				"STAT:OPER:COND?"]
    set opt [scan $operationCondition %ld]
    if {$opt!=32 && $opt!=56 && $opt!=0} {
	SetStatus "Failed to acquire waveform in 30 seconds, check the par VSA."
	SetStatus "DEBUG: STAT:OPER:COND? returned $opt"
	return
    }
    SetStatus "HP VSA has completed data acquisition"
    # }
    if {$plane=="s"} {
        #turn off source before measuring the waveform for s tune.
        if [catch {exec hpSocketSend hpvecpar "OUTP OFF" } result] {
            return -code error "Error turn off source: $result"
        }
	set outputOn OFF
	set outputOnReadback +0
    }
    SetStatus "saving VSA waveform..."
    if [catch {exec hpVecTrace -hpvecpar a $tmpRoot.data } result] {
        return -code error "Error reading hpvecpar waveform data: $result"
    }
    SetStatus "Turn off source..."
    if [catch {exec hpSocketSend hpvecpar "OUTP OFF" } result] {
        return -code error "Error turn off source: $result"
    }
    # set outputOn OFF
    #set outputOnReadback +0
    if {$plane=="s" } {
        if [catch {exec sddsxref $tmpRoot.data $tmpRoot.par -transfer=par,* -leave=* -pipe=out \
                     | sddsconvert -pipe -edit=col,*,ai/$plane/ \
                     | sddsprocess -pipe \
                     "-define=par,PARRF,A014-IETS:BTC:BInjSetFreqM 36.0 /" \
                     "-define=col,${plane}Tune,${plane}Frequency PARRF / 1.0e6 * 1 mod" \
                     | sddsprocess -pipe \
                     -process=${plane}Waveform,max,maxFreq,pos,functionOf=sFrequency \
		       | sddsprocess -pipe=in $filename \
		       "-print=par,Description,[APSMakeSafeQualifierString $description]" \
                     "-redefine=col,sFreq,sFrequency maxFreq - 1000 *,units=kHz" \
                     "-process=sWaveform,max,sFreqPos,pos,functionOf=sFreq,lowerlimit=1" \
                     "-reprint=par,TuneLabel," } result] {
            return -code error "$result"
        }
	set tune [exec sdds2stream -par=sFreqPos $filename]
	if $plot {
	    exec sddsplot  -col=sFreq,${plane}WaveformPower -topline=@TuneLabel -leg=yname  $filename \
		-title=@Description &   
	}

    } else {
        if [catch {exec sddsxref $tmpRoot.data $tmpRoot.par -transfer=par,* -leave=* -pipe=out \
                     | sddsconvert -pipe -edit=col,*,ai/$plane/ \
                     | sddsprocess -pipe \
                     "-define=par,PARRF,A014-IETS:BTC:BInjSetFreqM 36.0 /" \
                     "-define=col,${plane}Tune,${plane}Frequency PARRF / 1.0e6 * 1 mod" \
                     | sddsprocess -pipe=in $filename  \
                     "-print=par,Description,[APSMakeSafeQualifierString $description]" \
                     "-redefine=col,${plane}Tune,${plane}Tune 0.5 > ? ${plane}Tune 1.0 - : ${plane}Tune $ " \
                     -process=${plane}Waveform,max,${plane}Tune,pos,functionOf=${plane}Tune  \
                     "-reprint=par,TuneLabel,\\\$gn\\\$r\\\$b${plane}\\\$n = %.4f,${plane}Tune"} result] {
            return -code error "Error processing data: $result"
        }
	set tune [exec sdds2stream -par=${plane}Tune $filename]
	if $plot {
	    exec sddsplot  -col=${plane}Tune,${plane}WaveformPower -title=@Description -topline=@TuneLabel -leg=yname  $filename &
	}
    }
    #if [catch {exec sddsxref $tmpRoot.data $tmpRoot.par -transfer=par,* -leave=* $filename } result] {
    #    return -code error "Error transferring parameters: $result"
    #}
    APSAddToTmpFileList -ID par -fileList "$tmpRoot.scalars $tmpRoot.par $tmpRoot.data"
   # exec sddsplot -sep -layout=1,2 -col=${plane}Tune,${plane}Waveform* -topline=@TuneLabel -leg=yname  $filename &
    SetStatus "waveform is saved in $filename."
    return $tune
}

proc SetPars {args} {
    set plane x
    set set 1
    APSParseArguments {plane set}
    global varList otherVarList changeParList
    eval global $varList
    eval global $otherVarList
    foreach var $changeParList {
	set $var [set ${var}.$plane]
    }
    update
    if [catch {ReadSetSettings -set $set} result] {
	return -code error "Error setting VSA parameters for $plane plane: $result"
    }
    if $set {
	SetStatus "Switch mux to $plane plane ..."
	if {$plane=="s"} {
	    set plane0 x
	} else {
	    set plane0 $plane
	}
	if [catch {exec cavput -list=P:BnchCln:Mux10mbbo=[string toupper $plane0],P:BnchCln:Mux20mbbo=${plane0}Tune -pend=30} result] {
	    return -code error "Error changing tune mux: $result"
	}
	SetStatus "done"
    }
}

proc SetDefaultPars {args} {
    global  changeParList otherVarList
    
    
    set otherVarList ""
    foreach plane {x y s} {
	foreach var $changeParList {
	    lappend otherVarList ${var}.$plane
	}
    }
    eval global $otherVarList
    set average ON

    set centerFreq.x +9.97e7
    set sourceLevel.x 0DBM
    set freqPoints.x 1601
    set span.x 5e5
    set resolution.x 3000
    set range.x -10
    set averageNum.x +10
    set average.x ON

    set centerFreq.y +9.99e7
    set sourceLevel.y -10DBM
    set freqPoints.y 1601
    set span.y 5e5
    set resolution.y 3000
    set range.y -35
    set averageNum.y +10
    set average.y ON
    
    set centerFreq.s 439.9185e6
    set span.s 3e5
    set sourceLevel.s -5DBM
    set freqPoints.s 1601
    #set resolution 716.1299
    set resolution.s 300
    set range.s -10
    set averageNum.s +10
    set average.s ON
    
}
#SetDefaultPars

proc CopyToArchive {args} {
    global outputDir archiveDir selectedFiles
    cd $outputDir
    set file [SelectFile -xytune 0]
    set filename [file tail $file]
    if ![file exist $archiveDir/$filename] {
        if ![APSYesNoPopUp "$filename already exist in archive, overwrite it?"] {
            return
        }
    }
    #SetStatus "copy $filename to archive..."
    exec cp $file $archiveDir/.
    SetStatus "copied $filename to archive."
}
proc CompareWithArchive {args} {
    global archiveDir tuneRef tuneRef outputDir selectTuneFile
    
    if {![string length $tuneRef]} {
        SetStatus "tune reference has to selected first."
        return
    }
    SetStatus "Select a tune file..."
    if [catch {SelectFile} file] {
        SetStatus "$file"
        return
    }
    set label1 [exec sdds2stream -par=TuneLabel $tuneRef]
    set label2 [exec sdds2stream -par=TuneLabel $file]
   # puts "$label1"
    set label "Ref: [join $label1]  Data: [join $label2]"
    regsub -all "=" $label ":" labelT
  #  puts $labelT
    
    exec sddsplot "-topline=$labelT" -gra=line,vary  \
      -col=xTune,xWaveformPower "-leg=spec=x-data" $file -col=xTune,xWaveformPower $tuneRef "-leg=spec=x-ref" \
      -col=yTune,yWaveformPower "-leg=spec=y-data" $file -col=yTune,yWaveformPower $tuneRef "-leg=spec=y-ref" &
    
}

proc MeasureXYTune {args} {
    global outputDir archiveDir
    cd $outputDir
    set rootname [clock format [clock seconds] -format %Y-%j-%m%d.%H%M%S]
    foreach plane {x y} {
        if [catch {GetWaveformData -rootname $rootname -plane $plane -setup 1} result] {
            SetStatus "Error measure $plane tune: $result"
            return
        }
    }
    if [catch {exec sddsxref $rootname.xtune $rootname.ytune -take=* -transfer=par,yTune -pipe=out \
                 | sddsprocess -pipe=in $rootname.xytune "-reprint=par,filename,[file tail $rootname]" \
                 "-reprint=par,TuneLabel,\\\$gn\\\$r\\\$bx\\\$n = %.4f  \\\$gn\\\$r\\\$by\\\$n = %.4f,xTune,yTune" } result] {
        SetStatus "Error combining x and y tune: $result"
        return
    }
    SetStatus "done. Tune saved in $rootname.xytune"
}

set archiveDir /home/helios/oagData/par/vsaTuneArchive/data
proc SelectTuneRef {args} {
    global archiveDir tuneRef

    set files [lsort -decreasing [glob -nocomplain $archiveDir/*.xytune]]
    if ![llength $files] {
        SetStatus "No tune files found for xytune in archive directory"
        return
    }
    global selectedRefFile
    set selectedRefFile ""
    APSScrolledListWindow .select -name "Select a file" -descriptionName Description -directory $archiveDir -selectMode single \
	-label "Select a File" \
	-itemList $files  -selectionVar selectedRefFile
    tkwait variable selectedRefFile
    if ![string length $selectedRefFile] {
        SetStatus "no file chosen"
        return
    }
    set tuneRef $selectedRefFile
}

proc PlotArchive {args} {
    global tuneRef archiveDir
    #if ![string length $tuneRef] {
    #    SetStatus "tune reference is not chosen!"
    #    return
    #}
    set file [SelectFile -dir $archiveDir]
    if [regexp .xytuen $file] {
        exec sddsplot -grap=line,vary  "-topline=@TuneLabel" "-title=@filename" -samescale=x   \
          -col=xTune,xWaveformPower -leg=spec=xTune $tuneRef -col=yTune,yWaveformPower -leg=spec=yTune  $file &
    } else {
        
    }
}

proc SelectFile {args} {
    set xytune 1
    set dir ""
    APSParseArguments {xytune dir}
    global outputDir  selectedFile
    #cd $outputDir
    if ![llength $dir] {
        set dir $outputDir
    }
    if $xytune {
        set name *.xytune
    } else {
        set name *.*tune
    }
   
    set files [lsort -decreasing [glob -nocomplain $dir/$name]]
    if ![llength $files] {
       return -code error "No files found"
    }
    set selectedFile ""
    APSScrolledListWindow .select -name "Select a file" -descriptionName Description -selectMode single \
      -label "Select a File" \
      -itemList $files  -selectionVar selectedFile
    tkwait variable selectedFile
    if ![string length $selectedFile] {
        return -code error "No file chosen"
    }
    return $selectedFile
}

proc PlotTune {args} {
    set archive 0
    APSParseArguments {archive}
    
    global outputDir selectedFile archiveDir
  #  cd $outputDir
    if $archive {
        set dir $archiveDir
    } else {
        set dir $outputDir
    }
    if [catch {SelectFile -xytune 0 -dir $dir} file] {
        SetStatus "$file"
        return
    }
    if [regexp xytune $file] {
        exec sddsplot -grap=line,vary "-title=@filename" "-topline=@TuneLabel" -samescale=x  -title=@Description  \
          -col=xTune,xWaveformPower -leg=spec=xTune $file -col=yTune,yWaveformPower -leg=spec=yTune  $file &
    } else {
        if [regexp xtune $file] {
            set pl x
        }  elseif [regexp ytune $file] {
            set pl y
        } elseif [regexp stune $file] {
            set pl s
        }
        if {$pl=="s"} {
            exec sddsplot -grap=line,vary  -samescale=x  -topline=@TuneLabel    \
              -col=${pl}Freq,${pl}WaveformPower -leg=spec=${pl}Tune $file &
        } else {
            exec sddsplot -grap=line,vary  -samescale=x    -topline=@TuneLabel -title=@Description  \
              -col=${pl}Tune,${pl}WaveformPower -leg=spec=${pl}Tune $file &
        }
    }
}

proc ChangeTCycle {args} {
    global tcycle
    if [catch {exec cavget -list=P:DG1:cDelayAO -pend=10} before] {
        return -code error "Error reading tcycle(P:DG1:cDelayAO): $before"
    }
    SetStatus "Change tcycle from $before to $tcycle..."
    if [catch {exec cavput -list=P:DG1:cDelayAO=$tcycle -pend=10} result] {
        return -code error "Error in changing tcycle: $result"
    }
    SetStatus "done."
}

proc LoadScopeSetting {args} {
    global tuneConfigPlane
    set tuneConfigPlane ""
    APSDialogBox .tuneconfig -name "chose a config" -cancelCommand "SetStatus \"recall config is cancelled.\"" \
	-okCommand "LoadTuneConfig"
    set tuneConfig ""
    APSRadioButtonFrame .plane -parent .tuneconfig.userFrame -buttonList {"x tune" "y tune" "s tune"} \
	-valueList {x y s} -variable tuneConfigPlane -orientation horizontal -label "Tune Config:"
}
proc LoadTuneConfig {args} {
    global tuneConfigPlane
    if ![string length $tuneConfigPlane] {
	SetStatus  "no config chosen!"
	return
    }
    SetStatus "load tune config for $tuneConfigPlane..."
    exec hpSocketSend hpvecpar "INST:NSEL 1"
    exec hpSocketSend hpvecpar "MMEM:MSIS 'INT:'"
    switch $tuneConfigPlane {
	x {
	    puts "hpSocketSend hpvecpar \"MMEM:LOAD:STAT 1,'INT:PARTUNEX'\""
	    exec hpSocketSend hpvecpar "MMEM:LOAD:STAT 1,'INT:PARTUNEX'"
	}
	y {
	    puts "hpSocketSend hpvecpar \"MMEM:LOAD:STAT 1,'INT:PARTUNEY'\""
	    exec hpSocketSend hpvecpar "MMEM:LOAD:STAT 1,'INT:PARTUNEY'"
	}
	s {
	    exec hpSocketSend hpvecpar "MMEM:LOAD:STAT 1,'INT:PARTUNES'"
	}
    }
    APSWaitWithUpdate -waitSeconds 10
    ReadSetSettings
    SetStatus "done."
}

proc LaunchVSADisplay {args} {
    
    catch {DisconnectVSADisplay}
    catch {exec killall Xephyr}
    
    exec Xephyr -br -ac -noreset -listen tcp -softCursor -screen 1030x455 :0 & 
    after 2000
    exec hpVecDisplay -unit par -display :0 &
    
}
proc CloseVSADisplay {args} {
    SetStatus "Close VSA display..."
    if [catch {exec /home/helios/BOOSTER/bin/hpStopDisplay -unit par -display :0 } result] {
	#SetStatus "Error disconnet par VSA display: $result"
	return
    }
    SetStatus "wait 5 seconds..."
    APSWaitWithUpdate -waitSeconds 5
    SetStatus "Kill Xephyr window..."
    catch {exec killall Xephyr}
    SetStatus "done"
}


wm geometry . -0+0

APSApplication . -name PARTuneMeasurementVSA -version $CVSRevisionAuthor \
  -overview {measurement par tune with booster VSA instrument.}

set status Working...
APSScrolledStatus .status -parent .userFrame -textVariable status \
        -width 60 -height 6 -packOption "-fill both -expand true"
update

ReadSetSettings -set 0


#set freqPoints 1601

foreach var $varList {
    set $var [set ${var}Readback]
    if {[set $var]=="+1"} {
        set $var ON
    } elseif {[set $var]=="+0"} {
        set $var OFF
    }
   # puts "$var [set $var]"
    set ${var}Last [set $var]
}
if ![regexp "DBM" $sourceLevel] {
    set sourceLevel ${sourceLevel}DBM
}
set first 1
#set average ON
SetDefaultPars

set Plane $plane
if !$GUI {
    if $setupScope {
	set tuneConfigPlane $plane
	if [catch {LoadTuneConfig} result] {
	    return -code error "Error setting up scope: $result"
	}
    }
    set range.$plane $range
    if [catch {GetWaveformData -rootname $rootname -plane $plane -plot $plot} tune] {
	return -code error "Error measuring $Plane tune: $tune"
    }
    puts $tune
    exit 0
}

SetPars -plane $plane -set 0
update

#LoadScopeSetting
set tuneConfigPlane $plane
LoadTuneConfig

set width 25
APSLabel .lable -parent .userFrame -text "                            X plane Setpoint       Y plane setpoint           S plane setpoint           Readback"

APSLabeledOutput .center -parent .userFrame -width $width -label "Center frequency (Hz):" -textVariable centerFreqReadback
APSLabeledEntryFrame .center1 -parent .userFrame.center  -width $width -label "" -fg blue \
    -variableList {centerFreq.x centerFreq.y centerFreq.s} -orientation horizontal -packOption "-side right"

bind .userFrame.center.center1.frame.entry1 <Return> "SetSingleSetting -var centerFreq -plane x"
bind .userFrame.center.center1.frame.entry2 <Return> "SetSingleSetting -var centerFreq -plane y"
bind .userFrame.center.center1.frame.entry3 <Return> "SetSingleSetting -var centerFreq -plane s"

APSLabeledOutput .span -parent .userFrame -width $width -label "Span (Hz):" -textVariable spanReadback
APSLabeledEntryFrame .span1 -parent .userFrame.span -width $width -label "" \
    -variableList {span.x span.y span.s} -orientation horizontal
bind .userFrame.span.span1.frame.entry1 <Return> "SetSingleSetting -plane x -var span"
bind .userFrame.span.span1.frame.entry2 <Return> "SetSingleSetting -plane y -var span"
bind .userFrame.span.span1.frame.entry3 <Return> "SetSingleSetting -plane s -var span"

APSLabeledOutput .ave -parent .userFrame -width $width -label "Average number:" -textVariable averageNumReadback
APSLabeledEntryFrame .ave1 -parent .userFrame.ave -width $width -label "" -orientation horizontal \
    -variableList {averageNum.x averageNum.y averageNum.s}
bind .userFrame.ave.ave1.frame.entry1 <Return> "SetSingleSetting -plane x -var averageNum"
bind .userFrame.ave.ave1.frame.entry2 <Return> "SetSingleSetting -plane y -var averageNum"
bind .userFrame.ave.ave1.frame.entry3 <Return> "SetSingleSetting -plane s -var averageNum"

APSLabeledOutput .sourcelevel -parent .userFrame -width $width -label "Source level (dB):" -textVariable sourceLevelReadback
APSLabeledEntryFrame .sourcelevel1 -parent .userFrame.sourcelevel -width $width -label "" -orientation horizontal \
    -variableList {sourceLevel.x sourceLevel.y sourceLevel.s}
bind .userFrame.sourcelevel.sourcelevel1.frame.entry1 <Return> "SetSingleSetting -plane x -var sourceLevel"
bind .userFrame.sourcelevel.sourcelevel1.frame.entry2 <Return> "SetSingleSetting -plane y -var sourceLevel"
bind .userFrame.sourcelevel.sourcelevel1.frame.entry3 <Return> "SetSingleSetting -plane s -var sourceLevel"

APSLabeledOutput .range -parent .userFrame -width $width -label "Range (DBM):" -textVariable rangeReadback
APSLabeledEntryFrame .range1 -parent .userFrame.range -width $width -label "" -orientation horizontal \
    -variableList {range.x range.y range.s}
bind .userFrame.range.range1.frame.entry1 <Return> "SetSingleSetting -var range -plane x"
bind .userFrame.range.range1.frame.entry2 <Return> "SetSingleSetting -var range -plane y"
bind .userFrame.range.range1.frame.entry3 <Return> "SetSingleSetting -var range -plane s"


APSRadioButtonFrame .average -parent .userFrame -label "Average on/off:       " -buttonList {ON OFF} -valueList {+1 +0} \
  -variable averageReadback -orientation horizontal  

APSRadioButtonFrame .repeat -parent .userFrame -label "Repeat on/off:        " -buttonList {ON OFF} -valueList {REP NORM} \
  -variable repeatOnReadback -orientation  horizontal
APSRadioButtonFrame .output -parent .userFrame -label "Source on/off:        " -buttonList {ON OFF} -valueList {+1 +0} \
  -variable outputOnReadback -orientation horizontal

APSDisableWidget .userFrame.average.frame.button1
APSDisableWidget .userFrame.average.frame.button2
APSDisableWidget .userFrame.repeat.frame.button1
APSDisableWidget .userFrame.repeat.frame.button2
APSDisableWidget .userFrame.output.frame.button1
APSDisableWidget .userFrame.output.frame.button2

#.userFrame.output.frame.button1 configure -bg green
#.userFrame.output.frame.button2 configure -bg red
#.userFrame.repeat.frame.button1 configure -bg green
#.userFrame.repeat.frame.button2 configure -bg red
#.userFrame.average.frame.button1 configure -bg green
#.userFrame.average.frame.button2 configure -bg red


APSRadioButtonFrame .aveRB -parent .userFrame.average -packOption "-side left" -label "" -orientation horizontal \
  -buttonList {ON OFF} -valueList {ON OFF} -variable average -commandList \
  {"ChangeRadioButton -var average" "ChangeRadioButton -var average"} 

APSRadioButtonFrame .repeatRB -parent .userFrame.repeat -packOption "-side left" -label "" -orientation horizontal \
  -buttonList {ON OFF} -valueList {REP NORM} -variable repeatOn -commandList \
  {"ChangeRadioButton -var repeatOn" "ChangeRadioButton -var repeatOn"} 

APSRadioButtonFrame .outputRB -parent .userFrame.output -packOption "-side left" -label "" -orientation horizontal \
  -buttonList {ON OFF} -valueList {ON OFF} -variable outputOn \
  -commandList {"ChangeRadioButton -var outputOn" "ChangeRadioButton -var outputOn"} 
set tcycle 400000
set waitTimeAfterSetup 5
APSLabeledEntry .tcycle -parent .userFrame -width $width -textVariable tcycle -label "Time in cycle (us):"
bind .userFrame.tcycle.entry <Return> "ChangeTCycle"
APSLabeledEntry .time -parent .userFrame -width $width -textVariable waitTimeAfterSetup -label "Wait time after changing PAR VSA parameters:" 

#set Plane ""
APSRadioButtonFrame .plane -parent .userFrame -label "Plane:" -buttonList {x y s} -variable Plane -valueList {x y s} \
  -orientation horizontal -commandList {"SetPars -plane x" "SetPars -plane y" "SetPars -plane s"}
APSLabel .desc -parent .userFrame.plane -text " (Recall config before switching between x/y and s)"

APSRadioButtonFrame .rf -parent .userFrame -label "RF source on/off for x/y measurement:" \
    -orientation horizontal -buttonList {ON OFF} -valueList {ON OFF} -variable RFOnOff


APSLabeledEntry .dir -parent .userFrame -label "Output directory:" -textVariable outputDir -width 80 
APSLabeledEntry .des -parent .userFrame -label "Description:" -textVariable description -width 80

APSButton .archive -parent .userFrame.dir -text "archive" -size small -command "set outputDir /home/helios/oagData/par/vsaTuneArchive/data"
APSButton .daily -parent .userFrame.dir -text "daily" -size small -command "set outputDir [APSGoToDailyDirectory -subdirectory parTuneVSA]"
set tuneRef ""
APSLabeledEntry .xref -parent .userFrame -label "x/y tune archive:" -textVariable tuneRef -width 80
APSButton .xsel -parent .userFrame.xref -text "F" -size small -command "SelectTuneRef"

APSFrame .f1 -parent .userFrame
APSFrame .f2 -parent .userFrame
APSFrame .f3 -parent .userFrame
set w1 .userFrame.f1.frame
set w2 .userFrame.f2.frame
set w3 .userFrame.f3.frame

#APSButton .take -parent $w1 -text "Take Waveform" -command "GetWaveformData"
APSButton .meas -parent $w1 -text "Measure X/Y Tune" -command "MeasureXYTune"
APSButton .meas1 -parent $w1 -text "Measure sTune" -command "GetWaveformData -plane s"
APSButton .trace -parent $w1 -text "MeasureTune without Setup" -command "GetWaveformData -setup 0"
APSButton .read -parent $w1 -text "Read Settings" -command "ReadSetSettings -set 0"
APSButton .set -parent $w1 -text "Set Settings" -command "ReadSetSettings -set 1"
APSButton .recall -parent $w1 -text "Recall Config" -command LoadScopeSetting
APSButton .start1 -parent $w2 -text "Launch VSA Display" -command LaunchVSADisplay
APSButton .close -parent $w2 -text "Close VSA Display" -command CloseVSADisplay
APSButton .copy -parent $w3 -text "Copy to Archive" -command "CopyToArchive"
APSButton .compare -parent $w3 -text "Compare x/y tune with Archive" -command "CompareWithArchive"
APSButton .plot1 -parent $w3 -text "Plot Archive" -command "PlotTune -archive 1"
APSButton .plot -parent $w3  -text "Plot Tune" -command "PlotTune"



