# procedures to be change for APS-U

# initial change completed 7/22/2024
proc APSSRReadBunchCM {args} {
    # Reads the bunch-by-bunch current monitor (BCM), which is already calibrated and
    # baseline substracted.
    # Doesn't do any setup of the BCM.

    set output ""
    #  average is used as number of samples by acquisition
    set average 1
    # if median is 0, then averaging of above sample is used.
    set median 1
    set targetFile ""
    set timeLimit 20
    set noScalars 0
    set S-DCCT ""
    set interval 1
    
    set monitorFilesDir /home/helios/oagData/sr/sddsmonitorFiles
    set clockSecs [clock seconds]
    if {[APSStrictParseArguments {output average median targetFile noScalars \
                                      S-DCCT interval }] || \
            ![string length $output] || $average<=0} {
        return -code error "APSSRReadBunchCM: bad arguments"
    }

    set PVPrefix SR:BCM:
    # note that SR:BCM:BunchQ has units of mA, not nC
    set WaveformPV SR:BCM:BunchQ,S-INJ:BunchChargeSetpointArrayM
    
    set tmpFile /tmp/[APSTmpString]
    set scalarsArg ""
    if !$noScalars {
        # that is, scalars are desired
        set scalarsArg -scalars=$monitorFilesDir/BunchCM.scalars 
    }
    # had to remove ,${PVPrefix}BunchNumbers; no connection on weed
    if [catch {eval exec sddswmonitor -PVnames=$WaveformPV \
                   $scalarsArg -step=$average -interval=$interval $tmpFile} result] {
        return -code error "APSSRReadBunchCM: (sddswmonitor) $result"
    }
    
    if [catch {exec cavget -list=A014-IETS:BTC:SRSetFreqM -flo=%0f} rfFRequency ] {
        return -code error "APSSRReadBunchCM: $result"
    }
    set revFreq [expr $rfFRequency / 1296]
    # is there a target file??
    # there is a PV called S-INJ:ActiveBunchChargeSetpointArrayM
    # maybe we could use that as reference
    if [string length $targetFile] {
        if [catch {exec sddsxref $tmpFile $targetFile -pipe=out \
                       -take=TargetCurrent \
                       | sddsconvert -pipe -rename=col,Index=Bucket \
                       | sddsprocess -pipe=in $output \
                       "-def=col,BunchCurrent,SR:BCM:BunchQ" \
                       "-define=column,CurrentDeficit,TargetCurrent BunchCurrent -,units=mA" \
                       "-process=CurrentDeficit,max,CurrentDeficitMax" \
                       "-process=CurrentDeficit,max,CurrentDeficitMaxBucket,position,func=Bucket" \
                   } result] {
            return -code error "APSSRReadBunchCM: $result"
        }
        # catch {eval file delete $tmpFile $tmpFile.1}
    } else {
        if !$median {
            # if not median processing, then do average processing
            # the extra column acquired S-INJ:BunchChargeSetpointArrayM is constant, so we copy from first page
            exec sddsconvert $tmpFile -pipe=out -rename=col,Index=Bucket \
                | sddsenvelope -pipe \
                -mean=SR:BCM:BunchQ -copy=Bucket,S-INJ:BunchChargeSetpointArrayM \
                | sddsconvert -pipe -edit=col,*Mean,%/Mean// \
                | sddsprocess -pipe=in $tmpFile.col \
                -print=para,Processing,Average \
                "-def=col,BunchCurrent,SR:BCM:BunchQ,units=mA"

            # process the scalars.
            exec sddsconvert $tmpFile -pipe=out \
                -dele=col,* \
                -dele=para,TimeStamp,PageTimeStamp,S-INJ:InjectionModeC,S-INJ:BucketSelectModeC  \
                | sddscollapse -pipe \
                | sddsprocess -pipe \
                -proc=*,ave,%sAve \
                | sddsconvert -pipe \
                -edit=col,*Ave,%/Ave// \
                | sddsexpand -pipe=in ${tmpFile}.para

            exec sddsxref ${tmpFile}.col  ${tmpFile}.para $output \
                -transfer=para,*
            
        } else {
            # do median processing
            exec sddsconvert $tmpFile -pipe=out -rename=col,Index=Bucket \
                | sddsenvelope -pipe \
                -median=SR:BCM:BunchQ -copy=Bucket,S-INJ:BunchChargeSetpointArrayM \
                | sddsconvert -pipe -edit=col,*Median,%/Median// \
                | sddsprocess -pipe=in $tmpFile.col \
                -print=para,Processing,Median \
                "-def=col,BunchCurrent,SR:BCM:BunchQ,units=mA"

            exec sddsconvert $tmpFile -pipe=out \
                -dele=col,* \
                -dele=para,TimeStamp,PageTimeStamp,S-INJ:InjectionModeC,S-INJ:BucketSelectModeC \
                | sddscollapse -pipe \
                | sddsprocess -pipe \
                -proc=*,median,%sMedian \
                | sddsconvert -pipe \
                -edit=col,*Median,%/Median// \
                -dele=para,* \
                | sddsexpand -pipe=in ${tmpFile}.para

            exec sddsxref ${tmpFile}.col  ${tmpFile}.para $output \
                -transfer=para,*
                
        }
    }
    set files [glob ${tmpFile}*]
    catch {eval file delete -force $files}
}

