#!/usr/bin/perl -w
# NAME: bucket.pl
# AIM: Give a lat lon, show the bucket
# 27/09/2011 geoff mclane http://geoffair.net/mperl
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use Cwd;
my $perl_dir = 'C:\GTools\perl';
unshift(@INC, $perl_dir);
require 'lib_utils.pl' or die "Unable to load 'lib_utils.pl' Check paths in \@INC...\n";
require "Bucket2.pm" or die "Unable to load 'Bucket2.pm'\n";
require 'fg_wsg84.pl' or die "Unable to load 'fg_wsg84.pl'\n";

# log file stuff
our ($LF);
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = $perl_dir."\\temp.$pgmname.txt";
open_log($outfile);

# user variables
my $VERS = "0.0.1 2011-09-14";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $debug_on = 0;
my $def_file = 'def_file';

my ($m_lat,$m_lon);

### program variables
my @warnings = ();
my $cwd = cwd();
my $os = $^O;

sub VERB1() { return $verbosity >= 1; }
sub VERB2() { return $verbosity >= 2; }
sub VERB5() { return $verbosity >= 5; }
sub VERB9() { return $verbosity >= 9; }

sub show_warnings($) {
    my ($val) = @_;
    if (@warnings) {
        prt( "\nGot ".scalar @warnings." WARNINGS...\n" );
        foreach my $itm (@warnings) {
           prt("$itm\n");
        }
        prt("\n");
    } else {
        ### prt( "\nNo warnings issued.\n\n" );
    }
}

sub pgm_exit($$) {
    my ($val,$msg) = @_;
    if (length($msg)) {
        $msg .= "\n" if (!($msg =~ /\n$/));
        prt($msg);
    }
    show_warnings($val);
    close_log($outfile,$load_log);
    exit($val);
}


sub prtw($) {
   my ($tx) = shift;
   $tx =~ s/\n$//;
   prt("$tx\n");
   push(@warnings,$tx);
}

sub process_in_file($) {
    my ($inf) = @_;
    if (! open INF, "<$inf") {
        pgm_exit(1,"ERROR: Unable to open file [$inf]\n"); 
    }
    my @lines = <INF>;
    close INF;
    my $lncnt = scalar @lines;
    prt("Processing $lncnt lines, from [$inf]...\n");
    my ($line,$inc,$lnn);
    $lnn = 0;
    foreach $line (@lines) {
        chomp $line;
        $lnn++;
        if ($line =~ /\s*#\s*include\s+(.+)$/) {
            $inc = $1;
            prt("$lnn: $inc\n");
        }
    }
}

sub set_int_stg($) {
    my ($r) = @_;
    ${$r} = int( ${$r} + 0.5 );
}

