#!/usr/bin/perl -pi~
# $Id: fixgpx.pl,v 1.2 2011/07/10 13:16:58 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.

# Standardize geographical coordinates in a GPX file.
# Usage:
#	fixgpx.pl wpts.gpx	# writes wpts.gpx, creating wpts.gpx~
# or:
#	fixgpx.pl <wpts.gpx >wpts-fixed.gpx

# While reading the input GPX file, look for geographical coordinates
# that were given in the format lat="N12°34.567'" lon="W23°45.678'",
# or lat="N12°34'34''" lon="W23°45'41''", and convert them to valid
# decimal GPX coordinates (lat="12.576116666667" lon="-23.7613").
# Nothing else is changed.

# If we are called with a file name as an argument, editing is done
# in-file, with a backup copy of the input file created with a tilde
# appended to its name.  An alternative is to feed input on stdin and
# redirect output to the new file manually.

use utf8;

# To look for a degree sign or "d", we use [^.0-9] to avoid unicode
# issues.  Up to three characters are possible if a degree sign was
# stored as UTF-8 and a space character follows before the minute
# figure.
while (/(lat|lon)="([NSWE])([0-9]{1,3})[^.0-9]{1,3}([0-9]{2})(\.|' ?)([0-9]{2,})'{0,2}"/) {
    $_ = "$`$1=\"" . (($2 eq 'S' or $2 eq 'W') ? "-" : "") .
	($5 eq "." ? ($3+($4+$6/10**length($6))/60) :
		     ($3+($4+$6/60)/60)) . "\"$'";
}

