#!/usr/bin/perl -w
#
#NAME
#  SumTimes - Read columns of times and sum them.
#
#SYNOPSIS
#  SumTimes [file]..
#
#DESCRIPTION
#  This is a bit of a kludge, to  read  simple  time  summaries,  and
#  calculate the total of the hours and minutes.  The only trickiness
#  is the fact that adding and  subtracting  times  in  hh:mm  format
#  isn't a natural act in perl or any other language that I know of.
#
#  The  line  formats  are also kludges, to handle whatever files I'm
#  currently dealing with.  More line formats will appear with time.
#
#RETURNS
#  The exit status is 0 if no anomalies are found in the data.
#  1 means there was an arithmetic error in the input.
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#
#BUGS
#  At present, this only handled hours and minutes.
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

$exitstat = 0;
$total = '0:00';

for $line (<>) {
	chomp $line;
	if (($t1,$t2,$t3) =
			($line =~ /^(\d\d:\d\d)[- ](\d\d:\d\d)\s+(\d+:\d\d)$/)) {
		$tim = &tsub($t2,$t1);
		if ($tim ne $t3) {
			print "### Wrong: $tim\n";
			$exitstat = 1;
		}
		$total = &tsum($total,$3);
		print "$line T=$total\n";
	} elsif (($t1,$t2) =
			($line =~ /^(\d\d:\d\d)[- ](\d\d:\d\d)\s*$/)) {
		$tim = $t3 = &tsub($t2,$t1);
		$total = &tsum($total,$tim);
		print "$line $tim T=$total\n";
	} else {
		print "$line\n";
	}
}
print "\nTotal hours: $total\n";
exit $exitstat;

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
sub tsum {
	local($v1,$v2) = @_;
	local($h1,$m1) = split(/:/,$v1);
	local($h2,$m2) = split(/:/,$v2);
	local($ht) = $h1 + $h2;
	local($mt) = $m1 + $m2;
	while ($mt > 59) {$ht ++; $mt -= 60}
	return sprintf("%d:%02d",$ht,$mt);
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
sub tsub {
	local($v1,$v2) = @_;
	local($h1,$m1) = split(/:/,$v1);
	local($h2,$m2) = split(/:/,$v2);
	local($ht) = $h1 - $h2;
	local($mt) = $m1 - $m2;
	while ($mt < 0) {$ht --; $mt += 60}
	return sprintf("%d:%02d",$ht,$mt);
}
