#!/bin/sh  
# \
exec oagwish "$0" "$@"
#
# $Log: not supported by cvs2svn $
# Revision 1.5  2010/04/30 18:31:38  shang
# set the default coefficients to be zero if they can not be obtained from pvs.
#
# Revision 1.4  2010/01/25 20:44:06  shang
# added "Postprocess and Review" button per Bui's request to post-process data and display the results.
#
# Revision 1.3  2009/11/04 22:02:51  shang
# changed to use Pj for A  bpms and added ploting Pj bpm option for A bpm
#
# Revision 1.2  2009/08/21 21:37:41  shang
# added entry for transition dead time.
#
# Revision 1.1  2009/08/21 19:35:32  shang
# developed much earlier, just add it to CVS
#

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 statusText ""
proc SetStatus { text } {
    global statusText
    set statusText "$text ([clock format [clock seconds] -format "%H:%M:%S"])"
    update
}

proc ScanData {args} {
    global outputDir rootname scanType mainDir plane switchMode planeMode samplesPerBunch delay subSector bpm
    global readType pauseAfterChange posIndexLimit powerIndexLimit updateFilters libera comment serial transitionDeadTime
    global Cx12 Cx30 Cy12 Cy30 bpmType
    switch $scanType {
        PowerScan {
            set expFile ${plane}Scan.exp
            SetStatus "Start continuouse power scan..."
        }
        PositionScan  {
            set expFile pos_${plane}Scan.exp
            SetStatus "Start discreate power scan ..."
        }
    }
    set tmpRoot /tmp/[APSTmpString]
    if [catch {exec replaceText $mainDir/inputFiles/$expFile $tmpRoot.exp \
                 -orig=<subSector>,<readType>,<posIndexLimit>,<powerIndexLimit>,<pauseAfterChange>,<monFile>  \
                 -repl=$subSector,$readType,$posIndexLimit,$powerIndexLimit,$pauseAfterChange,$tmpRoot.mon } result] {
        return -code error $result
    }
    if [regexp {A} $subSector] {
        set BPM Pj
    } elseif [regexp {B} $subSector] {
        set BPM P5
    } else {
        set BPM P5
    }
    switch $bpmType {
        libera -
        monopulse {
            switch $bpmType {
                libera {
                    set monFile $mainDir/inputFiles/libera.mon.template
                }
                default {
                    set monFile $mainDir/inputFiles/bpm.mon.template
                }
            }
            if [catch {exec replaceText $monFile $tmpRoot.mon \
                         -orig=<subSector>,<BPM>,<readType>,<subSector-lower> -repl=$subSector,$BPM,$readType,[string tolower $subSector] } result] {
                return -code error $result
            }
        }
        bergoz {
            if [catch {exec sddsprocess /home/helios/oagData/SCR/requestFiles/SBPMWaveform.config  \
                         -match=par,IOCName=$subSector $tmpRoot.root
                exec sddsprocess $tmpRoot.root $tmpRoot.x1 -edit=col,ControlName,BPM,ei/:${readType}:x/ 
                exec sddsprocess $tmpRoot.root $tmpRoot.y1 -edit=col,ControlName,BPM,ei/:${readType}:y/ 
                exec sddsprocess $tmpRoot.root $tmpRoot.x2 -edit=col,ControlName,BPM,ei/:${readType}Pn:x/ 
                exec sddsprocess $tmpRoot.root $tmpRoot.y2 -edit=col,ControlName,BPM,ei/:${readType}Pn:y/ 
                exec sddsprocess $tmpRoot.root $tmpRoot.x3 -edit=col,ControlName,BPM,ei/:${readType}Pw:x/ 
                exec sddsprocess $tmpRoot.root $tmpRoot.y3 -edit=col,ControlName,BPM,ei/:${readType}Pw:y/ 
                exec sddscombine $tmpRoot.x1 $tmpRoot.y1 $tmpRoot.x2 $tmpRoot.y2 $tmpRoot.x3 $tmpRoot.y3 -merge $tmpRoot.mon}  result] {
                return -code error $result
            } 
            file delete -force $tmpRoot.root $tmpRoot.x1 $tmpRoot.y1 $tmpRoot.x2 $tmpRoot.y2 $tmpRoot.x3 $tmpRoot.y3
        }
            
    }
    if [regexp {A} $subSector] {
        set BPM Pj
    } elseif [regexp {B} $subSector] {
        set BPM P5
    } else {
        set BPM P5
    }
    
    if {$bpmType!="libera" && $updateFilters} {
        exec replaceText $mainDir/inputFiles/updateFilters.exp $tmpRoot.1 -orig=<subSector> -replace=$subSector
        exec cat $tmpRoot.1 $tmpRoot.exp > $tmpRoot.2
        exec mv $tmpRoot.2 $tmpRoot
    }
    
    set fileroot  $outputDir/${rootname}-[clock format [clock seconds] -format %Y-%j-%m%d-%H%M%S]
    SetStatus "set tc:atten ..."
    if [catch {exec cavput -list=tc:atten: -list=TO=6,TI=6,BI=6,BO=6 -pend=10} result] {
        return -code error $result
    }
    if {$bpmType!="libera"} {
        SetStatus "Set up MpBPM waveform ..."
        if [catch {exec sddsgencontrolbits /dev/null \
                     -planeMode=$planeMode \
                     -commutationMode=$switchMode \
                     -sampleMode=single \
                     -samplesPerBunch=$samplesPerBunch \
                     -turnMarkerOffset=$delay \
                     -transitionDeadTime=$transitionDeadTime \
                     -setRAMWaveformPV=${subSector}:AcqControlSetWF \
                     -controlRAMFile=$fileroot.RAM } result] {
            return -code error $result
        }
    }
    Coefficients -action read
    APSExecLog .scan -name "Power Scan" -width 90 \
        -unixCommand "sddsexperiment $tmpRoot.exp $fileroot.scan -verbose" \
        -callback "PostProcess -fileroot $fileroot -libera $libera -planeMode $planeMode -switchMode $switchMode -samplesPerBunch $samplesPerBunch -subSector $subSector -delay $delay -scanType $scanType -serial $serial -Cx12 $Cx12 -Cx30 $Cx30 -Cy12 $Cy12 -Cy30 $Cy30 -comment \"$comment\"" \
        -cancelCallback "PostProcess -fileroot $fileroot -libera $libera  -planeMode $planeMode -switchMode $switchMode -samplesPerBunch $samplesPerBunch -subSector $subSector -delay $delay -scanType $scanType -serial $serial  -Cx12 $Cx12 -Cx30 $Cx30 -Cy12 $Cy12 -Cy30 $Cy30 -comment \"$comment\"" \
        -abortCallback  "PostProcess -fileroot $fileroot -libera $libera  -planeMode $planeMode -switchMode $switchMode -samplesPerBunch $samplesPerBunch  -subSector $subSector -delayt $delay -scanType $scanType -serial $serial  -Cx12 $Cx12 -Cx30 $Cx30 -Cy12 $Cy12 -Cy30 $Cy30 -comment \"$comment\"" 
}