proc APSSRMakeTargetFillPattern {args} {
    # Reads the fill pattern current in the machine and produces a file
    # giving the target fill pattern.  The target fill pattern is based on
    # maintaining the same current as presently in the machine (or a
    # defined level) 

    set output ""
    # Optionally define how much current to define as the target.
    # By default (value of exactly 0), uses what's in the machine now.
    set targetCurrent 0
    
    if {[APSStrictParseArguments {output targetCurrent}] || \
            ![string length $output] || \
            $targetCurrent<0} {
        return -code error "APSSRMakeTargetFillPattern(0): bad arguments"
    }
    if {$targetCurrent == 0 } {
        # read the DCCT 10 times to get a stable averaged value
        if [catch {exec cavget -list=S-DCCT:currentM -repeat=number=10,pause=0.5,average} \
                targetCurrent] {
            return -code error "APSSRMakeTargetFillPattern(1): $targetCurrent"
        }
    }
    set tmpFile /tmp/[APSTmpString]
    if [catch {exec sddswmonitor -PVnames=SR:BCM:BunchQ -step=1 \
                 $tmpFile} result] {
        return -code error "APSSRMakeTargetFillPattern(2): $result"
    }
    # make bunch pattern for pure multiplet pattern.
    # all bunches should have the same charge.
    if [catch {exec sddsprocess $tmpFile -pipe=out \
                   -define=para,LowerLimit,0.01,units=mA \
                   -define=parameter,targetCurrent,$targetCurrent,units=mA \
                   "-define=col,BucketFilled,SR:BCM:BunchQ LowerLimit > ? pop pop 1 : 0 \$ " \
                   -process=BucketFilled,sum,BunchCount \
                   "-define=parameter,MLevel,targetCurrent BunchCount /,units=mA" \
                   "-define=column,TargetCurrent,MLevel BucketFilled *,units=mA" \
                   | sddsconvert -pipe=in $output \
                   -rename=column,Index=Bucket \
                   -retain=column,Bucket,TargetCurrent,Index} result] {
        return -code error "APSSRMakeTargetFillPattern(3): $result"
    }
    catch {file delete $tmpFile}
}


proc APSSRReadBunchCMSampleBySample {args} {
    # Reads the bunch-by-bunch current monitor ADC by samples.
    # There are 74 interleaved samples per rf buckets
    # so there is 74 x 1296 values.
    # The data is not calibrated.
    # Doesn't do any setup of the BBB current monitor.
    
    set output ""
    
    if { [APSStrictParseArguments {output} ]} {
        return -code error "APSSRReadBunchCMTurnByTurn: bad arguments"
    }
    set PVPrefix SR:BCM
    
    set file BCM-ADC-[clock format [clock seconds] -format "%Y-%m%d-%H%M%S"].raw
    if [catch {exec sddswget -PV=SR:BCM:ADC $file \
               } result] {
        return -code error "APSSRReadBunchCMTurnByTurn:$result"
    }
    if [string length $output] {
        exec mv $file $output
    }
}

