#!/usr/bin/perl



sub print_help {
    print "sum_root v0.4 (Author: Nikita Ermakov, E-Mail: coffe92\@gmail.com)";
    print "\nExample of usage:\n\tperl sum_root.pl --path PATH --basename BASE_NAME --max MAX_FILES --comp COMPRESSION";
    print "\nOptions:";
    print "\n\t--path (-p)\tpath to the list of root files to merge (.list)";
    print "\n\t--basename (-bn)\tpart of the temp files name (default: tmp)\n";
    print "\n\t--max (-m)\tmaximum files to read (default: 10)\n";
    print "\n\t--comp (-c)\tcompression level (default: 9)\n";
}

my $comp = 9;      # compression of the input files
my $maxFiles = 10; # maximum files to merge


sub sum_files {
    my $files = @_[0];
    my $baseName = @_[1];
    my $iter = @_[2];
    my $filesNum = $#files + 1;
    my $outFile;
    my $listAdd;
    my $list;
    my $counter = 0;
    
    $#list = -1;

    for (my $i = 1; $i <= $filesNum + 1; $i++) {
	if ((($i % ($maxFiles + 1)) == 0) || ($i == $filesNum + 1)) {
	    if ($#listAdd != -1) {
		$outFile = $baseName."_".$iter."_".$counter.".root";
		push(@list, $outFile);
		system("hadd $outFile ".join(" ", @listAdd));
		print $listAdd."\n";
		$counter++;
		if ($iter > 0) {
		    system("rm ".join(" ", @listAdd));
		}
		$#listAdd = -1;
		
	    }
	} 
	push(@listAdd, $files[$i - 1]);
    }

    return @list;
}

###############
#             #
# ENTRY POINT #
#             #
###############

# Get and check arguments number
my $argNum = $#ARGV + 1;

if ($argNum == 0) {
    print_help();
    exit 0;
}

my $path = "";
my $baseName = "";

for (my $i = 0; $i < $argNum; $i++) {
    # Searching path argument
    if (($ARGV[$i] eq "--path") || 
	($ARGV[$i] eq "-p")) {
	if (++$i < $argNum) {
	    print "Using list file: ".$ARGV[$i]."\n";
	    $path = $ARGV[$i];
	}
    }

    # Searching basename argument
    if (($ARGV[$i] eq "--basename") ||
	($ARGV[$i] eq "-bn")) {
	if (++$i < $argNum) {
	    print "Using basename for temporary files: ".$ARGV[$i]."\n";
	    $baseName = $ARGV[$i];
	}
    }

    # Searching max files argument
    if (($ARGV[$i] eq "--max") ||
	($ARGV[$i] eq "-m")) {
	if (++$i < $argNum) {
	    print "Max files set to: ".$ARGV[$i]."\n";
	    $maxFiles = $ARGV[$i];
	}	
    }
    
    # Searching max files argument
    if (($ARGV[$i] eq "--comp") ||
	($ARGV[$i] eq "-c")) {
	if (++$i < $argNum) {
	    print "Compression set to: ".$ARGV[$i]."\n";
	    $comp = $ARGV[$i];
	}	
    }    
}

if ($path eq "") {
    print "Please sepcify path to the list file\n";
    print_help();
    exit 0;
}

if ($baseName eq "") {
    $baseName = "tmp";
    print "Warning: using default basename for temporary files: tmp\n";
}

my $files;

open(my $fd, $path) 
    or die "Could not open file '$path' $!";

# Create array with list of input files
while (my $row = <$fd>) {
    chomp $row;
    push (@files, $row);
}

close($fd);

my $iter = 0;
while ($#files > 0) {
    @files = sum_files($files, $baseName, $iter++);
}

print "Output file name: $files[0]\n";

exit 0;
