#!/bin/bash
# Program to generate a table of repump rf power, OD, pair rate, singles rate, peak coincidence rate, g2 decay time and their respective errors.
# output file column format :
# Col1 - repump laser AOM rf power
# Col2 - Optical density
# Col3 - error in Optical density (from fit)
# Col4 - Peak value of coincidence rate within 1 ns bin width
# Col5 - error in Col4
# Col6 - Pair rate in coincidence window of 50 ns
# Col7 - error in Col6
# Col8 - Singles rate of 762
# Col9 - error in col8
# Col10- Singles rate of 795
# Col11- error in Col10
# Col12- g2 decay time from exponential fit
# Col13- error in col12


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

# loop over all timestamp raw files for different repump rf powes.
for f in $(ls repump*.dat)
do
	# Extract rf power from filename
	rf=$(echo $f | grep -E -o "[0-9]\.[0-9]*") 
	
	# run g2 program on the current file	
	$g2_prog -t 8 -m 600 -i $f -o out.dat

	# Extract time of measurement, singles, pairs and peak coincidences from out.dat. Peak occurs at a delay of 328 ns. Coincidence window from 325 to 375 ns.
	res=$(awk '
	BEGIN{
	  sum=0;
	};
	{
	     if(NR==1)
	     {
		s1=$3;
		s2=$5*1;
	     }  
	     if(NR==2)
	     {
		t=($3/(16*8000000000));
	     }
	     if($1>=325 && $1<375)
	     {
	     	if($1==328)
	     	  {
		    p=$2;
		    sum+=$2;
	     	  }
		else
		  {
		    sum+=$2;
		  }
	     }
	     
	}
	END{
	     print p/t " " sqrt(p)/t " " sum/t " " sqrt(sum)/t " "  s1/t " " sqrt(s1)/t " " s2/t " " sqrt(s2)/t
	   }' out.dat)

	# Extract g2 decay time from the exponential fit (gnuplot file: exponential_fit.gnu) 
	decay_time=$(gnuplot exponential_fit.gnu 2>&1 | tail -n 1)

	# Write all the values to the std out and data file.
	echo $rf " " $res " " $decay_time
	echo $rf " " $res " " $decay_time >> plot_data.dat
done

