#!/usr/bin/perl

## Set up our initial variables
$inputFile = $ARGV[0];
$outputFile = $inputFile . ".cnv";
$first = "yes";

## Open our input and output files
open (INFILE, "< $inputFile") or die "Cannot read $inputFile";
open (OUTFILE, "> $outputFile") or die "Cannot write $outputFile";

## For each line in the file...
while ($line = <INFILE>) {

	## Strip out newlines and comment lines
	$line =~ s/\n//;
	$line =~ s/#.*//;

	# Split our line into two data points
	#
	# The first bit is the control data point (i.e. what time it really was
	# when the data point was taken)
	# 
	# The second bit is what time the watch thought it was at the same time
	@bits = split(/\s/,$line);	

	## Only process interesting data
	if ($line) { 

		#
		# We'll be plotting change in seconds per day, so...
		#
		# Take the first bit of data, turn it into a number of seconds.
		# Then divide by number of seconds per day to get a day
		# 
		# Take the second bit of data and turn it into a number of seconds
		# difference from the first bit of data, to get change in seconds.
		#
		# Output this data to a line on the new file for gnuplot
		#
		print OUTFILE (bit2sec($bits[0])/(24*3600)) . "\t" . (bit2sec($bits[1])-bit2sec($bits[0])) . "\n";
	}
}

# Take one of our data points (looks like: 2/14:55:23) and turn it into a
# number of seconds
sub bit2sec
{
	$bit = shift (@_);
	@units = split(/[\/:]/, $bit);
	$seconds = $units[0]*24*3600 + $units[1]*3600 + $units[2]*60 + $units[3];

	# Take the first data point and subtract the others from it
	# 
	# The first datapoint in a set of data is always midnight, so the rest of
	# the data points will be displayed relative to the first (this makes the
	# graph line up nicely)
	if ($first eq "yes") {
		$first = "no";
		$initial = $seconds;
	}
	return ($seconds - $initial);
}
