#!/usr/bin/perl

my $stopped=0;
my $started=0;
my $first=0;
my $last=0;
my $covered=0;
my $count=0;


use strict;
use Time::Local;
use XML::Twig;
my $t=XML::Twig->new( twig_handlers =>
	{ event => \&event }
	);

$|=1;
print "processing " . $ARGV[0];
$t->parsefile($ARGV[0]);
$t->purge();
print "\n";

#print "last : " . $last . " first: " . $first . "s\n";
print "total time: ", $last - $first, " s\n";
print "covered:    " . $covered . " s\n";

sub event
{
	my( $t, $event )= @_;
	my $dt=$event->first_child_text('datetime');
	$count++;
	return if ($dt eq "");
	#if ($count % 100 == 0)  { print "."; }
	$dt =~ /(....)(..)(..)T(..)(..)(..)/ || die "cannot convert $dt at $count";
	(my $year, my $mon, my $d, my $h, my $min, my $s)=($1, $2, $3, $4, $5, $6);
	$dt=timegm($s, $min, $h, $d, $mon-1, $year);
	#print "$dt\n";
	my $loc= $event->first_child('location');
	if (defined($loc)) {
		my $stop=$loc->first_child('stop');
		$last=$dt;
		if ($last < $first) { die "before first at $count"; }
		if (defined($stop) && $started) {
			$stopped=$dt;
			if($started) {
				#print "$started - $dt\n";
				if ($stopped < $started) { die "negative interval at $count"; }
				$covered+=$stopped-$started;
			}
			$started=0;
		} else {
			#print "! $stopped - $dt\n" unless($stopped eq "");
			$first=$dt unless ($first);
			$stopped=0;
			$started=$dt unless ($started);
		}
	}
	$t->purge();
}
