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


set auto_path [linsert $auto_path 0 /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]
APSStandardSetup

set CVSRevisionAuthor "\$Revision: 1.3 $ \$Author: shang $"

proc measureCharge {args} {
    global totalCharge darkCharge photoCharge measPhase driveLaser QE QEError
    global totalChargeError darkChargeError photoChargeError measPhaseError driveLaserError
    global status average outputFile

    set timeStamp [exec date]
    set status "setup the average..."
    if [catch {exec cavget -list=L1:PG1:CM1:measCurrentCM.CAVG \
                   -printErrors -pend=30} oldAve] {
        return -code error $oldAve
    }
    if [catch {exec cavput -list=L1:PG1:CM1:measCurrentCM.CAVG=1 -pend=30} result] {
        return -code error $result
    }
    
    set status "measure the dark charge..."
    if [catch {exec cavput -list=L:LR:shutter4C=0 -pend=30} result] {
        return -code error $result
    }
    if [catch {exec cavget -list=L1:PG1:CM1:measCurrentCM.CVAL \
                   -repeat=number=$average,pause=0.25,average,sigma} darkCharges] {
        return -code error $darkCharges
    }
    set darkCharge [lindex $darkCharges 0]
    set darkChargeError [lindex $darkCharges 1]
    
    set status "measure the total charge..."
    if [catch {exec cavput -list=L:LR:shutter4C=1 -pend=30} result] {
        return -code error $result
    }
    if [catch {exec cavget -printErrors -pend=30 \
                   -list=L1:PG1:CM1:measCurrentCM.CVAL,L1:PG1:DC1AIQ.VAL,L:LR:EM:chBenergyM.VAL \
                   -repeat=number=$average,pause=0.25,average,sigma} valList] {
        return -code error $valList
    }
    set totalCharge [lindex $valList 0]
    set totalChargeError [lindex $valList 1]
    set measPhase [lindex $valList 2]
    set measPhaseError [lindex $valList 3]
    set driveLaser [expr [lindex $valList 4]*1.0e6]
    set driveLaserError [expr [lindex $valList 5]*1.0e6]
    set photoCharge [expr $totalCharge - $darkCharge]
    set photoChargeError [expr sqrt($totalChargeError * $totalChargeError + $darkChargeError * $darkChargeError)]
    set status "put the averager back."
    if [catch {exec cavput -list=L1:PG1:CM1:measCurrentCM.CAVG=$oldAve} result] {
        return -code error $result
    }
    
    #calculate QE, one photon energy is 4.69eV
    set nPhoton [expr $driveLaser*1.0e-6/(4.69*1.6e-19)]
    set nElectron [expr $photoCharge*1.0e-9/1.6e-19]
    set QE [expr 100*$nElectron/$nPhoton]
    #set QE [expr 100.0*$photoCharge*1.0e-3/$driveLaser*4.69]
    # set status "The quantume efficiency is $QE"
    set nPError [expr $driveLaserError * 1.0e-6/(4.69*1.6e-19)]
    set nEError [expr $photoChargeError * 1.0e-9/1.6e-19]
    
    set QEError [expr $QE*sqrt($nEError/$nElectron*$nEError/$nElectron + $nPError*$nPError/$nPhoton/$nPhoton)]
    
    foreach term {totalCharge darkCharge  measPhase driveLaser photoCharge QE} {
        global ${term}ErrorLabel
        set ${term}ErrorLabel +/-[format %.5f [set ${term}Error]]
    }
    
    set tmpfile /tmp/[APSTmpString]
    if [catch {exec sddsmakedataset -par=TimeStamp,type=string "-data=$timeStamp" \
                   -par=AverageNumber,type=long -data=average \
                   -col=Name,type=string \
                   "-data=TotalCharge(nC),DarkCharge(nC),PhotoCharge(nC),GunPhase,DriveLaser(uJ),QE(%)" \
                   -col=Value,type=double \
                   -data=$totalCharge,$darkCharge,$photoCharge,$measPhase,$driveLaser,$QE \
                   -col=Error,type=string \
                   "-data=$totalChargeErrorLabel,$darkChargeErrorLabel,$photoChargeErrorLabel,$measPhaseErrorLabel,$driveLaserErrorLabel,$QEErrorLabel" $tmpfile} result] {
        return -code error $result
    }
    if [file exist $outputFile] {
	if [catch {exec sddscombine $outputFile $tmpfile $outputFile.1 -overwrite} result] {
	    return -code error $result
	}
	file delete -force $tmpfile
        exec mv $outputFile.1 $outputFile
    } else {
        exec mv $tmpfile $outputFile
    }
    set status "done."
}