proc PostProcess {args} {
    set comment ""
    set fileroot ""
    set planeMode ""
    set samplesPerBunch ""
    set switchMode ""
    set subSector ""
    set delay ""
    set scanType ""
    set serial ""
    set Cx12 ""
    set Cx30 ""
    set Cy12 ""
    set Cy30 ""
    set libera 0
    APSParseArguments {libera comment fileroot planeMode samplesPerBunch planeMode switchMode subSector delay scanType serial Cx12 Cx30 Cy12 Cy30}

    if ![string length $fileroot] {
        return
    }
    if ![file exist $fileroot.scan] {
        return 
    }
    if $libera {
        set Cx12 0
        set Cx30 0
        set Cy12 0
        set Cy30 0
    }
    if ![string compare $scanType "PowerScan"] {
        
        if [catch {exec sddsbreak -increaseOf=TO ${fileroot}.scan -pipe=out \
                     | sddsprocess -pipe=in ${fileroot}.sdds \
                     "-print=par,MonoPulse,Mono Pulse serial# $serial" \
                     "-print=par,Description,[APSMakeSafeQualifierString $comment]" \
                     "-print=par,ScanType,$scanType" "-print=par,subSector,$subSector" \
                     -process=TO,average,TOavg -process=BO,average,BOavg \
                     -process=TI,average,TIavg -process=BI,average,BIavg \
                     -print=par,planeMode,$planeMode -print=par,commutationMode,$switchMode \
                     -print=par,sampleMode,single -define=par,samplesPerBunch,$samplesPerBunch \
                     -redefine=par,turnMarkerOffset,$delay -define=par,transitionDeadTime,100  \
                     -redefine=par,Cx12,$Cx12 \
                     -redefine=par,Cx30,$Cx30 \
                     -redefine=par,Cy12,$Cy12 \
                     -redefine=par,Cy30,$Cy30 } result] {
            return -code error $result
        }
    } else {
        if [catch {exec sddsbreak -changeOf=power ${fileroot}.scan -pipe=out \
                     | sddsprocess -pipe=in ${fileroot}.sdds \
                     "-print=par,MonoPulse,Mono Pulse serial# $serial" \
                     -process=TO,average,TOavg -process=BO,average,BOavg \
                     -process=TI,average,TIavg -process=BI,average,BIavg \
                     "-print=par,ScanType,$scanType" \
                     -process=power,average,power \
                     "-reprint=par,Description,[APSMakeSafeQualifierString $comment]" \
                     "-reprint=par,subSector,$subSector" \
                     -reprint=par,planeMode,$planeMode -print=par,commutationMode,$switchMode \
                     -reprint=par,sampleMode,single -define=par,samplesPerBunch,$samplesPerBunch \
                     -redefine=par,turnMarkerOffset,$delay -define=par,transitionDeadTime,100 \
                     -redefine=par,Cx12,$Cx12 \
                     -redefine=par,Cx30,$Cx30 \
                     -redefine=par,Cy12,$Cy12 \
                     -redefine=par,Cy30,$Cy30 } result] {
            return -code error $result
        }
    }
    catch {exec setfacl -m user::rwx $fileroot.sdds}
    PlotData -filename ${fileroot}.sdds
    SetStatus "post process done."
}

