#! /usr/bin/perl -w

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

    $_ = <IN>;


    $out_name = "pna-" . substr($in_name, 5, 4) . "-" . substr($in_name, 9, 2) . "-" . substr($in_name, 11, 2);
    $out_name .= "-" . substr($in_name, 14, 2) . "-" . substr($in_name, 16, 2) . "-" . substr($in_name, 18);
    # $out_name = $in_name;
    $out_name =~ s/^track/pna-/;
    $out_name =~ s/\.trk/-gopal\.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=\"gopal2gpx.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, 5, 4) . "-" . substr($in_name, 9, 2) . "-" . substr($in_name, 11, 2);

    $old_lon = "";
    $old_lat = "";

    while (<IN>)
    {
	chomp;
	@foo = split(/\,\ /);
	# my ($date,$time,$lon,$lat,$alt,$speed,$test1,$test2,$test3) = split(/\s*,\s*/,$line);
	# print "  " . $#foo . " - '" . join("', '", @foo) . "'\n";

	if ($#foo == 8)
	{
	    if (!($foo[2] eq "0.000000"))
	    {
		$time = $foo[1];

		#  0    1    2     3     4    5     6     7     8
		# ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
		# 8 - '10', '59', '6', '2', '0', '70', '5', '1', '0'
		# @gaga = gmtime($time);
		# print "  " . $#gaga . " - '" . join("', '", @gaga) . "'\n";

		# ($sec, $min, $hour, $mday, $mon, $year) = gmtime($time);
		# $date = $year . "-" . $mon . "-" . $mday;
		# $time =  $hour . ":" . $min . ":" . $sec;

		# <time>2007-06-07T14:39:32Z</time>

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

		$lon = $foo[2];

		$lat = $foo[3];

		$ele = $foo[4];

		if (!(($lat eq $old_lat) && ($lon eq $old_lon)))
		{
		    # 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";

		    $old_lat = $lat;
		    $old_lon = $lon;
		}
	    }
	}
    }

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

    close (OUT);
}
