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

# $Log: ScanBucketPurity

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.1 $ \$Author: shang $"

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

proc Scan {args} {
    global mainDir abort 

    set file $mainDir/[clock format [clock seconds] -format %Y-%m%d.%H:%M:%S]
    set fileList ""
    if [catch {exec cavput -list=S36AM:BP:mcaErase=1 -pend=30} result] {
	SetMainStatus $result
	return
    }
    APSDisableButton .userFrame.review.button
    SetMainStatus "Scan bucket..."
    set tmpRoot /tmp/[APSTmpString]
    for {set bucket 0} {$bucket<1296} {incr bucket +54} {
        SetMainStatus "set bucket number to $bucket..."
        if [catch {exec cavput -list=S35IDBnchClkGenClearPatBO.VAL=1 -pend=30} result] {
            SetMainStatus $result
	    APSEnableButton .userFrame.review.button
            return
        }
        if [catch {exec cavput -list=S35IDBnchClkGenSetBucketAO.VAL=$bucket -pend=30} result] {
            SetMainStatus $result
	    APSEnableButton .userFrame.review.button
            return
        }
        after 1000
        SetMainStatus "collecting data..."
        if [catch {exec cavput -list=S36AM:BP:mcaEraseStart=1 -pend=30} result] {
            SetMainStatus $result
	    APSEnableButton .userFrame.review.button
            return
        }
	set timeout [expr [clock seconds] + 30]
	while {[clock seconds]<$timeout} {
	    if $abort {
		break
	    }
	    after 1000
	    update
	}
	if $abort {
	    SetMainStatus "Data collecting was aborted."
	    if [catch {exec cavput -list=S36AM:BP:mcaStop=1 -pend=30} result] {
		SetMainStatus $result
		APSEnableButton .userFrame.review.button
		return
	    }
	    set abort 0
	    break
	}
	if [catch {exec cavput -list=S36AM:BP:mcaStop=1 -pend=30} result] {
	    SetMainStatus $result
	    APSEnableButton .userFrame.review.button
            return
	}
	SetMainStatus "reading data..."
	if [catch {exec cavget -list=S36AM:BP:mca.ELTM -pend=30} time] {
	    SetMainStatus $time
	    APSEnableButton .userFrame.review.button
            return
	}
        if [catch {exec sddswmonitor -pvnames=S36AM:BP:mca.VAL $tmpRoot.$bucket} result] {
            SetMainStatus $result
	    APSEnableButton .userFrame.review.button
            return
        }
	SetMainStatus "reading done."
        if [catch {exec sddsprocess $tmpRoot.$bucket $tmpRoot.$bucket.proc \
                       -define=par,BucketNumber,$bucket,type=long \
		       -define=par,S36AM:BP:mca.ELTM,$time } result] {
            SetMainStatus $result
	    APSEnableButton .userFrame.review.button
            return
        }
	if [catch {PlotFile -file $tmpRoot.$bucket.proc} result] {
	    SetMainStatus $result
	}
        file delete -force $tmpRoot.$bucket
        lappend fileList $tmpRoot.$bucket.proc
    }
    if [llength $fileList] {
	if [catch {eval exec sddscombine $fileList $file -overwrite} result] {
	    SetMainStatus $result
	    APSEnableButton .userFrame.review.button
	    return
	}
	eval file delete -force $fileList
	SetMainStatus "done."
    } else {
	SetMainStatus "Nothing is collected yet."
    }
    APSEnableButton .userFrame.review.button
}

proc Review {args} {
    global mainDir FileSelection
    
    set oldDir [pwd]
    cd $mainDir
    set fileList [glob -nocomplain *]
    set fileList [lsort -decreasing $fileList]
    cd $oldDir
    if ![llength $fileList] {return -code error "No files found in $mainDir!"}
    if [winfo exist .review] {
        destroy .review
    }
    set FileSelection ""
    APSScrolledListWindow .review -name "" \
        -label "Select a scan data file" \
        -itemList $fileList -selectionVar FileSelection 
    
    tkwait variable FileSelection
    PlotFile -file $FileSelection -dir $mainDir
    
}

