#!/usr/bin/perl -w

#
# dbrowaccumulate
# Copyright (C) 1991-1998 by John Heidemann <johnh@isi.edu>
# $Id: dbrowaccumulate,v 1.9 1999/11/23 02:04:29 johnh Exp $
#
# This program is distributed under terms of the GNU general
# public license, version 2.  See the file COPYING
# in $dblibdir for details.
#

sub usage {
    print STDERR <<END;
usage: $0 [-C increment_constant] [-c increment_column] 

	Compute a running sum over a column of data
	to graph a cumulative distribution.
	What to accumulate is specified by -c or -C.

Sample input:
#h      diff
0.0
00.000938
00.001611
00.001736
00.002006
00.002049
#  | /home/johnh/BIN/DB/dbrow 
#  | /home/johnh/BIN/DB/dbcol diff
#  | dbsort diff

Command:
cat DATA/kitrace.jdb | dbrowaccumulate diff

Sample output:
#h      diff    accum
0.0     0
00.000938       .000938
00.001611       .002549
00.001736       .004285
00.002006       .006291
00.002049       .00834
#  | /home/johnh/BIN/DB/dbrow 
#  | /home/johnh/BIN/DB/dbcol diff
#  | dbsort diff
#  | /home/johnh/BIN/DB/dbrowaccumulate diff


END
    exit 1;
}

BEGIN {
    $dblibdir = "/usr/local/lib/jdb";
    push(@INC, $dblibdir);
}
require "$dblibdir/dblib.pl";
use DbGetopt;

use strict;
no strict 'vars';


my(@orig_argv) = @ARGV;
my($prog) = &progname;

my($inc_code) = '';
my($incc) = '';
my($debug) = undef;
my($dbopts) = new DbGetopt("C:c:d?", \@ARGV);
my($ch);
while ($dbopts->getopt) {
    $ch = $dbopts->opt;
    if ($ch eq 'C') {
	$inc_code = $dbopts->optarg;
    } elsif ($ch eq 'c') {
	$incc = $dbopts->optarg;
    } elsif ($ch eq 'd') {
	$debug = 1;
    } else {
	&usage;
    };
};


&usage if ($#ARGV > 0);

&readprocess_header;

if ($inc_code eq '') {
    # what col to inc with?
    die "$prog: neither -C nor -c specified.\n"
	if ($incc eq '');
    die ("$prog: unknown column ``$incc''.\n") if (!defined($colnametonum{$incc}));
    $incc = $colnametonum{$incc};
    $inc_code = '$f[' . $incc . ']';
};



my($accum) = 0;
my($accum_f) = &col_create('accum');
my($code) = "\$accum += $inc_code;\n\$f[$accum_f] = \$accum;\n";

if ($debug) {
    print $code;
    exit 1;
};

&write_header();

my($loop) = q[
    while (<STDIN>) {
        &pass_comments && next;
        &split_cols;
] . $code . q[
        &write_cols;
    };
];
eval $loop;
$@ && die "$prog: interal eval error: $@.\n";

print "#  | $prog " . join(" ", @orig_argv) . "\n";
exit 0;

if (0) {
    my $x;
    $x = $accum = $code;
}
