#!/usr/bin/perl
#
# Author:  Petter Reinholdtsen
# Date:    2006-02-12
# License: GNU General Public License v2 or later
#
# Convert wifi-norway network list into GPX waypoint list

use vars qw($owner, $gpsloc, $essid, $cost);

header();

while (<>) {
    chomp;
    $owner = $1 if /^OWNER:\s+(.+)$/;
    $gpsloc = $1 if /^GPS-LOCATION:\s+(.+)$/;
    $essid = $1 if /^ESSID:\s+(.+)$/;
    $cost = $1 if /^COST:\s+(.+)$/;
    if (/^\s*$/) {
	if ($gpsloc) {
	    print_wpt($owner, $gpsloc, $essid, $cost);
	} else {
	    print STDERR "Missing location for '$owner'\n";
	}
	undef $owner;
	undef $gpsloc;
	undef $essid;
	undef $cost;
    }
}
if ($gpsloc) {
    print_wpt($owner, $gpsloc, $essid, $cost);
}

footer();
sub header {
    print <<EOF;
<?xml version="1.0" encoding="ISO-8859-1" ?>
<gpx version="1.0"
  creator="wifi-norway2gps - http://www.nuug.no/dokumenter/wifi-norway.shtml"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.topografix.com/GPX/1/0"
  xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd">
EOF
}

sub footer {
    print <<EOF;
</gpx>
EOF
}

sub html_escape {
    my $str = shift;
    $str =~ s/&/&amp;/;
    $str =~ s/</&lt;/;
    $str =~ s/>/&gt;/;
    return $str;
}

sub print_wpt {
    my ($owner, $gpsloc, $essid, $cost) = map {html_escape($_)} @_;
    my ($lat, $lon, $acc) = split(/\s+/, $gpsloc);
    print <<EOF;
<wpt lat="$lat" lon="$lon">
  <name>$owner</name>
  <desc>ESSID: $essid, COST: $cost</desc>
</wpt>
EOF
}
