#!/bin/bash

np=`nproc`
# The LMA file is for a single sector, so filter the twiss file to cover the same interval
sddsprocess lma.twi lma.twi1 -filter=col,s,0,27.61

for sem in run-*kHz.done ; do
    # Loop over all runs
    leader=${sem/.done/}
    echo $leader ...
    tlist=""
    for bunch in ${leader}.sa??? ; do
        # Loop over bunches (slice analysis files)
        sddssplit $bunch -digits=3 -rootname=$bunch- -exten=
        count=0
        for sample in ${bunch}-??? ; do
            # Loop over bunch samples (pages of slice analysis files)
            (touschekLifetime -twiss=lma.twi1 -aperture=lma.mmap -sliceAnalysis=$sample $sample.tl -ignoreMismatch) &
            count=$((count+1))
            if [ $count -eq $np ] ; then
                wait
                count=0
            fi
        done
        wait
        \rm ${bunch}-???
        # Combine lifetime results for this bunch, compute statistics over all samples
        sddscombine ${bunch}-???.tl -collapse  -pipe=out \
            | sddsprocess -pipe=in ${bunch}.tl -process=tLifetime,ave,%sAve -process=tLifetime,stand,%sStDev
        \rm ${bunch}-???.tl
        tlist="$tlist ${bunch}.tl"
    done
    # Combine lifetime stats for this run
    sddscombine $tlist -pipe=out -collapse | sddsconvert -pipe=in $leader.tl -rename=col,PageNumber=BunchNumber
    \rm $tlist
done


