#!/usr/bin/perl
# $Id: txt2gpx.pl,v 1.2 2011/01/23 21:19:32 mas Exp $
# Copyright 2011 Marc André Selig
#
# 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.

# Convert geographical coordinates from a text file to GPX.
# Usage:
#	txt2gpx.pl [-d] [-p prefix]
# -d	Show how we interpret the input file -- output as comments in GPX
# -p	Define a prefix to prepend to waypoint names

# While reading the input text file, look for geographical coordinates
# in the format "N12°34.567' E23°45.678'" (with some leeway for
# whitespaces).  Then output a GPX file with waypoints corresponding
# to these coordinates.  Waypoint names will consist of a prefix, if
# given, and a number.

my $prefix="";
my $debug=0;
use vars qw($opt_d $opt_p);
use Getopt::Std;
getopts("dp:");
if (defined $opt_d) {
    $debug=1;
}
if (defined $opt_p) {
    $prefix=$opt_p . "-";
}

print "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
print "<gpx xmlns=\"http://www.topografix.com/GPX/1/1\" xmlns:groundspeak=\"http://www.groundspeak.com/cache/1/0\" version=\"1.1\" creator=\"txt2gpx.pl by Marc Andre Selig\">\n";
my $count = 0;

use POSIX qw(strftime);

while (<>) {
    if (/([NS]) ?([0-9]{2})° ?([0-9]{2})\.([0-9]{3})[^[0-9A-Z]* ?([WE]) ?([0-9]{2,3})° ?([0-9]{2})\.([0-9]{3})'?/) {
	print "<!-- $1$2°$3.$4' $5$6°$7.$8' -->\n" if $debug;
	print "<wpt lat=\"" . ($1 eq "S" ? -1 : 1)*($2+($3+$4/1000)/60) . "\" ";
	print "lon=\"" . ($5 eq "W" ? -1 : 1)*($6+($7+$8/1000)/60) . "\">";
	print "<name>$prefix$count</name>";
	print strftime("<time>%Y-%m-%dT%H:%M:%SZ</time>", gmtime);
	print "<groundspeak:cache id=\"$count\">";
	print "<groundspeak:name>$prefix$count</groundspeak:name>";
	print "<groundspeak:type>Other</groundspeak:type>";
	print "</groundspeak:cache></wpt>\n";
	$count++;
    } elsif ($debug) {
	chomp; chomp; s///g;
	print "	<!-- $_ -->\n";
    }
}

print "</gpx>\n";

