#!/usr/bin/perl -w
use strict;
use warnings;

use Net::GPSD;
use Getopt::Long;

my $note = '';
GetOptions("note:s"=>\$note);
my $interactive = 1 unless $note;

if( $interactive ){
    print STDERR "Press enter for fix: ";
    scalar(<>);
}

my $g=new Net::GPSD( host => 'localhost' );
my $p=$g->get;
my $dop = getdop($g);

my $fix;
if( $p->status == 2 ){
    $fix = 'dgps';
} elsif( $p->status == 1 && !$p->mode ){
    $fix = '2d';
} else {
    if( $p->mode == 1 ){
	$fix = 'none';
    } elsif( $p->mode == 2 ){
	$fix = '2d';
    } elsif( $p->mode == 3 ){
	$fix = '3d';
    } else {
	warn "No fix value received from gps";
    }
}

if( $interactive ){
    print STDERR "Note: ";
    chomp($note = <>);
}

print '<wpt lat="' . $p->lat . '" lon="' . $p->lon . '">' . "\n";
print '<ele>' . $p->altitude . '</ele>' . "\n" if $p->altitude;
print '<time>' . $p->datetime . '</time>' . "\n";
print '<name>' . $note . '</name>' . "\n";
print '<fix>' . $fix . '</fix>' . "\n";
print '<sat>' . $dop->{sat} . '</sat>' . "\n";
print '<hdop>' . $dop->{hdop} . '</hdop>' . "\n";
print '<vdop>' . $dop->{vdop} . '</vdop>' . "\n";
print '<pdop>' . $dop->{totaldop} . '</pdop>' . "\n";
print '</wpt>' . "\n";

sub getdop {
    my $self = shift;

    my @data = @{ $self->retrieve('Q')->{'Q'} };
    return {
	sat => $data[0],
	spheredop => $data[1],
	hdop => $data[2],
	vdop => $data[3],
	timedop => $data[4],
	totaldop => $data[5],
    };
}