proc ShowResults {args} {
    global outputFile
    if ![file exist $outputFile] {
	return -code error "No measurements had been taken."
    }
    APSExecLog .display -unixCommand "sddsprintout $outputFile -par=AverageNumber,format=%5ld \
       -par=TimeStamp,endsline -col=Name,format=%20s -col=Value,format=%20.5f -col=Error,format=%20s"
}


set outputFile /tmp/[APSTmpString].pcGunCharge
set average 5
APSApplication . -name "Measure PC Gun Charge" -version $CVSRevisionAuthor 
set status ""
APSScrolledStatus .status -parent .userFrame -textVariable status -width 100 \
    -withButtons 1
APSFrame .opt -parent .userFrame -label "Parameters"
APSFrame .charge -parent .userFrame.opt.frame -relief flat -label "Value" -width 30 \
    -packOption "-side left"

APSLabeledOutput .tot -parent .userFrame.opt.frame.charge.frame -label "Total Charge (nC):" \
    -textVariable totalCharge -width 30
APSLabeledOutput .dark -parent .userFrame.opt.frame.charge.frame -label "Dark charge (nC):" \
    -textVariable darkCharge -width 30
APSLabeledOutput .phot -parent .userFrame.opt.frame.charge.frame -label "Photo charge (nC):" \
    -textVariable photoCharge -width 30
APSLabeledOutput .gun -parent .userFrame.opt.frame.charge.frame -label "Gun Phase:" \
    -textVariable measPhase -width 30
APSLabeledOutput .drive -parent .userFrame.opt.frame.charge.frame -label "Drive Laser (uJ):" \
    -textVariable driveLaser -width 30
APSLabeledOutput .qe -parent .userFrame.opt.frame.charge.frame -label "QE (%):" \
    -textVariable QE -width 30

APSFrame .error -parent .userFrame.opt.frame -relief flat -label "Error" -width 30 \
    -packOption "-side left"
APSLabeledOutput .tot -parent .userFrame.opt.frame.error.frame -label "" \
    -textVariable totalChargeErrorLabel -width 30
APSLabeledOutput .dark -parent .userFrame.opt.frame.error.frame -label "" \
    -textVariable darkChargeErrorLabel -width 30
APSLabeledOutput .phot -parent .userFrame.opt.frame.error.frame -label "" \
    -textVariable photoChargeErrorLabel -width 30
APSLabeledOutput .gun -parent .userFrame.opt.frame.error.frame -label "" \
    -textVariable measPhaseErrorLabel -width 30
APSLabeledOutput .drive -parent .userFrame.opt.frame.error.frame -label "" \
    -textVariable driveLaserErrorLabel -width 30
APSLabeledOutput .qe -parent .userFrame.opt.frame.error.frame -label "" \
    -textVariable QEErrorLabel -width 30

APSLabeledEntry .ave -parent .userFrame -label "Average number:" \
    -textVariable average -width 30 -contextHelp "enter the average number for measuring charge."

APSButton .meas -parent .userFrame -text "Measure Charge" -command "measureCharge"
APSButton .show -parent .userFrame -text "Show Results" -command "ShowResults"
