#!/usr/bin/perl -w
#
# plots GPS data on a map file
#
# usage: plot-gps.pl <map-info-file> <gps-data-file-1> [...]

use Image::Magick;

# plots one file, given as the first argument
sub plot_file {
    my $fname=$_[0];
    my @fields;
    my ($lon, $lat);
    my ($lx, $ly, $x, $y, $c);
    my $valid;
    
    if(!open(G, $fname)) {
        die "Unable to open file $fname\n";
    }
    $lx = -1;
    $ly = -1;
    $c = 0;
    while(!eof(G)) {
        $line = <G>;
        $c++;
        if($c % 100 == 1) {
            # a simple progress indicator;)
            print "Plotting line $c.\n";
        }
        chomp $line;
        @fields = split(";",$line);
        $lon = $fields[1];   # longitude
        $lat = $fields[2];   # latitude
        $valid = $fields[3]; # validity flag
        if($valid == 0) {
            # we don't care about invalid entries
            next;
        }
        $x = ($lon - $minlon)/$dx;
        $y = $h - ($lat - $minlat)/$dy;
        if(($lx != -1) && ($lx != -1) && (($lx != $x) || ($ly != $y))) {
            # only draw the line if the position has changed since
            # the last time for at least one pixel in any direction
            $img->Draw(stroke=>"red", primitive=>"line",
                       points=>"$lx,$ly $x,$y");
        }
        $lx = $x;
        $ly = $y;
    }
    close(G);
}

my $dataf = $ARGV[0];
my $mapf;
my $plotf;

($mapf = $dataf) =~ s/.txt/.png/;        # original map image file
($plotf = $dataf) =~ s/.txt/-plot.png/;  # map image with plotted course

# open the map info file
if( !open(F, $dataf) ) {
    die "Unable to open data file $dataf.\n";
}

my $line;
my @params;

# read map info
# max and min longitude
$line = <F>;
chomp $line;
@params = split(",", $line);
$maxlon = $params[0];
$minlon = $params[1];
# max and min latitude
$line = <F>;
chomp $line;
@params = split(",", $line);
$maxlat = $params[0];
$minlat = $params[1];
# image width and height
$line = <F>;
chomp $line;
@params = split(",", $line);
$w = $params[0];
$h = $params[1];

# calculate longitude and latitude delta in x and y directions, respectively
$dx = ($maxlon - $minlon)/$w;
$dy = ($maxlat - $minlat)/$h;

$img = Image::Magick->new;
# if an old plot file exists, open that one - allows for incremental
# plots
if( -e $plotf ) {
    $img->ReadImage($plotf);
}
# otherwise open the original map file
else {
    $img->ReadImage($mapf);
}
# for each next command line parameter, plot it
for($i = 1; $i < @ARGV; $i++) {
    print "Plotting $ARGV[$i]\n";
    plot_file($ARGV[$i]);
}
# and finally write the plotted image
$img->WriteImage($plotf);