proc PlotData {args} {
    set filename ""
    APSParseArguments {filename}
    global  outputDir rootname bpm libera plane subSector
    if ![string length $filename] {
        set filename [APSFileSelectDialog [APSUniqueName .] -path $outputDir \
                          -pattern ${rootname}*.sdds -width 80 -title "Select Data"]
        if ![string length $filename] {
            return
        }
    }
    set npages [exec sdds2stream -npages=bare $filename]
    set subSector [lindex [exec sdds2stream -par=subSector $filename] 0] 
    set scanType [lindex [exec sdds2stream -par=ScanType $filename] 0]
    set parNames [exec sddsquery -par $filename]
    if [lsearch $parNames "MonoPulse"]>=0 {
        set extraOpt "-topline=@MonoPulse"
    } else {
        set extraOpt ""
    }
   
    set col1s [exec sddsquery -col $filename] 
    if {$subSector=="S43H"} {
        set bpms [join [exec sddsprocess /home/helios/oagData/SCR/requestFiles/SBPMWaveform.config  \
                         -match=par,IOCName=$subSector -pipe=out \
                          | sdds2stream -pipe -col=BPM]]
        eval global $bpms
        foreach bpm $bpms {
            set $bpm 0
        }
        APSDialogBox .diag  -name "select bpm to plot" -okCommand ""
        APSCheckButtonFrame .choise -parent .diag.userFrame -label "Select bpm to plot:"\
          -buttonList $bpms -variableList $bpms 
        tkwait window .diag
        set bpms1 ""
        foreach bpm $bpms {
            if [set $bpm] {
                lappend bpms1 $bpm
            }
        }
        if ![llength $bpms1] {
            return -code error "no bpm selected to plot."
        }
        set cols ""
        foreach bpm $bpms1 {
            foreach col $col1s {
                if [regexp $bpm $col] {
                    if {$plane!='q'} {
                        if [regexp $plane $col] {
                            lappend cols $col
                        }
                    } else {
                        lappend cols $col
                    }
                }
            }
        }
        if ![llength $cols] {
            return -code error "No plots found for $plane plane bpm $bpm."
        }
        if {$scanType=="PowerScan"} {
            set xcol power
            set option " -legend=parameter=TOavg -title=[file root [file tail $filename]]"
        } else {
            set xcol TO
            set option " -legend=parameter=power -title=[file root [file tail $filename]]"
        }
        foreach col $cols {
            append option " -col=$xcol,$col $filename"
            if {[regexp {Pn} $col] || [regexp {Pw} $col]} {
                append option " -mode=y=log -mode=y=spec -range=ymin=1"
            }
        }
        eval exec sddsplot -split=page -graphic=line,vary -sep=$npages \
          $extraOpt $option &
        return
    }
    if  ![string compare $scanType "PowerScan"] {
        eval exec sddsplot -split=page -graphic=line,vary -sep=$npages -layout=2,2 \
              $extraOpt \
              -legend=parameter=TOavg -title=[file root [file tail $filename]] \
              -col=power,S*:P${bpm}:ms*Ave:x $filename \
              -col=power,S*:P${bpm}:ms*Ave:sx $filename \
              -col=power,S*:P${bpm}:ms*Ave:y $filename \
              -col=power,S*:P${bpm}:ms*Ave:sy $filename \
              -col=power,S*:P${bpm}:ms*AvePn:x $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePn:sx $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePn:y $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePn:sy $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePw:x $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePw:sx $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePw:y $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePw:sy $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 &
    } else {
       eval exec sddsplot -graphic=line,vary -split=page -sep=$npages -layout=2,2 \
              $extraOpt \
              -legend=parameter=power -title=[file root [file tail $filename]]  \
              -col=TO,S*:P${bpm}:ms*Ave:x $filename \
              -col=TO,S*:P${bpm}:ms*Ave:sx $filename \
              -col=TO,S*:P${bpm}:ms*Ave:y $filename \
              -col=TO,S*:P${bpm}:ms*Ave:sy $filename \
              -col=TO,S*:P${bpm}:ms*AvePn:x $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePn:sx $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePn:y $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePn:sy $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePw:x $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePw:sx $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePw:y $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePw:sy $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 & 
        
    }
    return
    if  ![string compare $scanType "PowerScan"] {
        if {$plane=="q"} {
            eval exec sddsplot -split=page -graphic=line,vary -sep=$npages -layout=2,2 \
              $extraOpt \
              -legend=parameter=TOavg -title=[file root [file tail $filename]] \
              -col=power,S*:P${bpm}:ms*Ave:x $filename \
              -col=power,S*:P${bpm}:ms*Ave:sx $filename \
              -col=power,S*:P${bpm}:ms*Ave:y $filename \
              -col=power,S*:P${bpm}:ms*Ave:sy $filename \
              -col=power,S*:P${bpm}:ms*AvePn:x $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePn:sx $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePn:y $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePn:sy $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePw:x $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePw:sx $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePw:y $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePw:sy $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 &
        } else {
            eval exec sddsplot -split=page -graphic=line,vary -sep=$npages -layout=2,3 \
              $extraOpt \
              -legend=parameter=TOavg -title=[file root [file tail $filename]] \
              -col=power,S*:P${bpm}:ms*Ave:$plane $filename \
              -col=power,S*:P${bpm}:ms*Ave:s$plane $filename \
              -col=power,S*:P${bpm}:ms*AvePn:$plane $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePn:s$plane $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePw:$plane $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=power,S*:P${bpm}:ms*AvePw:s$plane $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 &
        }
    } else {
        if {$plane=="q"} {
            eval exec sddsplot -graphic=line,vary -split=page -sep=$npages -layout=2,2 \
              $extraOpt \
              -legend=parameter=power -title=[file root [file tail $filename]]  \
              -col=TO,S*:P${bpm}:ms*Ave:x $filename \
              -col=TO,S*:P${bpm}:ms*Ave:sx $filename \
              -col=TO,S*:P${bpm}:ms*Ave:y $filename \
              -col=TO,S*:P${bpm}:ms*Ave:sy $filename \
              -col=TO,S*:P${bpm}:ms*AvePn:x $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePn:sx $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePn:y $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePn:sy $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePw:x $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePw:sx $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePw:y $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePw:sy $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 &
        } else {
             eval exec sddsplot -graphic=line,vary -split=page -sep=$npages -layout=3,2 \
              $extraOpt \
              -legend=parameter=power -title=[file root [file tail $filename]]  \
              -col=TO,S*:P${bpm}:ms*Ave:$plane $filename \
              -col=TO,S*:P${bpm}:ms*Ave:s$plane $filename \
              -col=TO,S*:P${bpm}:ms*AvePn:$plane $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePn:s$plane $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePw:$plane $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 \
              -col=TO,S*:P${bpm}:ms*AvePw:s$plane $filename \
              -mode=y=log -mode=y=spec -range=ymin=1 &
        }
    }
}