proc PlotFile {args} {
    set file ""
    set dir ""
    APSParseArguments {file dir}
    global plotStart plotStop separate samescale layoutOption plotType mainDir
    if ![string length $file] {
        SetMainStatus "No file is chosen."
        return
    }
    if ![string length $dir] {
	set plotFile $file
    } else {
	set plotFile $dir/$file
    }
    set plotOption ""
    if $separate {
        append plotOption " -separate=page -split=page -group=page"
    }
    if $samescale {
        append plotOption " -samescale=y"
    }
    if {$plotType=="LOG"} {
        append plotOption " -col=Index,S36AM:BP:mca.VAL $plotFile -mode=y=logarithmic,y=special -tickSettings=ylogarithmic -scale=$plotStart,$plotStop,0,0"
    } else {
        append plotOption " -col=Index,S36AM:BP:mca.VAL $plotFile -scale=$plotStart,$plotStop,0,0"
    }
  #  SetMainStatus "sddsplot $layoutOption $plotOption -legen=parameter=BucketNumber"
    eval exec sddsplot $layoutOption $plotOption -legen=parameter=BucketNumber -topline=@S36AM:BP:mca.ELTM &
}

set mainStatus "ready."
set archiveDir /home/helios/oagData/sr/bunchPurity/24bucketPurity
set mainDir $archiveDir
set plotStart 1800
set plotStop  3000
set plotType  LOG
set separate 0
set samescale 0 
APSApplication . -name ScanBucketPurity -version $CVSRevisionAuthor \
    -overview {This application scans bunch purity data for each bucket in 24 bucket pattern and archive the data for review. The goal is to be able to trace bunch purity corruption during top-up.}

APSScrolledStatus .status -parent .userFrame \
    -textVariable mainStatus -width 80 \
    -withButtons 1 
APSLabeledEntry .dir -parent .userFrame -label "Main Directory:" \
    -textVariable mainDir -width 70 -contextHelp "provide the directory for saving bunch purity files."

APSFrameGrid .grid -parent .userFrame -xList {x1 x2} -packOption "-side top -fill x"
set w1 .userFrame.grid.x1
set w2 .userFrame.grid.x2
APSLabeledEntry .plotstart -parent $w1  -label "Plot start:" -textVariable plotStart \
    -contextHelp "Enter starting channel # for plot." -width 10 -packOption "-side top -fill x"
APSLabeledEntry .plotstop -parent $w1 -label "Plot stop:" -textVariable plotStop \
      -contextHelp "Enter ending channel # for plot." -width 10 -packOption "-side top -fill x"
# radio button for plotType selection
set plotTypeList {LOG LINEAR}
APSRadioButtonFrame .plotChoiceFrame -parent $w2   -orientation  horizontal \
    -packOption {-side top -fill x}  -label "   Plot Type:" \
    -variable plotType -buttonList $plotTypeList \
    -valueList  $plotTypeList \
    -contextHelp "This radio button is used to select a plot type."

set separate 1
set samescale 0    
APSCheckButtonFrame .group -parent $w2  -orientation  horizontal \
    -packOption {-side top -fill x}  -label "   Grouping:" \
    -buttonList {separate "same scale"}  -variableList  {separate samescale}  \
    -contextHelp "select grouping option for plotting multiple files."

set layoutOption "-layout=1,1"
APSRadioButtonFrame .layout -parent $w2 -orientation  horizontal \
    -packOption {-side left}  -variable layoutOption \
    -label "   Layout:"  -buttonList {1x1 2x2 3x3 4x4 5x5}  \
    -valueList  {-layout=1,1 -layout=2,2 -layout=3,3 -layout=4,4 -layout=5,5} \
    -contextHelp "Chooses how plot panels are layed out on a plot page.  If you choose to separate data on panels using the Grouping choices, you may also want a Layout other than the default 1x1."

APSButton .scan -parent .userFrame -text "Scan" -command "Scan &" \
    -contextHelp "scan each bucket in 24 bucket pattern."
APSButton .review -parent .userFrame -text "Review" -command "Review &" \
    -contextHelp "review bucket bunch purity data."

set abort 0
APSButton .abort -parent .userFrame -text "Abort" -command "set abort 1"