#! /usr/bin/perl
use strict;
use warnings;
use Getopt::Std;

my %options;
getopts ( 'x:y:vh', \%options );

if ( defined $options{'h'} )
{
    print STDERR <<EOHELP;
Trapeze integration of 2 columns of numbers from a space-separated input stream.
Options:
 -h           : This text.
 -x <integer> ; Column index of x-values (indexed from 1=leftmost).
 -y <integer> : Column index of y-values (indexed from 1=leftmost).
 -v           : Output a running total for each step. 
EOHELP
    exit(0);
}

my $xcol = 0;
if ( defined $options{'x'} ) { $xcol = $options{'x'}-1; }
my $ycol = 0;
if ( defined $options{'y'} ) { $ycol = $options{'y'}-1; }

my @columns = split ( /[\s]+/, <> ); 
my $x = $columns[$xcol];
my $y = $columns[$ycol];

my $x1; my $y1; my $dx; my $dy; my $trapeze;
my $integral = 0.0;

while ( <> )
{
    chomp;
    @columns = split ( /[\s]+/, $_ );
    $x1 = $columns[$xcol];
    $y1 = $columns[$ycol];
    $dx = $x1-$x;
    $trapeze = 0.5 * $dx * ($y + $y1);
    $integral += $trapeze;
    $x = $x1;
    $y = $y1;
    if ( defined $options{'v'} )
    {
        print "($x1, $y1), $integral\n";
    }
}
print "$integral\n";
