#!/usr/bin/perl
#
# ov2wp.pl by Stefan Tomanek <stefan@pico.ruhr.de>
#

use strict;
use DBI();
use IO::File;
use Unicode::String qw(latin1);

sub connect_db {
    my $host = "localhost";
    my $user = "gast";
    my $password = "gast";
    my $database = "geoinfo";
    return DBI->connect("DBI:mysql:database=$database;host=$host", $user, $password, {'RaiseError' => 1});
}

sub insert_wp($$$$$$) {
    my ($db, $name, $lat, $lon, $type, $filename) = @_;
    
    $name =~ s/ /_/g;
    my $uname = latin1($name)->utf8();
    
    my $sth = $db->prepare('DELETE FROM waypoints WHERE lat=? AND lon=? AND type=?');
    
    $sth->execute($lat, $lon, $type);
    $sth->finish();
    
    my $sth2 = $db->prepare( 'INSERT INTO waypoints (name, type, lat, lon, comment) VALUES (?, ?, ?, ?, ?);' );
    $sth2->execute($uname, $type, $lat, $lon, "imported from $filename");
    $sth2->finish();

    #print "$name\n";
}

sub read_waypoints($$) {
    my ($file, $type) = @_;
    my $fh = new IO::File('<'.$file) || die "Unable to open file!";
    my $db = connect_db();
    
    my $name = "";
    my $lat = "";
    my $long = "";
    # We have to look for a 02 Marker, followed by another byte
    my $searching = 2;
    # After that 00 00 00 will appear before every waypoint
    my $waiting = 3;
    # The position in ever record
    my $count = 0;
    
    while( $fh->read($_, 1) ) {
        if ($searching) {
                if ($_ eq "\x02") {
                        $searching--;
                } elsif ($searching == 1) {
                        $searching--;
                }
                next;
        }
        if ($waiting) {
                if ($_ eq "\0") {
                        $waiting--;
                } else {
                        $waiting = 3;
                        $searching = 2;
                }
                next;
        }
        if ($count >= 0 && $count < 3) {
                # erste Koordinate
                $long .= $_;
                $count++;
        } elsif ($count > 3 && $count < 7) {
                $lat .= $_;
                $count++;
        } elsif ($count > 7) {
                $count++;
                if ($_ eq "\0") {
                        print "$name: ";
                        print bytes2dec($lat)."-".bytes2dec($long)."\n";
			insert_wp($db, $name, bytes2dec($lat), bytes2dec($long), $type, $file);
                        $lat = "";
                        $long = "";
                        $name = "";
                        $count = 0;
                        $waiting = 3;
                        $searching = 2;
                } else {
                        $name .= $_;
                }
        } else {
                $count++;
        }
    }
    $fh->close();
    $db->disconnect();
}

sub bytes2dec ($) {
        my ($bytes) = @_;
        my @tokens = unpack("C3", $bytes);
        my $dec = $tokens[0] + $tokens[1]*256 + $tokens[2]*256*256;
        $dec = sprintf("%08d", $dec);
        if ($dec =~ /(0*)(\d+)(\d{5})/) {
                $dec = "$2.$3";
        }
        return $dec;
}

if (defined $ARGV[0] && defined $ARGV[1]) {
    read_waypoints($ARGV[0], $ARGV[1]);
} else {
    print STDERR 'ov2wp.pl by Stefan "tommie" Tomanek <stefan@pico.ruhr.de>'."\n";
    print STDERR "Usage:\n";
    print STDERR "    ov2wp.pl <filename.ov2> <Waypoint type>\n";
}

