#!/usr/bin/perl

print "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
print "<gpx version=\"1.1\" xmlns=\"http://www.topografix.com/GPX/1/1\">\n";
if ($_ = <>) {
	s/[\x00\x0d\x0a]//g;
	@name = split /,/;
	print "<trk>\n";
	print "<trkseg>\n";
	while (<>) {
		s/[\x0d\x0a]//g;
		@data = split /,/;
		%data = ();
		for ($i = 0; $i < @name; $i++) {
			$data[$i] =~ s/^\x00+//;
			$data[$i] =~ s/\x00+$//;
			$data{$name[$i]} = $data[$i];
		}
		$hdop = $data{'HDOP'};
		$vdop = $data{'VDOP'};
		$pdop = $data{'PDOP'};
		if ($hdop =~ /\x00/ || $vdop =~ /\x00/ || $pdop =~ /\x00/) {
			next;
		}
		unless ($hdop =~ /[0-9]+(?:\.[0-9]+)?/ && $hdop > 0) {
			next;
		}
		unless ($vdop =~ /[0-9]+(?:\.[0-9]+)?/ && $vdop > 0) {
			next;
		}
		unless ($pdop =~ /[0-9]+(?:\.[0-9]+)?/ && $pdop > 0) {
			next;
		}
		if ($hdop >= 20 || $vdop >= 20 || $pdop >= 20) {
			next;
		}
		$lat = $data{'LATITUDE N/S'};
		$lat =~ s/^([0-9]+(?:\.[0-9]+)?)N$/$1/;
		$lat =~ s/^([0-9]+(?:\.[0-9]+)?)S$/-$1/;
		$lon = $data{'LONGITUDE E/W'};
		$lon =~ s/^([0-9]+(?:\.[0-9]+)?)E$/$1/;
		$lon =~ s/^([0-9]+(?:\.[0-9]+)?)W$/-$1/;
		print "<trkpt lat=\"$lat\" lon=\"$lon\">";
		$time = $data{'DATE'} . $data{'TIME'};
		if ($time =~ /([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])/) {
			$time = "20$1-$2-$3T$4:$5:$6Z";
			print "<time>$time</time>";
		}
		$ele = $data{'HEIGHT'};
		if ($ele =~ /-?[0-9]+(?:\.[0-9]+)?/) {
			print "<ele>$ele</ele>";
		}
		$course = $data{'HEADING'};
		if ($course =~ /[0-9]+(?:\.[0-9]+)?/) {
			print "<course>$course</course>";
		}
		$speed = $data{'SPEED'};
		if ($speed =~ /[0-9]+(?:\.[0-9]+)?/) {
			$speed = sprintf "%.3f", $speed / 3.6;
			print "<speed>$speed</speed>";
		}
		$fix1 = $data{'FIX MODE'};
		$fix2 = $data{'VALID'};
		if ($fix2 == "DGPS") {
			print "<fix>dgps</fix>";
		} elsif ($fix1 == "2D") {
			print "<fix>2d</fix>";
		} elsif ($fix1 == "3D") {
			print "<fix>3d</fix>";
		}
		print "<hdop>$hdop</hdop>";
		print "<vdop>$vdop</vdop>";
		print "<pdop>$pdop</pdop>";
		print "</trkpt>\n";
	}
	print "</trkseg>\n";
	print "</trk>\n";
}
print "</gpx>\n";
