
# Comparison of SR BPM memory scanners and scdu's using sddsstatmon.

proc APSSRCompareMSSCDU {args} {
    set samples 60 
    set interval 1
    set fileName ""
    set flagSuffix "MSSCDU"
    set statusCallback "puts stderr"
    set reprocess 1
    APSStrictParseArguments {samples interval fileName statusCallback flagSuffix reprocess}

    set input /home/helios/oagData/sr/sddsmonitorFiles/scdu+ms.mon

    if [string length $fileName]==0 {
        return -code error "APSSrCompareMSSCDU: no fileName supplied"
    }
    if $reprocess {
        if ![file exists $fileName.raw] {
            return -code error "APSSrCompareMSSCDU: $fileName doesn't exist, but in reprocess mode."
        } 
    } else {
        if [string length $statusCallback] {
            eval $statusCallback {"Acquiring $samples SCDU/MS samples at intervals of $interval seconds."}
        }
        set tmpFile /tmp/[APSTmpString]
        if [catch {exec sddsstatmon $input $fileName.raw -erase \
                     -steps=1 -samples=${samples} -interval=${interval},seconds \
                     -includeStatistics=mean,sigma} result] {
            if [string length $statusCallback] {
                eval $statusCallback {"APSSrCompareMSSCDU: $result"}
            }
            catch {exec rm $tmpFile}
            return -code error "APSSrCompareMSSCDU: $result"
        }
        if [string length $statusCallback] {
            eval $statusCallback {"Finished data acquisition.  Processing..."}
        }
    }

    if [catch \
          {exec sddscollect $fileName.raw -pipe=out -collect=suffix=:scdu:xMean  \
             -collect=suffix=:scdu:yMean  -collect=suffix=:scdu:xSigma \
             -collect=suffix=:scdu:ySigma -collect=suffix=:ms:xMean    \
             -collect=suffix=:ms:yMean    -collect=suffix=:ms:xSigma   \
             -collect=suffix=:ms:ySigma   \
             | sddsprocess -pipe \
             -edit=column,BPMName,Rootname,eb%/:// \
             -process=:*:?Sigma,average,%sMean,toplimit=0.25 \
             "-define=col,xNormDeviation,:scdu:xMean :ms:xMean - abs :scdu:xSigmaMean sqr :ms:xSigmaMean sqr + sqrt 1e-16 + /" \
             "-define=col,yNormDeviation,:scdu:yMean :ms:yMean - abs :scdu:ySigmaMean sqr :ms:ySigmaMean sqr + sqrt 1e-16 + /" \
             "-define=col,xFlag${flagSuffix},xNormDeviation 3 > ? 0 : 1 $ ,type=short" \
             "-define=col,yFlag${flagSuffix},yNormDeviation 3 > ? 0 : 1 $ ,type=short" \
             "-define=col,Flag${flagSuffix},xFlag${flagSuffix} yFlag${flagSuffix} + 2 / int,type=short" \
             | sddsprocess -pipe=in  $fileName \
             -process=*Flag${flagSuffix},sum,%sSum 
             } result] {
        eval $statusCallback {"APSSrCompareMSSCDU: $result"}
        return -code error "APSSrCompareMSSCDU: $result"
    }
    if [string length $statusCallback] {
        eval $statusCallback {"Finished processing."}
    }
}

