#!/usr/bin/perl
use warnings;
use strict;

print "<?xml version='1.0' encoding='UTF-8'?>\n";
print "<gpx\n";
print "  version='1.0'\n";
print "  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n";
print "  xmlns='http://www.topografix.com/GPX/1/0'\n";
print "  xsi:schemaLocation='http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd'>\n";
print "<trk>\n";
print "<trkseg>\n";

while( my $line = <> ){
    chomp $line;

    next unless $line =~ /O=(.*)/;

    my @data = map {$_ eq '?' ? undef() : $_ } split(/\s+/, $1);
    
    my %data = (
        time => $data[1],
        lat => $data[3],
        lon => $data[4],
        ele => $data[5],
#        horiz_err => $data[6],
#        vert_err => $data[7],
        course => $data[8],
        speed => $data[9]
        );
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime($data{time});
    $data{time} = sprintf('%d-%02d-%02dT%02d:%02d:%02dZ', $year + 1900, $mon, $mday, $hour, $min, $sec);

    print "<trkpt lat='$data{lat}' lon='$data{lon}'>\n";
    delete($data{lat}); delete($data{lon});
    foreach my $key (keys(%data)) {
        print "<$key>$data{$key}</$key>\n" if defined($data{$key});
    }
    print "</trkpt>\n";
}

print "</trkseg>\n";
print "</trk>\n";
print "</gpx>\n";