proc UpdateFilters {args} {
    global subSector
    SetStatus "Updating filters for $subSector..."
    foreach thing {1 2} { 
        if [catch {exec cavput -list=${subSector}:rms:Force.PROC=1
            exec cavput -list=${subSector}:position:Force.PROC=1 } result] {
            return -code error $result
        }
        after 2000
    }
    SetStatus "done"
}

set archiveDir /home/helios/oagData/sr/BPMcontrolRAM/archive
proc MakeArchiveFileList {args} {
    global status archiveDir
    
    set returnList 0
    APSParseArguments {returnList}
    
    SetStatus "Searching for archives..."; update
    if ![file exist $archiveDir/archiveList.sdds] {
        set oldDir [pwd]
        cd $archiveDir
        set fileList [glob -nocomplain RAMControlRAM*]
        if [catch {eval exec sddscombine $fileList -pipe=out \
                     | sddscollapse -pipe \
                     | sddssort -pipe=in -col=Time,decreasing archiveList.sdds } result] {
            return -code error "MakeArchiveFileList: $result"
        }
        cd $oldDir
    }
    set fileList [exec sdds2stream -col=Filename $archiveDir/archiveList.sdds]
    set commList [exec sdds2stream -col=Comment $archiveDir/archiveList.sdds]
    set itemList ""
    foreach file $fileList Comment $commList {
        lappend itemList [list $file $Comment]
    }
    return $itemList
}

