#!/bin/bash

g2_prog="/Users/Ale/programs/g2/g2"

for((i=3;i<=18;i+=3))
do
	rf_780=$(echo "$i" | awk '{print $0/100}')
	for((j=1;j<=19;j+=2))
	do
		rf_776=$(echo "$j" | awk '{print $0/100}')

		power_776=$(awk '{if($1=='"$rf_780"' && $3=='"$rf_776"') print $4}' power.dat)

		# run g2 program on the current file
		$g2_prog -t 8 -m 600 -i "780_""$rf_780""_776_""$rf_776"".dat" -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 $power_776 " " $res " " $decay_time
		echo $power_776 $res " " $decay_time >> plot_data_"$rf_780".dat
	done
done


# 		singles=$($g2_prog -t 8 -m 1200 -i "780_""$rf_780""_776_""$rf_776"".dat" -o out.dat 2>&1 | awk '{print $2,$4}')

# 		pairs=$(awk 'BEGIN{sum=0;} {if($1>=325 && $1<365) sum+=$2;} END{print sum}' out.dat)
# 		acc=$(awk 'BEGIN{sum=0;} {if($1>=600 && $1<1000) sum+=$2;} END{print sum/400}' out.dat)
# 		g2_peak=$(awk '{if($1==328) print $2;}' out.dat)
# 		norm_g2=$(echo "$g2_peak $acc" | awk '{print $1/$2}')

# 		echo $power_776" "$pairs" "$singles" "$norm_g2 >> plot_data_"$rf_780".dat
# 	done
# done
