#! /usr/bin/perl -w

for $in_name (@ARGV)
{
    open (IN, "< $in_name") || die ("Can't open $in_name: $!\n");

    $_ = <IN>;
    if (!(/\$Glopus/))
    {
	print "Not a glopus file: $!\n";
    }

    $out_name = "pna-" . $in_name;
    $out_name =~ s/\.txt/-00-glopus\.gpx/;
    $out_name =~ s/\_/\-/g;

    print $in_name . " -> " . $out_name . "\n";

    open (OUT, "> $out_name") || die ("Can't open $out_name: $!\n");

    print OUT "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
    print OUT "<gpx version=\"1.0\" creator=\"glopus2gpx.pl - http://www.gurkensalat.com/geostuff/\">\n";
    print OUT "  <time>2006-03-19T12:58:02Z</time>\n";
    print OUT "  <trk>\n";
    print OUT "    <trkseg>\n";

    $date = substr($in_name, 0, 10);

    while (<IN>)
    {
	chomp;
	@foo = split(/\,/);
	# print "  " . $#foo . " - '" . join("', '", @foo) . "'\n";

	if ($#foo == 14)
	{
	    if ($foo[0] eq "\$GPGGA")
	    {
		if (!($foo[2] eq ""))
		{
		    $time = $foo[1];

		    $time = "";
		    $time .= substr($foo[1], 0, 2) . ":";
		    $time .= substr($foo[1], 2, 2) . ":";
		    $time .= substr($foo[1], 4, 2);

		    $lat = $foo[2] / 100;
		    $lat = substr($foo[2], 0, 2);
		    $lat_s = substr($foo[2], 2, 2) . "." . substr($foo[2], 5);
		    $lat = $lat + $lat_s / 60;

		    $lat = -$lat if ($foo[3] eq "S");

		    $lon = substr($foo[4], 0, 3);
		    $lon_s = substr($foo[4], 3, 2) . "." . substr($foo[4], 6);
		    $lon = $lon + $lon_s / 60;

		    $lon = -$lon if ($foo[5] eq "W");

		    $ele = $foo[9];

		    # print "$date $time $lat $lon\n";
		    print OUT "      <trkpt lat=\"" . $lat . "\" lon=\"" . $lon . "\">\n";
		    print OUT "        <time>" . $date . "T" . $time . "Z" . "</time>\n";
		    print OUT "        <ele>" . $ele . "</ele>\n";
		    print OUT "      </trkpt>\n";
		}
	    }
	}
    }

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

    close (OUT);
}
