#!/usr/local/bin/perl
use strict;
use warnings;

my $ana_flag = 0;
my $force_flag = 0;
my $save_flag = 0;
my $xtalk_flag = 0;
my $ext_flag = 0;
my $corr_flag = 0;
my $command;

if($ARGV[0]){
    if($ARGV[0] =~ m/-/){
	if($ARGV[0] =~ m/[aA]/){
	    $ana_flag = 1;
	}
	if($ARGV[0] =~ m/[fF]/){
	    $force_flag = 1;
	}
	if($ARGV[0] =~ m/[sS]/){
	    $save_flag = 1;
	}
	if($ARGV[0] =~ m/[xX]/){
	    $xtalk_flag = 1;
	}
	if($ARGV[0] =~ m/[eE]/){
	    $ext_flag = 1;
	}
	if($ARGV[0] =~ m/[cC]/){
	    $corr_flag = 1;
	}
    }
}

my $data_dir = "./data/QDC";
my $result_dir = "./results";
my @filter_list = ('DarkRun','Filter=1%','Filter=2%','Filter=4%','Filter=6%');
my @sipm_list = glob($data_dir."/"."SiPM_*");
my @file_list = ("All_Histogram.png","Distribution.png","Results.txt","History.png","Average.txt","Settings.txt");
open (my $list_file, ">", "./list.txt") or die "Can't open list.txt: $!";

my $sipm;
my $filter;
my $date;
my $des_dir;

foreach $sipm (@sipm_list)
{
    $sipm =~ s/.*\///;
    print $sipm,"\n";
    print $list_file $sipm,"\n";

    foreach $filter (@filter_list)
    {
#	print $filter,": ";

	my @data_list = glob($data_dir."/".$sipm."/".$filter."/*");

	foreach my $data_dir (@data_list)
	{
	    $date = $data_dir;
	    $date =~ s/(.*\/|_.*)//g;
	    print $list_file $data_dir,"\n";

	    # analyze data
	    if($ana_flag)
	    {
		if(!(-f $data_dir."/Results.txt")||$force_flag)
		{
		    $command = "root -l ".$data_dir." ".$xtalk_flag." ".$save_flag." replay.C+ -q";
		    $command =~ s/\..*QDC\///;
		    print $command."\n";
		    system($command);
		}
		if(!(-f $data_dir."/Average.txt")||$force_flag)
		{
		    $command = "root -l ".$data_dir." ".$save_flag." average.C+ -q";
		    $command =~ s/\..*QDC\///;
		    print $command."\n";
		    system($command);
		}
	    }
	    
	    # test directory
	    my @dir_list = ($sipm,$date,$filter);
	    $des_dir = $result_dir;
	    foreach my $app_dir (@dir_list)
	    {
		$des_dir .= "/".$app_dir;
		unless(-d $des_dir)
		{
		    system("mkdir ".$des_dir);
		}
	    }

	    # start copy results to new directory
	    foreach my $file (@file_list)
	    {
		if(-f $data_dir."/".$file)
		{
		    system("cp -f ".$data_dir."/".$file." ".$des_dir);
		}
	    }
	}
    }
    if($ext_flag)
    {
	$des_dir = $result_dir."/".$sipm."/".$date;
	if(-f $des_dir."/Filter=6%/Results.txt")
	{
	    if((!(-f $des_dir."/Summary.txt")&&($corr_flag))
	       ||(!(-f $des_dir."/Summary_nc.txt")&&(!$corr_flag))
	       ||$force_flag)
	    {
		$command = "root -l ".$result_dir."/".$sipm."/".$date." ".$corr_flag." ".$save_flag." extract.C+ -q";
		$command =~ s/\..*results\///;
		print $command,"\n";
		system($command);
	    }
	}
    }
}
close $list_file or die "$list_file: $!";