proc ConfigureFPGA {args} {
    set item [APSChooseItemFromList -itemList [MakeArchiveFileList] \
                  -name "Select Archive to Load" -returnIndices 0]
    if ![string length $item] {
        return
    }
    set filename [lindex [lindex $item 0] 0]
    SetStatus "loading RAM from $filename to Mp bpm waveform..."
    if [catch {exec sddswput $archiveDir/$filename \
               } result] {
        return -code error "RestoreFromRAMarchive: $result"
    }
    # do a caput to *:AcqControlGetWF.PROC 1
    if [catch {exec cavput -list=${PVprefix}:AcqControlGetWF.PROC=1 -pend=30} result] {
        return -code error "RestoreFromRAMarchive: $result"
    }
    after 2000
    if [catch {exec cavput -list=${PVprefix}:scope:gtr:arm=1 -pend=30} result] {
        return -code error "RestoreFromRAMarchive: $result"
    }
    SetStatus "done"
}

set Cx12 0
set Cx30 0
set Cy12 0
set Cy30 0
proc Coefficients {args} {
    set name ""
    set action ""
    APSParseArguments {name action}
    if ![string length $name] {
        set name {Cx12 Cx30 Cy12 Cy30}
    }
    
    global bpm subSector Cx12 Cx30 Cy12 Cy30
    switch $action {
        read {
            if [catch {exec cavget -list=${subSector}:P$bpm: -list=Cx12,Cx30,Cy12,Cy30} valList] {
                return -code error "Unable to read coefficients: $valList"
            }
           
            foreach nm {Cx12 Cx30 Cy12 Cy30} index {0 1 2 3} {
                set value [lindex $valList $index]
                if {$value=="?"} {
                    set value 0
                }
                set $nm 0
            }
        }
        set {
            foreach nm $name {
                if [catch {exec cavput -list=${subSector}:P$bpm: -list=${nm}=[set $nm] -pend=10} result] {
                    return -code error "Unable to set coefficient - ${subSector}:P$bpm:$nm: $result"
                }
            }
        }
        default {
            set Cx12 -40.4269
            set Cx30 21.93935
            set Cy12 -21.23656
            set Cy30 14.40193
            if [catch {exec cavput -list=${subSector}:P$bpm: -list=Cx12=$Cx12,Cx30=$Cx30,Cy12=$Cy12,Cy30=$Cy30 -blunderAhead \
                         -pend=10} result] {
                return -code error "Unable to set coefficients(2): $result"
            }
        }

    }
}

