#!/usr/bin/perl -w

# $Id: pwtrk2gpx.pl,v 1.3 2007/03/10 21:14:51 girlich Exp $

#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

use strict;
use IO::File;
use XML::Writer;
sub pwtrk2gpx($$);

my $pwtrk = shift;
if (!defined $pwtrk) {
	die "No PathAway track given.\n";
}
if (!-r $pwtrk) {
	die "Can't read '$pwtrk': $!\n";
}	
my $gpx = shift;
if (!defined $gpx) {
	$gpx = $pwtrk;
	$gpx =~ s/\.pwtrk$/.gpx/;
	if ($pwtrk eq $gpx) {
		$gpx = $pwtrk . '.gpx';
	}
}
my $temp = 'temp.xml';
pwtrk2gpx($pwtrk,$temp);
my $command = "xmllint --format $temp -o '$gpx'";
my $result = system $command;
if ($result == 0) {
	unlink $temp;
}

sub pwtrk2gpx($$)
{
	my ($pwtrk, $gpx) = @_;

	my $pwtrk_fh = new IO::File $pwtrk, 'r';
	if (!defined $pwtrk_fh) {
		die "Can't open '$pwtrk' for reading: $!\n";
	}
	my $gpx_fh = new IO::File $gpx, 'w';
	if (!defined $gpx_fh) {
		die "Can't open '$gpx' for writing: $!\n";
	}
	my $writer = new XML::Writer(OUTPUT => $gpx_fh);
	$writer->xmlDecl('UTF-8');
	$writer->doctype('gpx');
	$writer->startTag('gpx');
	$writer->startTag('trk');
	$writer->startTag('trkseg');
	while (<$pwtrk_fh>) {
		# 51.36100833,12.34779333,362.20363701,130341.0 17122006,
		/([\-\d\.]+),([\-\d\.]+),([\-\d\.]+),(\d{2})(\d{2})(\d{2}\.\d+)\s+(\d{2})(\d{2})(\d{4}),/;
		my ($lat,$lon,$ele_feet,$hour,$min,$sec,$day,$month,$year)=
		($1,$2,$3,$4,$5,$6,$7,$8,$9);
		my $ele_meter = $ele_feet * 12*0.0254;
		$writer->startTag('trkpt', 'lat'=>$lat, 'lon'=>$lon);
		$writer->dataElement('ele',$ele_meter);
		$sec=int($sec+0.5);
		if ($sec==60) {
			# It would be senseless to implement here the
			# full-blown calendar artithmetic. We prefer an error
			# of 0.5 sec.
			$sec=59;
		}
		$writer->dataElement('time'=>sprintf('%4d-%02d-%02dT%02d:%02d:%02dZ',$year,$month,$day,$hour,$min,$sec),
		);
		$writer->endTag('trkpt');
	}
	$writer->endTag('trkseg');
	$writer->endTag('trk');
	$writer->endTag('gpx');
	$writer->end();
	$pwtrk_fh->close();
	$gpx_fh->close();
}

