#!/usr/bin/perl
# The Missing Textutils, Ondrej Bojar, obo@cuni.cz
# http://www.cuni.cz/~obo/textutils
#
# 'hoursum' expects every input line to be in the format
# "any-prefix-followed-by-a-colon: hour.min-hour.min hour.min-hour.min"
#
# All the given time intervals are summed and the total number of hours and
# minutes spent on the project is appended.
#
# $Id: hoursum,v 1.5 2013-02-12 12:58:02 bojar Exp $

my $verbose = 0;

while (<>) {
  print;
  chomp;
  ($date, $times) = split /\s*:\s*/, $_, 2;
  foreach $pair (split /\s+/, $times) {
    ($from, $to) = split /-/, $pair;
    if (!$from || !$to) {
      print STDERR "# Skipping unpaired $pair\n";
    } else {
      ($fromh, $fromm) = split /[:.]/, $from;
      ($toh, $tom) = split /[:.]/, $to;
      if ($toh < $fromh) {
        # Assuming overnight!
	$toh += 24;
      }
      if ($tom < $fromm) {
        $tom += 60;
	$toh -= 1;
      }
      $len = ($toh - $fromh) * 60 + ($tom - $fromm);
      $total += $len;
      print STDERR "$pair ---> $len\n" if $verbose;
    }
  }
}
$toth = int($total / 60);
$totm = $total - $toth*60;
printf "Total %i.%02i\n", $toth,$totm;