proc PostprocessReview {args} {
    set filename ""
    APSParseArguments {filename}
    global  outputDir rootname bpm libera plane
    if ![string length $filename] {
        set filename [APSFileSelectDialog [APSUniqueName .] -path $outputDir \
                        -pattern ${rootname}*.sdds -width 80 -title "Select Data"]
        if ![string length $filename] {
            return
        }
    }
    set scanType [lindex [exec sdds2stream -par=ScanType $filename] 0]
    set tmpFile /tmp/[APSTmpString]
    if  ![string compare $scanType "PowerScan"] {
        if ![file exist $filename.proc] {
            if [catch {exec sddsprocess $filename $filename.1 \
                         -filter=col,power,-21,11 \
                         -process=S42*msAve:*,spread,%sSpread -process=S42*msAve:*,average,%sMean
                exec sddsxref $filename $filename.1 $filename.proc -transfer=par,*Spread,*Mean -leave=* } result] {
                return -code error "Error in processing power scan data: $result"
            }
            exec rm $filename.1
        }
        if [catch {exec sddsconvert $filename.proc -pipe=out \
                     -retain=par,*P${bpm}*msAve:${plane}Spread,*P${bpm}*msAve:${plane}Mean \
                     | sddsprintout -pipe=in $tmpFile.power "-title=printout for $plane P$bpm of $filename." \
                     -par=*Spread -par=*Mean  } result] {
            return -code error $result
        }
        APSFileDisplayWindow [APSUniqueName .fileDisp] -fileName $tmpFile.power -width 120 -height 30\
          -comment "Printout for config.sdds" -deleteOnClose 1 -font "courier 12" \
          -printCommand "enscript -r"
    } else {
        if ![file exist $filename.proc] {
            set columns [exec sddsquery -col $filename]
            set fileList ""
            foreach col $columns {
                if [string match "*:msAve:*" $col] {
                    if [catch {exec  sddspfit $filename -xOffset=6 -terms=4 -col=TO,$col -pipe=out \
                                 | sddsconvert -pipe -rename=par,sddspfitLabel=${col}sddspfitLabel \
                                 | sddsprocess -pipe=in $filename.$col -process=*Residual,rms,%sRms} result] {
                        return -code error $result
                    }
                    lappend fileList $filename.$col
                }
            }
            if [catch {eval exec sddsxref $filename $fileList $filename.proc -transfer=par,*Rms,*sddspfitLabel \
                         -take=*Fit,*Residual } result] {
                return -code error $result
            }
            eval file delete -force $fileList
        }
        
        if [catch {exec sddsconvert $filename.proc -pipe=out \
                     -retain=par,*P${bpm}*msAve:${plane}ResidualRms \
                     | sddsprintout -pipe=in "-title=$plane P$bpm residual RMS of $filename." \
                     -par=*ResidualRms $tmpFile.fft} result] {
            return -code error $result
        }
        APSFileDisplayWindow [APSUniqueName .fileDisp] -fileName $tmpFile.fft -width 120 -height 30\
          -comment "Printout for config.sdds" -deleteOnClose 1 -font "courier 12" \
          -printCommand "enscript -r"
        set columns [exec sddsquery -col $filename]
        foreach col $columns {
            if [string match "*P${bpm}:msAve:$plane" $col] {
                lappend plotOpt1  -split=page -sep -title=@${col}sddspfitLabel -col=TO,${col}Residual 
            }
        }
        exec sddsplot $filename.proc -layout=1,3 -legend \
          -topline=@power -split=pages -sep=nameindex,pages -group=pages,nameindex \
          -col=TO,*P${bpm}:msAve:$plane -grap=sym,sca=3,sub=1 -col=TO,*P${bpm}:msAve:${plane}Fit -grap=line & 
          
        
        eval exec  sddsplot -legend  -layout=1,3  $filename.proc $plotOpt1 &
    }
   
    
}
set CVSRevisionAuthor "\$Revision: 1.6 $ \$Author: shang $"
APSApplication . \
  -name FPGAbpmTest \
  -version "$CVSRevisionAuthor" \
  -overview {LCLS experiment.}

