#!/usr/bin/perl

#
# This piece of crap written by mcr@sandelman.ca.
#
# $Id: gen-geo-pi-v1.pl,v 1.1 2009/12/23 23:01:10 mcr Exp $
#
# See http://www.sandelman.ottawa.on.ca/SSW/ietf/geo-pi/ for updates.
#

print "Please enter your lattitude: ";
chop($lat=<STDIN>);

print "Please enter your longitude: ";
chop($long=<STDIN>);

print "Please enter radius of reference: ";
chop($radius=<STDIN>);

($longdeg, $longmin, $longsec) = split(/ /, $long);
($latdeg, $latmin, $latsec) = split(/ /, $lat);

if($longdeg < 0) {
  $longdeg = 360 - $longdeg;
}

if($latdeg < 0) {
  # south
  $latdeg = -$latdeg;
  $south = 1;
}

$wgs84long = $longdeg + ($longmin / 60) + ($longsec / 360);
$wgs84lat  = $latdeg +  ($latmin / 60)  + ($latsec / 360);
#$wgs84long = ($longdeg * 360) + ($longmin * 60) + $longsec;
#$wgs84lat  = ( $latdeg * 360) + ( $latmin * 60) +  $latsec;

# this is really not good, we blow 32 bits here, but turns out
# that 64 is a common factor, but we still blow 32 bits!
#$wgs84long = int(($wgs84long * (4194304/64)) / (129600/64));
#$wgs84lat  = int(($wgs84lat  * (4194304/64)) / (129600/64));
$wgs84long = int($wgs84long / 0.0000858306884765625);
$wgs84lat  = int($wgs84lat  / 0.0000858306884765625);

# convert to binary
@lat  = &convert_to_binary($wgs84lat);
@long = &convert_to_binary($wgs84long);

print "Raw lat: ",join('', @lat),"\n";
print "Raw long:",join('', @long),"\n";

# need to shift @lat/@long along a bit.
foreach $i (1..10) {
  shift(@lat);
  shift(@long);
}

@geopi=();
foreach $i (1..22) {
  my($a,$b);
  $a = shift(@lat);
  $b = shift(@long);
  push(@geopi, $a);
  push(@geopi, $b);
}

print "Digits ",join('', @geopi),"\n";
print "Lat: $lat Long: $long  -> X";

foreach $i (0..10) {
  @nibble = @geopi[($i*4)..($i*4+3)];
  $nibble = $nibble[0]*8 + $nibble[1]*4 + $nibble[2]*2 + $nibble[3];
  print sprintf("%x", $nibble);
  if($i==2 || $i==6) {
    print ":";
  }
}
print "\n";

exit;

sub convert_to_binary {
  local($num)=@_;
  local($i, @digits);

  @digits=();
  foreach $i (1..32) {
    if($num & 1) {
      unshift(@digits, 1);
    } else {
      unshift(@digits, 0);
    }
    $num = $num >> 1;
  }

  return @digits;
}
    
    


