#!/usr/bin/perl
use DateTime;

use warnings;
use strict;

# ./vsrt_log_timeplot.pl /home/superkuh/vsrt_2013.06.14.12.03.00.log > whee2.log
# gnuplot> plot "./whee2.log" using 1:2 title "VSRT Test" with lines

my $data = '/home/superkuh/vsrt_2013.06.13.12.26.47.log';
my $bytelength = 4; 
my $format = "V"; # unsigned 32 bit floats (little endian)
my $num_records;

if ($ARGV[0]) {
	$data = $ARGV[0];
} else {
	print "you need to pass the log file path as an argument.";
	exit;
}

my $dt; # declare datetime variable globally
extracttime($data); # $dt now has date object.


open(LOG,"$data") or die "Can't open log.\n$!";
binmode(LOG);

my $i = 0;
until ( eof(LOG) ) {
	my $record;
	my $decimal;
	read(LOG, $record, $bytelength) == $bytelength
		or die "short read\n";

	$decimal = unpack($format, $record);

	# This is a stupid/fragile way to deal with datetime
	# not having enough precision. It only works if the
	# record to record interval is always 0.5 seconds.
	my $recordtime = $dt->epoch();
	if (0 == $i % 2) {
		printf("$recordtime.0,\t$decimal\n", $decimal);
	} else {
		printf("$recordtime.5,\t$decimal\n", $decimal);
	}

	$dt->add( nanoseconds => 500000000 );
	$i++;
}


sub extracttime {
	my $timestring = shift;
	# /home/superkuh/vsrt_2013.06.13.12.26.47.log
	$timestring =~ /(\d{4}\.\d{2}\.\d{2})\.(\d\d\.\d\d\.\d\d)/;
	my $year_month_day = $1;
	my $time = $2;

	my ($year,$month,$day) = split(/\./, $year_month_day);
	$time =~ s/\./:/g;
	my ($hour,$minute,$second) = split(/:/, $time);

	$dt = DateTime->new(
		year       => $year,
		month      => $month,
		day        => $day,
		hour       => $hour,
		minute     => $minute,
		second     => $second,
		time_zone  => 'America/Chicago',
	);

	$dt->set_time_zone('UTC');
	return 1;	
}


