#!/bin/sh
# \
exec oagwish "$0" "$@"
set dataDir /usr/local/oag/apps/src/appconfig/SRrf



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.11 $ \$Author: borland $"

APSApplication . -name "SRrfProbeCal" -version $CVSRevisionAuthor \
  -overview "This utility does calibration of storage ring field probes based on forward and reflected power values.  Both rf systems must be operating."

set tcl_precision 4
set stationList { 1  2  3  4}
set sectorList  {40 36  37 38}

set mainStatus "Ready."
APSScrolledStatus .status -parent .userFrame -width 60 -textVariable mainStatus \
        -height 2

set Averages 10
frame .userFrame.aveentry
pack .userFrame.aveentry -side top
APSLabeledEntry .ave -parent .userFrame.aveentry -width 10 -textVariable Averages \
  -label "Readings to average for each factor: " \
  -contextHelp "Entry the number of readings to average to get each loss factor."

set Station 0
set Sector 0
set Cavity 0
APSFrame .update -parent .userFrame -label "Working On"  
set w .userFrame.update.frame
APSLabeledOutput .station -parent $w -width 10 -label "Station: " \
  -contextHelp "Shows the rf station being worked on." \
  -textVariable Station
APSLabeledOutput .sector -parent $w -width 10 -label "Sector: " \
  -contextHelp "Shows the rf sector being worked on." \
  -textVariable Sector
APSLabeledOutput .cavity -parent $w -width 10 -label "Cavity: " \
  -contextHelp "Shows the rf cavity being worked on." \
  -textVariable Cavity

APSFrame .results -parent .userFrame -label "Loss factor results (dB)" 
set resFrame .userFrame.results.frame
foreach sector $sectorList {
    if $sector==0 continue
    APSLabeledEntryFrame .sector${sector} -parent $resFrame -label "Sector $sector" \
      -variableList "S${sector}C1Loss S${sector}C2Loss S${sector}C3Loss S${sector}C4Loss"  \
      -noPack 1 \
      -contextHelp "Will show new loss factors.  Enter ? to erase a value for remeasurement \
or to inhibit its use."
    pack $resFrame.sector${sector} -side left -fill x
    foreach cavity {1 2 3 4} {
        set S${sector}C${cavity}Loss ?
    }
}


APSFrame .op -parent .userFrame -label "" 
set w .userFrame.op.frame
APSButton .go -parent $w -text "GO" \
  -command MeasureLossFactors \
  -contextHelp "Initiates measurement of loss factors."
APSButton .clear -parent $w -text CLEAR \
  -command ClearMeasurements \
  -contextHelp "Clears measurement results in preparation for a new set."
APSButton .send -parent $w -text "SEND" \
  -command SendLossFactors \
  -contextHelp "Sends loss factors to the IOCs"
APSButton .present -parent $w -text "READ" \
  -command GetPresentValues \
  -contextHelp "Reads present loss factors to the IOCs"

proc SetMainStatus {text} {
    global mainStatus
    set mainStatus $text
    update
}


proc ReadStationData {Station Cavity dataFile} {
    global fwdPwr revPwr probePwr probeLoss
    global fwdPwrName revPwrName probePwrName probeLossName
    set fwdPwrName    S${Station}C${Cavity}ForwardPowerMean
    set revPwrName    S${Station}C${Cavity}ReversePowerMean
    set probePwrName  S${Station}C${Cavity}ProbePowerMean

    set fwdPwr [lindex [APSGetSDDSColumn -fileName $dataFile -column $fwdPwrName -page 0] 0]
    set revPwr [lindex [APSGetSDDSColumn -fileName $dataFile -column $revPwrName -page 0] 0]
    set probePwr [lindex [APSGetSDDSColumn -fileName $dataFile -column $probePwrName -page 0] 0]
    set probeLossName S${Station}:C:envDet${Cavity}Ch2Loss

    catch {exec cavget "-list=$probeLossName"} probeLoss
#    puts "$fwdPwr $revPwr $probePwr $probeLoss"
}