sub show_bucket($$) {
   my ($lon,$lat) = @_;
   my ($i,$nb,$i2,$clat,$clon,$plat,$plon,$wid,$hgt,@arr,$az1,$az2,$dist);
   my $bucket = Bucket2->new;
   prt("Using lon=$lon, lat=$lat\n");
   $bucket->set_bucket($lon,$lat);
   prt( "Bucket info: ".$bucket->bucket_info()."\n" );
   prt( "Base path:   ". $bucket->gen_base_path() . " Index " . $bucket->gen_index() ."\n" );
   $clat = $bucket->get_center_lat();
   $clon = $bucket->get_center_lon();
   $wid = $bucket->get_width();
   $hgt = $bucket->get_height();
   prt( "Center:      $clat,$clon, width = $wid, height = $hgt degrees\n");
   if (VERB1()) {
       $clon = 0;
       $clat = 0;
       for ($i = 0; $i < 4; $i++) {
           $plat = $clat;
           $plon = $clon;
           ($clon,$clat) = $bucket->get_corner($i);
           push(@arr, [$clat,$clon,0]);
       }
       for ($i = 0; $i < 4; $i++) {
           if ($i == 0) {
               $i2 = 3;
           } else {
               $i2 = $i - 1;
           }
           $plat = $arr[$i2][0];
           $plon = $arr[$i2][1];
           $clat = $arr[$i][0];
           $clon = $arr[$i][1];
           fg_geo_inverse_wgs_84($plat,$plon,$clat,$clon,\$az1,\$az2,\$dist);
           $arr[$i][2] = $dist;
       }
       prt("Corners:     ");
       for ($i = 0; $i < 4; $i++) {
           $clat = $arr[$i][0];
           $clon = $arr[$i][1];
           $dist = $arr[$i][2];
           prt("$clat,$clon ");
       }
       prt("\n");
       prt("Distances:   ");
       for ($i = 0; $i < 4; $i++) {
           $clat = $arr[$i][0];
           $clon = $arr[$i][1];
           $dist = $arr[$i][2];
           set_int_stg(\$dist);
           $dist /= 1000;
           prt("$dist ");
       }
       prt("Km\n");
   }
   if (VERB2()) {
       my %bn = (
           0=>'BL',
           1=>'BC',
           2=>'BR',
           3=>'CR',
           4=>'TR',
           5=>'TC',
           6=>'TL',
           7=>'CL'
       );
       prt("Adjacent and corner buckets... Start Bottom Left anticlockwise around\n");
       for ($i = 0; $i < 8; $i++) {
           $nb = $bucket->get_next_bucket($i);
           $clat = $nb->get_center_lat();
           $clon = $nb->get_center_lon();
           $wid = $nb->get_width();
           $hgt = $nb->get_height();
           prt(" ".$bn{$i}." ".$nb->gen_index(). " Cent: $clat,$clon. Wid $wid, Hgt $hgt degs.\n");
       }
   }
}

sub process_bucket($$) {
    my ($lat,$lon) = @_;
    show_bucket($lon,$lat);
}

#########################################
### MAIN ###
parse_args(@ARGV);
#prt( "$pgmname: in [$cwd]: Hello, World...\n" );
process_bucket($m_lat,$m_lon);

pgm_exit(0,"");
########################################
sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] [--lat <degs> [--lon <degs>]]\n");
    prt("Options:\n");
    prt(" --help  (-h or -?) = This help, and exit 0.\n");
    prt(" --verb[n]     (-v) = Bump [or set] verbosity. def=$verbosity\n");
    prt(" --lat <degs>       = Set latitude.\n");
    prt(" --lon <degs>       = Set longitude.\n");

}
sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have a following argument!\n") if (!@av);
}

sub parse_args {
    my (@av) = @_;
    my ($arg,$sarg);
    my $cnt = 0;
    while (@av) {
        $arg = $av[0];
        if (($arg =~ /^-/)&& (!($arg =~ /^-(\d|\.)+$/))) {
            $sarg = substr($arg,1);
            $sarg = substr($sarg,1) while ($sarg =~ /^-/);
            if (($sarg =~ /^h/i)||($sarg eq '?')) {
                give_help();
                pgm_exit(0,"Help exit(0)");
            } elsif ($sarg =~ /^v/) {
                if ($sarg =~ /^v.*(\d+)$/) {
                    $verbosity = $1;
                } else {
                    while ($sarg =~ /^v/) {
                        $verbosity++;
                        $sarg = substr($sarg,1);
                    }
                }
                prt("Verbosity = $verbosity\n") if (VERB1());
            } elsif ($sarg eq 'lat') {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $m_lat = $sarg;
                prt("Set lat to $m_lat\n");
                $cnt |= 1;
            } elsif ($sarg eq 'lon') {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $m_lon = $sarg;
                prt("Set lon to $m_lon\n");
                $cnt |= 2;
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            if (!($cnt & 1)) {
                $m_lat = $arg;
                prt("Set lat to $m_lat\n");
                $cnt |= 1;
            } elsif (!($cnt & 2)) {
                $m_lon = $arg;
                prt("Set lon to $m_lon\n");
                $cnt |= 2;
            } else {
                pgm_exit(1,"Already have lat $m_lat, lon $m_lon! What is this [$arg]\n");
            }
        }
        shift @av;
    }


    if (!($cnt & 1)) {
        pgm_exit(1,"ERROR: No lat found in command!\n");
    }
    if (!($cnt & 2)) {
        pgm_exit(1,"ERROR: No lon found in command!\n");
    }
}

# eof - bucket.pl