APSScrolledStatus .status  \
  -parent .userFrame \
  -textVariable statusText \
  -width 60 \
  -height 8 \
  -withButtons 1 \
  -packOption "-fill both -expand true"

APSFrame .par -parent .userFrame -label "Setup Parameters"
APSFrameGrid .grid -parent .userFrame.par.frame -xList {x1 x2}
set w .userFrame.par.frame
set w1 $w.grid.x1
set w2 $w.grid.x2

set subSector S42A
set bpm 2
set readType msAve
set samplesPerBunch 6
set delay 19
set plane x
set switchMode ab2
set planeMode xy1
set width 15
set mainDir /home/helios/oagData/sr/FPGAbpm
set outputDir [APSGoToDaily Directory -subdirectory FPGAbpmTest]
set rootname PowerScan
set comment ""
set scanType PowerScan
set posIndexLimit 97
set powerIndexLimit 61
set pauseAfterChange 5
set serial 1
set updateFilters 0
set transitionDeadTime 100
APSLabeledEntry .sector -parent $w1 -label "Sub sector:" -width $width -textVariable subSector

APSLabeledEntry .samples -parent $w1 -label "Samples per bunch:" -width $width -textVariable samplesPerBunch
APSLabeledEntry .delay -parent $w1 -label "Delay:" -textVariable delay -width $width
APSLabeledEntry .trans -parent $w1 -label "Transition dead time:" -textVariable transitionDeadTime -width $width
APSLabeledEntry .pindex -parent $w1 -label "Position scan index limit:" -width $width -textVariable posIndexLimit 
APSLabeledEntry .powindex -parent $w1 -label "Power scan index limit:" -width $width -textVariable powerIndexLimit
APSRadioButtonFrame .filter -parent $w1 -label "Update filters between samples?" -buttonList {Yes No} \
    -valueList {1 0} -variable updateFilters -orientation horizontal

