
g2_prog="/home/qitlab/programs/g2/g2"

for f in $(ls rf_*.dat)
do
	$g2_prog -t 8 -m 600 -i $f -o out.dat
	
	# Extract singles from first row (NR==1) in out.dat (in <s1> and <s2>)
	# Extract time of measurement from 2nd row (NR==2) (in <t>)
	# Extract peak coincidences at time delay of 328 ns (in <peak>)
	# Extract total pairs from coincidence time window 325 ns to 375 ns (in <sum>)
	# accidental coincidences = singles1_rate * singles2_rate * 1 ns (bin width) (in <base>)
	# propagated statistical error in normalized g2 (in err)
	awk 'BEGIN{sum=0;peak=0;};
		  {
		   if(NR==1){s1=$3;s2=$5*1;};
		   if(NR==2){t=$3/(16.03*8000000000);}; 
		   if($1==328){peak=$2;}; 
		   if($1>=325 && $1<375){sum+=$2};}; 
             END{
		   peak_rate=peak/t; 
		   base=(s1*s2/(t^2))*10^(-9); 
		   pair_err=(sqrt(peak)/t);
		   s1_err=(sqrt(s1)/t);
		   s2_err=(sqrt(s2)/t);
		   err=sqrt((pair_err/base)^2 \
		        + (peak_rate*s1_err/((s1/t)*base))^2 \
			+ (peak_rate*s2_err/((s2/t)*base))^2);
		   print sum/(t) " " peak_rate/base " " base " " s1/t " " s2/t " " err
		}' out.dat >> rate_g2_singles.dat
done
