#!/usr/bin/perl

use warnings;                             # warn me about the sh.. I wrote
use strict;                               # catch errors as early as possible
use Getopt::Std;                          # helps you to parse the command line
use Data::Dumper;                         # for debugging

# the command line option flags - imported from Getopt::Std module
our ($opt_h);

# get options from the command line
getopts( 'h' );

if ($opt_h)
{
   &showHelp;
   exit( 0 );
}

my $inputFile = shift( @ARGV );


my @fileList;
my $eventSum=0;
my $count=0;

if ($inputFile)
	{
		open( INPUTFILE, "<$inputFile" )
			or die "ERROR: Can not open file: $inputFile\n";

		while (<INPUTFILE>)
			{
				chomp;                  # no newline
				s/#.*//;                # no comments
				s/^\s+//;               # no leading white
				s/\s+$//;               # no trailing white
				next unless length;     # anything left?

				my ($file, $qf, $mg, $events) = split(/\s* /, $_, 4);
        $eventSum += $events;
				$count++;
			}
    print "Number of total events: $eventSum in $count files.\n";
		close ( INPUTFILE );
	}
exit ( 0 );

sub showHelp
{
   print <<"EOF";

	 sumEvents - A tool to sum up the number of events in the files in a textfile generated by SQL script

   -h         : Show the help.
   -v         : Verbose mode.

   The textfile must contain four entries per line:
     the filename,
		 the quality factor, the magnet current
     and the number of events.

   The number of events i sevaluated by this script.
EOF
}