APSLabeledEntry .pause -parent $w2 -label "Pause after change (seconds):" -width $width -textVariable pauseAfterChange
APSLabeledEntry .serial -parent $w2 -label "Mono Pulse serial number:" -width $width -textVariable serial
APSRadioButtonFrame .readtype -parent $w2 -label "Reading type:" -variable readType -valueList {msAve mswAve} \
    -buttonList {msAve mswAve} -orientation horizontal
APSRadioButtonFrame .plane -parent $w2 -label "Plane:" -buttonList {x y q} -valueList {x y q} \
    -variable plane -orientation horizontal
APSRadioButtonFrame .type -parent $w2 -label "Scan type:" -buttonList {PowerScan PositionScan} -valueList {PowerScan PositionScan} \
    -variable scanType -commandList {"set rootname PowerScan" "set rootname PositionScan"}  -orientation horizontal 
APSRadioButtonFrame .planeSwitch -parent $w -label "Plane switch:      " -buttonList {"x " "y   " "x/y every turn   " "x/y every two turns  "} \
    -variable planeMode -valueList {x y xy1 xy2} -orientation horizontal


APSRadioButtonFrame .switch -parent $w -label "Commutation switch:" -buttonList {"0 " "180 " "0/180 every turn " "0/180 every two turns"} \
    -variable switchMode -valueList {a b ab1 ab2} -orientation horizontal 

APSRadioButtonFrame .bpm -parent $w2 -label "Bpm for plot:      "  -variable bpm -buttonList {j 1 2 3 4 5} -valueList {j 1 2 3 4 5} \
    -orientation horizontal

APSFrame .f -parent $w -label "Polynomial Coefficients"
set w1 $w.f.frame
APSFrameGrid .grid -parent $w1 -xList {y1 y2 y3 y4}
if [catch {exec cavget -list=${subSector}:P$bpm: -list=Cx12,Cx30,Cy12,Cy30} valList] {
    return -code error "Unable to read coefficients: $valList"
}
foreach nm {Cx12 Cx30 Cy12 Cy30} index {0 1 2 3} {
    set value [lindex $valList $index]
    if {$value=="?"} {
        set value 0
    }
    set $nm $value
}

foreach name {Cx12 Cx30 Cy12 Cy30} index {1 2 3 4} {
    APSLabeledEntry .[string tolower $name] -parent $w1.grid.y$index -label "${name}" -textVariable $name -width 20
    bind $w1.grid.y$index.[string tolower $name].entry <Return> "Coefficients -action set -name $name"
}
APSButton .set -parent $w1 -text "Set" -command "Coefficients -action set"
APSButton .read -parent $w1 -text "Read" -command "Coefficients -action read"
APSButton .default -parent $w1 -text "Default" -command "Coefficients -action default"

set libera 0
set bpmType monopulse
#APSCheckButtonFrame .check -parent $w -label "" -buttonList {libera} -variableList {libera} -orientation horizontal 
APSRadioButtonFrame .type -parent $w -label "BPM type:" -buttonList {monopulse libera bergoz} \
  -valueList {monopulse libera bergoz} -orientation horizontal -variable bpmType
APSLabeledEntry .dir -parent $w -label "Output directory:" -width 70 -textVariable outputDir
APSLabeledEntry .root -parent $w -label "Output rootname:" -width 70 -textVariable rootname
APSLabeledEntry .comment -parent $w -label "Comment:" -width 70 -textVariable comment

APSButton .scan -parent .userFrame -text "Start Scan" -command "ScanData"
APSButton .filter -parent .userFrame -text "Update Filters" -command "UpdateFilters"
APSButton .plot -parent .userFrame -text "Plot Data" -command "PlotData" 
APSButton .config -parent .userFrame -text "Config FPGA" -command "ConfigureFPGA"
APSButton .proc -parent .userFrame -text "Postprocess and Review" -command "PostprocessReview"
