#!/usr/bin/perl
#
# Author:  Petter Reinholdtsen
# Date:    2005-03-20
# License: GNU Public License v2
#
# Generate GPX data file for the location of all NUUG members, based
# on their address (postal code).
#
# Map from postal code to coordinate is also available from
# <URL: http://www.erikbolstad.no/geo/noreg/postnummer/ >.

use strict;
use warnings;

use vars qw($found $missing);

use Text::CSV_XS;

my %pcode_locations = ();
my $input = "medlemsliste.csv";

my $debug = 0;

$found = 0;
$missing = 0;

pcode_location_load();
gpx_header();
member_load();
gpx_footer();

sub member_load {
  my $csv = Text::CSV_XS->new({
			       'sep_char' => "\t",
			       'eol' => "\015\012",
			       'binary'   => 1
			      });

  open(INPUT, $input) or die "Unable to read $input";
  while (<INPUT>) {
    next if /^CustomerNo/; # Skip header
    next if /^\s*$/; # Skip empty lines
    my $status = $csv->parse($_);
    unless ($status) {
      print "Failed to parse '$_' using '\t' as separator\n";
    } else {
      my @columns = $csv->fields();
      add_member(@columns);
    }
  }
  close(INPUT);
}

sub gpx_header {
  print <<EOF;
<?xml version="1.0"?>
<gpx version="1.0" creator="Cetus TrackLog (Mac OS) 1.32 http://www.CetusGPS.dk"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.cetusgps.dk/gpx/1.0"
        xsi:schemaLocation="http://www.cetusgps.dk/gpx/1.0
        http://www.cetusgps.dk/gpx/1.0/gpx.xsd">
EOF
}

sub gpx_footer {
  print <<EOF;
</gpx>
<!-- $found found, $missing missing -->
EOF
}

sub xmlenc {
  my $s = shift;
  $s =~ s/Ø/OE/;
  $s =~ s/Å/AA/;
  return $s;
}

sub add_member {
  my ($nr, $name, $email, $usenix, $mstatus, $mtlf, $tlf, $mstatusnr,
      $arbno, $arb, $addr1, $addr2, $addr3, $pcode, $ploc) = @_;

  return unless $mstatus; # Only count members

  unless ($pcode) { # No use continuing without a postal code
      $missing++;
      print STDERR "Missing pcode for ",join(" ",@_),"\n";
      return;
  }

  print STDERR "Looking for pcode $pcode\n" if $debug;
  $pcode = sprintf "%04d", $pcode;
  my ($lat, $lon) = pcode_location($pcode);
  if (defined $lat) {
    printf("  <wpt lat=\"%f\" lon=\"%f\">\n", $lat, $lon);
#    print "  <name>$ploc</name>\n";
    printf "  <desc>$pcode %s</desc>\n", xmlenc($ploc);
    print "  </wpt>\n";
    $found++;
  } else {
    print STDERR "Unknown pcode $pcode: ",join(" ",@_),"\n";
    $missing++;
  }
}

sub pcode_location_load {
  my $filename = $ENV{'HOME'} . "/src/perecvs/www/homepage/gis/openstreetmap/pcode-location.txt";
  open(FILE, $filename) or die <<EOF;
Unable to read from $filename.
Fetch it from
<URL:http://developer.skolelinux.no/~pere/gis/openstreetmap/pcode-location.txt>.
EOF
  while (<FILE>) {
    chomp;
    s/\#.+$//;
    next if /^\s*$/;
    my ($pcode, $latitude, $longitude) = split(/\s+/);
    $pcode_locations{$pcode} = [$latitude, $longitude];
  }
  close(FILE);
}

#
# Return (latitude,longitude) for a given pcode
#
sub pcode_location {
  my $pcode = shift;
  return undef if (! exists $pcode_locations{$pcode});

  return @{$pcode_locations{$pcode}};
}
