#!/usr/bin/perl

use strict;

my $run_number = $ARGV[0];

exit if $run_number!~/7\d{4}/ ;

#  some arrays to keep track of which rows and column to use for each mirror
#  8X19 Row_List[i][j] i: mirror number - 1 j:row number - 1 the value is 1 
#  if that row was used for timing and 0 if not
#  Col_List[i]: mirror number  the value is the 
#               col that was used for timing 1 or 2  

my @Row_List;

$Row_List[0] = [1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
$Row_List[1] = [1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
$Row_List[2] = [0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0];
$Row_List[3] = [0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0];
$Row_List[4] = [0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0];
$Row_List[5] = [0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0];
$Row_List[6] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0];
$Row_List[7] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0];

my @Col_List;
$Col_List[0] = 2;
$Col_List[1] = 1;
$Col_List[2] = 2;
$Col_List[3] = 1;
$Col_List[4] = 2;
$Col_List[5] = 1;
$Col_List[6] = 2;
$Col_List[7] = 1;



#    Making the necessary directories to store the data files in
print "checking for ${run_number}_fits\n";

if(!(-e "${run_number}_fits" )){
    system("mkdir ${run_number}_fits");
    print "mkdir ${run_number}_fits \n";
}

print "files will be moved to ${run_number}_fits\n existing files will be overwritten\n";

print "checking for subdirectories\n";

if(!(-e "${run_number}_fits/row_col_fits")){
    system("mkdir ${run_number}_fits/row_col_fits");
    print "mkdir ${run_number}_fits/row_col_fits/ \n";
}
if(!(-e "${run_number}_fits/tdc_mir_col_2d")){
    system("mkdir ${run_number}_fits/tdc_mir_col_2d");
    print "mkdir ${run_number}_fits/tdc_mir_col_2d \n";
}
if(!(-e "${run_number}_fits/tdc_mir_col_1d")){
    system("mkdir ${run_number}_fits/tdc_mir_col_1d");
    print "mkdir ${run_number}_fits/tdc_mir_col_1d \n";
}



print "moving the hbook file\n";

system("mv hist${run_number}.hbook ${run_number}_fits/");

print "moving all sum64 row and col fits\n";
print "moving all the 2-d tdc vs row plots\n";
print "moving all the 1-d tdc spectra for each mirror\n";
print "moving the data \n";
my @list = `ls | grep $run_number`;
chomp(@list);


foreach my $a (@list){
# Going through all the fit plots
# sorting through to find the ones used and not used for timing based
# on the row and column lists
    if($a =~ /plot\d{5}tdccol(\d)row(\d{1,2})mir(\d)\.(\w{3})/){
	my $col = $1;
	my $row = $2;
	my $mir = $3;
	my $format = "$4";
	my $col_flag = 0;
	my $row_flag = 0;
	$col_flag = $Col_List[$mir-1];
	$row_flag = $Row_List[$mir-1]->[$row-1];
	if($col_flag == $col && $row_flag == 1){
	    # plot was used
	    system("mv $a ${run_number}_fits/row_col_fits/good_mir${mir}col${col}row${row}.${format}");
	}else{
	    system("mv $a ${run_number}_fits/row_col_fits/unused_mir${mir}col${col}row${row}.${format}");
	}	    
    }
# Going through all the 2-d plots of tdc vs row.
    if($a =~ /plot\d{5}_mir(\d)_col(\d)_allrows\.(\w{3})/){
	my $mir = $1;
	my $col = $2;
	my $format = "$3";
	if($col == $Col_List[$mir-1]){
	    system("mv $a ${run_number}_fits/tdc_mir_col_2d/good_mir${mir}col${col}.${format}");
	}else{
	    system("mv $a ${run_number}_fits/tdc_mir_col_2d/unused_mir${mir}col${col}.${format}");
	}
    }
# Going through all the tdc spectra for each mir and col
    if($a =~ /plot\d{5}_mir(\d)_col(\d)tdc\.(\w{3})/){
	my $mir = $1;
	my $col = $2;
	my $format = "$3";
	if($col == $Col_List[$mir-1]){
	    system("mv $a ${run_number}_fits/tdc_mir_col_1d/good_mir${mir}col${col}.${format}");
#	    print "mv $a ${run_number}_fits/tdc_mir_col_1d/good_mir${mir}col${col}.${format}\n";
	}else{
	    system("mv $a ${run_number}_fits/tdc_mir_col_1d/unused_mir${mir}col${col}.${format}");
#	    print "mv $a ${run_number}_fits/tdc_mir_col_1d/unused_mir${mir}col${col}.${format}\n";
	}
    }
    if($a =~ /fit\d{5}tdccol(\d)mir(\d).dat/){
	if($1 == $Col_List[$2 - 1] ){
	    system("mv $a ${run_number}_fits/good_fitdata_col${1}_mir${2}.dat")
	}else{
	    system("mv $a ${run_number}_fits/unused_fitdata_col${1}_mir${2}.dat")
	}
    }
}

# Making a file with all the fits we used organized by mirror


print "cd to ${run_number}_fits \n";
chdir("${run_number}_fits/") or die "can't cd to ${run_number}_fits/\n";

my @data_list=`ls | grep good_fitdata`;
# raw data sorted and output
my @output;
# processed peak location and width estimate for each mirror
my @summary_output;
#    make new header;
push(@output,"# row height err centroid err sigma err\n");
foreach my $a (@data_list){
    if($a =~ /good_fitdata_col(\d)_mir(\d)\.dat/){
#       array to be used for the sum to determining avg peak position.
	my @sum;
#       similar array for th equadratic sum for the widths of the peaks (treating them like an error)
	my @qsum;

	my $mir = $2;
	my $col = $1; 
	open(READ,"$a");
	my @lines = <READ>;
	chomp(@lines);
	close(READ);
#    remove header	
	shift(@lines);
#    make header for this mirror
	push(@output,"# mir $mir\n");
#    each line corresponds to a sum64 row. finding the ones that were used
	for(my $i = 0; $i<19 ; $i++){
	    if($Row_List[$mir-1]->[$i]){
		my @entries = split(/\s+/,@lines[$i]);
		my $row = $i+1;
		push(@sum,$entries[3]);
		push(@qsum,$entries[5]);
		push(@output,"$row $entries[1] $entries[2] $entries[3] $entries[4] $entries[5] $entries[6]\n");		
	    }
	}

#  building summary file
	push(@summary_output,"# mir $mir\n");
#  calculating average and std deviation of the peak position;
	my $avg_pos = 0;
	my $std_dev = 0;
	my $error = 0;
	foreach(@sum){
	    $avg_pos = $_ + $avg_pos;
	}
	$avg_pos = $avg_pos/@sum;
	foreach(@sum){
	    $std_dev = $std_dev + ($_ - $avg_pos)**2;
	}
	$std_dev = sqrt($std_dev/@sum);
# calculating the quadratic sum divided by n of the sigmas.
	foreach(@qsum){
	    $error = $error + ($_)**2; 
	}
	$error = sqrt($error)/@sum;
	$error = sqrt($error**2 + $std_dev**2);
	push(@summary_output,"$avg_pos  $error\n");
    }
}
open(WRITE,">timing_data.dat");
foreach(@output){
    print WRITE;
}
close(WRITE);
open(WRITE,">tdc_summary.dat");
foreach(@summary_output){
    print WRITE;
}
close(WRITE);