update

proc GetPresentValues {} {
    global sectorList stationList
    set index 0
    foreach Sector $sectorList {
        set Station [lindex $stationList $index]
        incr index
        if {$Sector==0} continue
        foreach Cavity {1 2 3 4} {
            global S${Sector}C${Cavity}Loss
            set probeLossName S${Station}:C:envDet${Cavity}Ch2Loss
            set S${Sector}C${Cavity}Loss [exec cavget -list=$probeLossName]
            update
        }
    }
}

proc ClearMeasurements {} {
    global sectorList stationList
    set index 0
    foreach Sector $sectorList {
        set Station [lindex $stationList $index]
        incr index
        if {$Sector==0} continue
        foreach Cavity {1 2 3 4} {
            global S${Sector}C${Cavity}Loss
            set S${Sector}C${Cavity}Loss "?"
        }
    }
}

proc MeasureLossFactors {} {
    global fwdPwr revPwr probePwr probeLoss
    global fwdPwrName revPwrName probePwrName probeLossName
    global Cavity Sector Station sectorList stationList dataDir Averages
    set done 0
    SetMainStatus "Measuring..."

    set takeData 0
    set index 0
    foreach Sector $sectorList {
        set Station [lindex $stationList $index]
        incr index
        if {$Sector==0} continue
        foreach Cavity {1 2 3 4} {
            update
            global S${Sector}C${Cavity}Loss
            if [string compare [subst \$S${Sector}C${Cavity}Loss] "?"]==0 {
                set takeData 1
                break
            }
        }
        if $takeData break
    }

    if !$takeData {
        SetMainStatus "No measurements taken...all values present."
        return
    }

    set dataFile /tmp/[APSTmpString]
    exec sddsstatmon $dataDir/SRrfProbeCal.mon $dataFile "-interval=0.5,s" \
         -step=1 -samples=$Averages
    exec sddsconvert $dataFile ${dataFile}0 "-retain=col,*Mean"
    exec rm $dataFile
    set dataFile ${dataFile}0

    set index 0
    foreach Sector $sectorList {
        set Station [lindex $stationList $index]
        incr index
        if {$Sector==0} continue
        foreach Cavity {1 2 3 4} {
            update
            global S${Sector}C${Cavity}Loss
            if [string compare [subst \$S${Sector}C${Cavity}Loss] "?"]!=0 {
                SetMainStatus "Skipping S${Sector}C${Cavity}"
                continue
            }
            ReadStationData $Station $Cavity $dataFile
            if {$fwdPwr<100} {
                SetMainStatus "Forward power too low ($fwdPwr)"
                continue
            }
            if {$probePwr<100} {
                SetMainStatus "Probe power too low ($probePwr)"
                continue
            }
            set errorRatio [expr ($fwdPwr-1.0*$revPwr)/(1.0*$probePwr)]
            SetMainStatus "Ratio for S${Sector}C${Cavity}: $errorRatio"
            set lossFactor [expr $probeLoss+10.0*log10($errorRatio)]
            set S${Sector}C${Cavity}Loss $lossFactor
            incr done
        }
    }
    exec rm $dataFile
    SetMainStatus "Done with $done calibrations."
}

proc SendLossFactors {} {
    global fwdPwr revPwr probePwr probeLoss
    global fwdPwrName revPwrName probePwrName probeLossName
    global Cavity Sector Station sectorList stationList
    set index 0
    set done 0
    SetMainStatus "Working..."
    foreach Sector $sectorList {
        set Station [lindex $stationList $index]
        incr index
        if {$Sector==0} continue
        foreach Cavity {1 2 3 4} {
            update
            set probeLossName S${Station}:C:envDet${Cavity}Ch2Loss
            global S${Sector}C${Cavity}Loss
            set value [subst \$S${Sector}C${Cavity}Loss]
            if [string length $value]==0 continue
            if [string compare $value "?"]==0 continue
            exec cavput -list=$probeLossName=$value
            incr done
        }
    }
    SetMainStatus "Done."
}
