#!/opt/star/rh80_gcc32/bin/perl -w

#-- Input CSV file --
open CSV, "auau62-ver2.csv" or die "Can't open EEMC QA spreadsheet";

#-- Output file --
open OUT, ">auau62GeVeemcCalib.lis";

#-- Regular expressions which must or must not be 
#-- present in eemc status to accept the run
$eeStatusRequired = "ok";
$eeStatusVeto = "[TM]";

#-- Regular expression used to select trigger
$trigMix = "eemcCalib";

#-- Regular expression used to select detectors
$detectors = "eemc|esmd";

#-- Read in the first line from the spreadsheet (header info)
$line = <CSV>;
@tags = split ',', $line;

#-- Will build a list of runs satisfying the condition 
@runList = ();

#--
$i = 0;
while ( <CSV> ) {

    #-- Break if we're at the end
    goto END if ( /Legend/ );
        
    #-- Skip header 
    next if ( /eeStatus/ );
    
    #-- Skip new fill lines
    next if ( /----/ );
    
    #-- Split the line into an array
    @array = split ",";
	
    #-- Skip if eeStatus should be vetoed --
    next if ( !defined $array[2] );
    next if ( $array[2] =~ /$eeStatusVeto/ );

    #-- Skip if eeStatus does not contain required bits --
    next if ( $array[2] !~ /$eeStatusRequired/ );

    #-- Skip if wrong trigger --
    next if ( !defined $array[6] );
    next if ( $array[6] !~ /$trigMix/ );

    #-- Skip if requested detectors are not present --
    next if ( !defined $array[8] );
    next if ( $array[8] !~ /$detectors/ );
	
    $_ = $array[1];
    s/R//;
    $runList[$i++] = $_;
	
}END:

print "Found $#runList runs with\n";
print "Status: $eeStatusRequired and not $eeStatusVeto\n";
print "Trigger: $trigMix\n";
print "Detectors: $detectors\n\n";
print "Query file catalog\n\n";

#-- Now build a muDst list... could do this more clever using
#-- perl modules for file catalog
@MuDstList = ();

for ( $i = 0; $i <= $#runList; $i++ ) {

    $get_run_list = "get_file_list.pl -keys path,filename -cond production=P04id,storage=NFS,filetype=daq_reco_mudst,runnumber=$runList[$i] -distinct -delim \"/\" ";
    
    open CAT, "$get_run_list|";

    $j = 0;
    while ( <CAT> ) {
	chomp;
	$MuDstList[$i][$j++] = $_;

	print OUT "$_\n";
    }

    $nfiles = $#{ $MuDstList[$i] } + 1;
    print "Run $runList[$i]: Found $nfiles muDst files\n";

    
    
}

