#!/usr/bin/perl -w

# numsum:  This program adds up all numbers it encounters and prints out
#          the total at the end on STDOUT. 
#   
# Copyright (C) 2002-2003 Suso Banderas

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# You may contact the author at <suso@suso.org>.

#######################
# VARIABLES AND SETUP #
#######################

use Getopt::Std;
use strict;
use vars qw/ %opts /;

my ($file, $finalsum, @number_array, $verbose);

getopts('dhiIqV', \%opts);


if ($opts{'h'}) {
    &help;
    exit(0);
}

if ($opts{'d'}) {
    $verbose = 3;
    print STDERR "Debug mode\n";
} elsif ($opts{'V'}) {
    $verbose = 2;
    print STDERR "Verbose mode\n";
} elsif($opts{'q'}) {
    $verbose = 0;  # No output except the final answer.
} else {
    $verbose = 1;  # Normal output.
}


################
# MAIN PROGRAM #
################

if (@ARGV) {
    foreach $file (@ARGV) {
        print STDERR "Reading from file $file.\n" if ($verbose >= 2);
        open (ARGFILE, "$file") && process_filehandle(\*ARGFILE, \@number_array)
        || $verbose && warn "Couldn't open file $file for reading: $!\n";
        close(ARGFILE);
    }
} else {
    print STDERR "Reading from STDIN.\n" if ($verbose >= 2);
    process_filehandle(\*STDIN, \@number_array);
}

$finalsum = add_array(\@number_array);

if ($opts{'i'}) {
    $finalsum = int($finalsum);
} elsif ($opts{'I'}) {
    if ($finalsum == int($finalsum)) {
        $finalsum = 0;
    } else {
        $finalsum =~ s/^(\-?)[0-9]*\.([0-9]*)$/$1.$2/;
    }
}

print "$finalsum\n";

exit(0);


###############
# SUBROUTINES #
###############

sub help {
	print <<"EOF";
---------------------------------------------------------------------------
numsum :  A program that adds up all numbers of input and returns the sum.
---------------------------------------------------------------------------
Usage:
        numsum [options] <file>   (Input from a file.)
        | numsum [options]        (Input from command pipeline.)
        numsum [options]          (Input on STDIN.  Use Ctrl-D to stop.)

Options:
        -i      Only return the integer portion of the final sum.
        -I      Only return the decimal portion of the final sum

        -d      Debug. For developers only.
        -h      Help: You're looking at it.
        -V      Increase verbosity.
        -q      Quiet mode, don't print any warnings.
EOF
}

# This function is used so that we can genericize what filehandle
# we are getting our information from.
sub process_filehandle {
    my $filehandle = shift;
    my $number_array_ref = shift;

    while (<$filehandle>) {
        if ($_ =~ /^\s*(\-?[0-9]*\.?[0-9]+)/) {
            print STDERR "number: $1\n" if ($verbose >= 3);
            push(@$number_array_ref, $1);
        }
    }
    return 1;
}

# Function for adding up numbers
sub add_array {
    my $arrayref = shift;
    my $runningtotal = 0;
    my $number;

    foreach $number (@$arrayref) {
        print STDERR "$number\n" if ($verbose >= 2);
        $runningtotal += $number;
    }
    return $runningtotal;
}


# Lay down some of that perl pod action.
=pod

=head1 NAME

numsum - numsum program file

=head1 SYNOPSIS

B<numsum> [-iIdhv] <FILE>

| B<numsum> [-iIdhv]   (Input on STDIN from pipeline.)

B<numsum> [-iIdhv]     (Input on STDIN.  Use Ctrl-D to stop.)


=head1 DESCRIPTION

B<numsum> is a program that is part of the numeric utilities package.  B<numsum>
will take all the numbers on stdin and return the sum of those numbers.  Currently
it only processes the first number on each line.  Besides positive numbers, it also
handles negative numbers and numbers with decimals.

=head1 OPTIONS

    -i  Only return the integer portion of the final sum.
    -I  Only return the decimal portion of the final sum.

    -h  Help: You're looking at it.
    -V  Increase verbosity.
    -d  Debug mode.  For developers
    -q  Quiet mode, don't print any warnings.

=head1 EXAMPLES

Simply add up the numbers in a file.
    $ numsum numbers.txt
    4315

Enter your own numbers on STDIN. The last number is the answer.
    $ numsum
    4
    21
    98
    100
    223

Use it in a command pipeline.
    $ ls -1s | numsum
    72288

Add up the total byte count in a http log file.
    $ cat access_log | awk {'print $10'} numsum


=head1 SEE ALSO

average(1), bound(1), interval(1), numgrep(1), numprocess(1), random(1), range(1), round(1)

=head1 COPYRIGHT

numsum is part of the num-utils package, which is copyrighted by
Suso Banderas and released under the GPL license.  Please read
the COPYING and LICENSE files that came with the num-utils package

  Developers can read the GOALS file and contact me about providing
submitions or help for the project.

=head1 MORE INFO

More info on numsum can be found at:

=over 1

=item B<http://suso.suso.org/programs/num-utils/>

=back

=cut

