#!/usr/bin/env perl

## Grid Square calculator

## This file Copyright 2000 <contact@gbppr.org> under the GPL
## NO WARRANTY. Please send bug reports / patches / reports.

%hash = (
0 => A,
1 => B,
2 => C,
3 => D,
4 => E,
5 => F,
6 => G,
7 => H,
8 => I,
9 => J,
10 => K,
11 => L,
12 => M,
13 => N,
14 => O,
15 => P,
16 => Q,
17 => R,
18 => S,
19 => T,
20 => U,
21 => V,
22 => W,
23 => X,
24 => Y,
25 => Z,
);

print "\n\n\t\tGrid Square Calculator\n\n\n";

while (!$latd || $latd > 90 || $latd < 0) {
        print "Enter degrees latitude : ";
        chomp($latd = <STDIN>);
        $latd =~ tr/0-9//csd;
}

print "\n";

while (!$latm || $latm > 60 || $latm < 0) {
        print "Enter minutes latitude (rounded) : ";
        chomp($latm = <STDIN>);
        $latm =~ tr/0-9//csd;
}

print "\n";

while (!$latdir) {
        print "Is that north or south latitude? : ";
        chomp($latdir = <STDIN>);
        $latdir =~ tr/a-z//csd;
}

print "\n";

while (!$longd || $longd > 180 || $longd < 0) {
        print "Enter degrees longitude : ";
        chomp($longd = <STDIN>);
        $longd =~ tr/0-9//csd;
}

print "\n";

while (!$longm || $longm > 60 || $longm < 0) {
        print "Enter minutes longitude (rounded) : ";
        chomp($longm = <STDIN>);
        $longm =~ tr/0-9//csd;
}

print "\n";

while (!$longdir) {
        print "Is that west or east longitude? : ";
        chomp($longdir = <STDIN>);
        $longdir =~ tr/a-z//csd;
}

$latm = $latm / 60;
$longm = $longm / 60;

if ($latdir =~ /^(north|n\w*)/i) {
	$latd = 90 + $latd;
}

elsif ($latdir =~ /^(south|s\w*)/i) {
	$latd = 90 - $latd;
}

if ($longdir =~ /^(west|w\w*)/i) {
	$longd = 180 - $longd;
}

elsif ($longdir =~ /^(east|e\w*)/i) {
	$longd = 180 + $longd
}

($a, $grid3) = split '\.', sprintf("%.1f", ($longd / 20));
($b, $grid4) = split '\.', sprintf("%.1f", ($latd / 10));

print "\n\n\nYour grid square is: $hash{$a}$hash{$b}$grid3$grid4\n\n\n";
