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


#$ENV{'ORACLE_HOME'} = '/home/cdfsoft/products/oracle_client/v9_2_0_1a/Linux+2';
$ENV{'ORACLE_HOME'} = $ENV{'CDFSOFT2_DIR'}.'/../../../products/oracle_client/v9_2_0_1a/Linux+2';
#$ENV{'TNS_ADMIN'} = '/home/cdfsoft/dist/oracle_tnsnames';
$ENV{'TNS_ADMIN'} = $ENV{'CDFSOFT2_DIR'}.'/../../oracle_tnsnames';


use DBI;

# comment to DB
my $dbh = DBI->connect('dbi:Oracle:cdfonprd','cdf_reader','reader') 
    or die "Error connecting $DBI::errstr\n";

open(FIN,$ARGV[0]);
my @files= <FIN>;
close(FIN);

my %bystores  = ();
my %storeLumi = ();

foreach my $f (@files)
{
    chop($f);
    my $run=whichRun($f);
    my ($store, $intLumi) = runToStore($run);
    if ( $store != "" ) {
      # printf("File $f\t\trun $run\t\tstore $store \t\tlumi $intLumi\n");
      $bystores{$store}  .= "$f\n";
      $storeLumi{$store} += $intLumi;
    }
    
}

foreach my $s (keys %bystores)
{
    printf("files_$s.list\n");
    open(FOUT,">files_$s.list");
    printf FOUT "$storeLumi{$s}\n";
    printf FOUT "$bystores{$s}";
    close(FOUT);
}

sub runToStore()
{
    my ($run) = @_;
    
    my $sql = "SELECT DISTINCT RC.TEVSTORE, RC.B0INTEGRATEDLIVELUMI FROM 
	       RUNCONFIGURATIONS RC, RUN_STATUS RS WHERE
	         (RS.RUNNUMBER=? AND RC.RUNNUMBER=RS.RUNNUMBER
		  AND RS.RUNCONTROL_STATUS=1 AND RS.GOODRUN_STATUS=1
		  AND RS.TOF_STATUS=1 AND RS.COT_STATUS=1)";
    
    my $sth = $dbh->prepare($sql);

    $sth->execute($run);
    
    while (my @row = $sth->fetchrow_array)
    {
	return @row;
    }
}


sub whichRun()
{
    my ($fname) = @_;
    my ($hrun) = ($fname =~ /([0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f])\./);

    my $run = hex $hrun;
    return $run;
}
