#!/bin/perl
# Mark J Cox, June 2006, mark@awe.com
#
# Quick hack to take the log file that mapopolis wrote out (make sure
# you enable full details) and convert it to gpx... it ignores w/e/n/s
# and treats anthing over 500 seconds between readings as a new track, but
# worked nicely with my trip to Nashville and loaded into Google Earth
# straight away.

# example data

#5/29/06  11:48:14 pm N36.13.025 W86.41.771 . 0 mph Alt: 449 ft Mcgavock Pike at Opryland Dr
#5/29/06  11:48:19 pm N36.13.022 W86.41.766 . 0 mph Alt: 423 ft Mcgavock Pike at Opryland Dr
#5/29/06  11:48:26 pm N36.13.022 W86.41.771 W 12 mph Alt: 410 ft Mcgavock Pike at Opryland Dr

use POSIX;
my $track = 1;

print <<EOF;
﻿<?xml version="1.0" encoding="utf-8"?>
<gpx version="1.1" creator="mapopolis2gpx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/1" schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
  <trk>
    <number>$track</number>
    <trkseg>
EOF

$track++;
while(<>) {
    s/\.\ 0\ mph/0 mph/;
    ($d,$t,$pm,$lat,$lon,$dir,$speed,$x,$alt,$alt2) = split(' ');
    $alt = $alt2 if ($alt =~ m/Alt/);

    ($h,$m) = $lat =~ m/\S(\d+).([\d\.]+)/;
    $m = $m/60;
    $lat = $h+$m;

    $lon =~ m/\S(\d+).(\d+).(\d+)/;
    ($h,$m) = $lon =~ m/\S(\d+).([\d\.]+)/;
    $m = $m/60;

    $lon = -($h+$m);

# fix for some data errors on my trip to Nashville
#    next if ($lon < -86.8119);
#    next if ($lon > -86.65);
#    next if ($lat > 36.24);
#    next if ($lat < 36.136);
#    next if ($alt > 1000);

    ($dm, $dd, $dy) = $d =~ m|(\d+)/(\d+)/(\d+)|;
    $date = sprintf("%04d-%02d-%02dT",$dy+2000,$dm,$dd);
    ($hour, $min, $sec) = $t =~ m|(\d+):(\d+):(\d+)|;
    $hour +=12 if ($pm eq "pm");
    $date .= sprintf("%02d:%02d:%02dZ",$hour,$min,$sec);

    my $d2 = mktime($sec,$min,$hour,$dd,$dm-1,$dy+100);

    if ($od2) {
        if ($d2-$od2 > 500) {
            print "</trkseg></trk><trk><number>$track</number><trkseg>\n";
            $track++;
        }
    }
    $od2 = $d2;

    print "<trkpt lat=\"$lat\" lon=\"$lon\"><ele>$alt</ele><time>$date</time></trkpt>\n";
}
print <<EOF;
    </trkseg>
  </trk>
</gpx>
EOF
