#!/usr/bin/perl -w
# NAME: 
# AIM:
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use Math::trig;
use Cwd;
my $os = $^O;
my $perl_dir = '/home/geoff/bin';
my $PATH_SEP = '/';
my $temp_dir = '/tmp';
if ($os =~ /win/i) {
    $perl_dir = 'C:\GTools\perl';
    $temp_dir = $perl_dir;
    $PATH_SEP = "\\";
}
unshift(@INC, $perl_dir);
require 'lib_utils.pl' or die "Unable to load 'lib_utils.pl' Check paths in \@INC...\n";
# log file stuff
our ($LF);
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = $temp_dir.$PATH_SEP."temp.$pgmname.txt";
open_log($outfile);

# user variables
my $VERS = "0.0.2 2014-01-13";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $out_file = '';

# ### DEBUG ###
my $debug_on = 0;
my $def_file = 'def_file';

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

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" ) if (VERB9());
    }
}

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 log10($) {
    my $n = shift;
    return log($n)/log(10);
}

sub do_test2() {
    my ($i,$l,$cnt,$min,$max,$val);
    $cnt = 0;
    my $max_max = 9000;
    my $step = $max_max / 20;
    my $inc = 9 / 20;
    for ($i = 1; $i <= 10; $i += $inc) {
        $cnt++;
        $val = 10 - $i;
        $l = log10($val);
        $min = int($max_max - ($cnt * $step * $l));
        $max = int($min + ($step * $l));
        #prt("$cnt: log10($val) = $l - min $min max $max\n");
        prt("$cnt: min $min max $max - log10($val) = $l\n");
    }

}

sub do_test() {
    my ($i,$val,$l,$cnt,$num);
    my ($last,$diff,$min,$max,$next,$prev);
    my $inc = 9 / 20;
    $cnt = 0;
    $last = 0;
    my $max_max = 9000;
    $next = $max_max;
    my $step = $max_max / 20;
    $prev = 0;
    for ($i = 1; $i < 10; $i += $inc) {
        $cnt++;
        $val = $i;
        $l = log10($val);
        $num = int($l * $max_max);
        $diff = $num - $last;
        $next -= $diff;
        #prt("$cnt $num $diff $next - log10($val) = $l\n");
        prt(sprintf("%2d %4d %4d %4d %4d",$cnt, $num, $diff, $next, $prev)." - log10($val) = $l\n");
        $last = $num;
        $prev = $next
    }

}

sub do_test3() {
    my $xdim = 1 / 1200;
    my $ydim = 1 / 1200;
    my $secs = $xdim * 3600;
    prt("HGT files cover 1x1 degree so N40E001 ranges 40-41N and 1-2E\n");
    prt("They have 1021 rows and columns, so that is an XDIM/YDIM of $xdim, $secs sec\n");
    my $blat = 40;
    my $blon = 1;
    my $max_lat = 40;
    my $max_lon = 1;
    my ($x,$y,$lat,$lon,$cnt);
    $cnt = 0;
    for ($y = 1200; $y >= 0; $y--) {
        for ($x = 0; $x < 1201; $x++) {
            if (($cnt % 5000) == 0) {
                $lat = $blat + ((1200 - $y) * $ydim);
                $lon = $blon + ($x * $xdim);
                prt("$cnt: x,y $x,$y = lon,lat $lon,$lat\n");
                $max_lat = $lat if ($lat > $max_lat);
                $max_lon = $lon if ($lon > $max_lon);
            }
            $cnt++;
        }
    }
    prt("max lon $max_lon, max lat $max_lat\n");
    prt("They have 1021 rows and columns, so that is an XDIM/YDIM of $xdim, $secs sec\n");
}

# GTOPO ranges
#// A - min. X : -180.0, max. X : -90.0, min. Y : 50.0, max. Y : 90.0
#// B - min. X :  -90.0, max. X :   0.0, min. Y : 50.0, max. Y : 90.0
#// C - min. X :    0.0, max. X :  90.0, min. Y : 50.0, max. Y : 90.0
#// D - min. X :   90.0, max. X : 180.0, min. Y : 50.0, max. Y : 90.0
#// E - min. X : -180.0, max. X : -90.0, min. Y :  0.0, max. Y : 50.0
#// F - min. X :  -90.0, max. X :   0.0, min. Y :  0.0, max. Y : 50.0
#// G - min. X :    0.0, max. X :  90.0, min. Y :  0.0, max. Y : 50.0
#// H - min. X :   90.0, max. X : 180.0, min. Y :  0.0, max. Y : 50.0
#// I - min. X : -180.0, max. X : -90.0, min. Y :-50.0, max. Y :  0.0
#// J - min. X :  -90.0, max. X :   0.0, min. Y :-50.0, max. Y :  0.0
#// K - min. X :    0.0, max. X :  90.0, min. Y :-50.0, max. Y :  0.0
#// L - min. X :   90.0, max. X : 180.0, min. Y :-50.0, max. Y :  0.0
#// M - min. X : -180.0, max. X : -90.0, min. Y :-90.0, max. Y :-50.0
#// N - min. X :  -90.0, max. X :   0.0, min. Y :-90.0, max. Y :-50.0
#// O - min. X :    0.0, max. X :  90.0, min. Y :-90.0, max. Y :-50.0
#// P - min. X :   90.0, max. X : 180.0, min. Y :-90.0, max. Y :-50.0

sub do_test4() {
    my $GTOPO_COLS = 10800;
    my $GTOPO_PROWS = 4800; # polar rows
    my $GTOPO_EROWS = 6000; # equitorial rows
    my $GTOPO_XDIM = 0.00833333;
    my $GTOPO_YDIM = 0.00833333;
    my $GTOPO_NODATA = -500;
    my $GTOPO_PSIZE = ($GTOPO_COLS * $GTOPO_PROWS * 2);
    my $GTOPO_ESIZE = ($GTOPO_COLS * $GTOPO_EROWS * 2);
    my $xdim = 90 / $GTOPO_COLS;
    #// G - min. X :    0.0, max. X :  90.0, min. Y :  0.0, max. Y : 50.0
    my $ydim = 50 / $GTOPO_EROWS; 
    my $minX = 0.0;
    my $maxX = 90.0;
    my $minY = 0.0;
    my $maxY = 50.0;
    my $lat = 40.0;
    my $lon = 35.0;
    # convert lat,lon to an x,y
    my $alat = $lat - $minY;
    my $alon = $lon - $minX;
    my $col = int($alon / $xdim);
    my $row = int($alat / $ydim);
    my $x = $GTOPO_COLS - $col;
    my $y = $GTOPO_EROWS - $row;
    prt("GTOPO files 50 or 40 X 90 degrees. XDIM $GTOPO_XDIM ($xdim/$ydim)\n");
    prt("lat,lon $lat,$lon = x,y $x,$y, col,row $col,$row\n");

}

# The grid spans 0 to 360 in longitude and -90 to 90 in latitude. 
# The upper left corner of the upper left grid cell has latitude 90 and longitude 0.
# There are 43200 columns and 21600 rows.
# Mt Ever - 27.983333, 86.925000 =   8685 - y,x 7442,10431
# Deepest - 11.375000,142.425000 = -10910 - y,x 9435,17091

# lon = 180.0 - (180.0 - (x * xdim)); // of 360
# lon + (180.0 - (x * xdim)) = 180;
# 180 - (x * xdim) = 180 - lon;
# 180 = 180 - lon + (x * xdim);
# 180 + lon = 180 + (x * xdim);
# lon = (x * xdim);
# lon / xdim = x;

# lat =  90.0 - (y * ydim); // of 180
# (y * ydim) = 90 - lat;
# y = (90 - lat) / ydim;

# SRTM30 with a 30 arc second (about 928 meters) sample distance.

sub do_test5() {
    my $cols = 43200;
    my $rows = 21600;
    my $xspan = 360;
    my $yspan = 180;
    my $xdim = $xspan / $cols;
    my $ydim = $yspan / $rows;
    my $xsecs = $xdim * 3600;
    my $ysecs = $ydim * 3600;
    prt("Rows $rows, Cols $cols, XDIM $xdim, YDIM $ydim, x-secs $xsecs, y-secs $ysecs\n");
    my $x = 10431;
    my $lon = ($x * $xdim);
    my $x2 = ($lon / $xdim);
    my $y = 7442;
    my $lat = 90 - ($y * $ydim);
    my $y2 = (90 - $lat) / $ydim;
    my ($msg);
    prt("Offset x $x = lon $lon = x2 $x2 - y $y = lat $lat = y2 $y2\n");
    for ($y = 0; $y < $rows; $y += 1000) {
        for ($x = 0; $x < $cols; $x += 1000) {
            $lon = ($x * $xdim);
            $x2 = int($lon / $xdim);
            if ($lon > 180) {
                $lon -= 360;
            }
            $lat = 90 - ($y * $ydim);
            $y2 = int((90 - $lat) / $ydim);
            $msg = "Offset x $x = lon $lon = x2 $x2 - y $y = lat $lat = y2 $y2 ";
            if (($x == $x2)&&($y == $y2)) {
                $msg .= "ok";
            } else {
                if (($x != $x2)&&($y != $y2)) {
                    $msg .= "CHECK BOTH!";
                } elsif ($x != $x2) {
                    $msg .= "CHECK X!";
                } else {
                    $msg .= "CHECK Y!";
                }
            }
            #prt("$msg\n");
        }
    }
    my $s2 = 57600000;  # 40 degs lon x 50 degs lat
    my $s1 = 51840000;  # 60 degs lon x 30 degs lat
    # 	x = 7200 ;
    #	y = 3600 ;

    my $cc1 = 4800;
    my $cc2 = 4320;
    my $mcols = int(40 / $xdim);
    my $mrows = int(50 / $ydim);
    my $mcolS = int(60 / $xdim);
    my $mrowS = int(30 / $ydim);
    #$mcolS = 7200;
    #$mrowS = 3600;
    my $tot = $mcols * $mrows * 2;

    my $tot2 = $mrowS * $mrowS * 2 * 2; # ????????????????????????
    prt("Cols $mcols x Rows $mrows = Total $tot\n");
    prt("Cols $mcolS x Rows $mrowS = Total $tot2\n");
    my $sz = $s1 / 2;
    prt("But sz2 = $s1, rows x cols $sz\n");
    #$load_log = 1;
}


sub do_test6() {
    my $lon = -118.292;
    my $ilon = 117;
    my $res = 1 + ($ilon + 1) + $lon;
    my $nxt = $lon + 1;
    my ($i,$nlon);
    #prt("lon $lon, ilon $ilon res $res nxt $nxt\n");
    $nlon = -119;
    prt("lon $nlon ");
    for ($i = 0; $i < 5; $i++) {
        $nlon += 0.25;
        prt("$nlon ");
    }
    prt("\n");
    #prt("lon $lon ");
    #$nlon = $lon;
    #for ($i = 0; $i < 5; $i++) {
    #    $nlon -= 0.5;
    ##    prt("$nlon ");
    #}
    #prt("\n");
}

# USGS DEM 30 FILES
# W180N90	W140N90	W100N90	W060N90	W020N90	E020N90	E060N90	E100N90	E140N90
# W180N40	W140N40	W100N40	W060N40	W020N40	E020N40	E060N40	E100N40	E140N40
# W180S10	W140S10	W100S10	W060S10	W020S10	E020S10	E060S10	E100S10	E140S10
sub do_test7() {
    my $ewspan = 40;
    my $nsspan = 50;
    my $DIM = 0.00833333333333333;
    my $mcols = $ewspan / $DIM;
    my $mrows = $nsspan / $DIM;
    prt("USGS DEM 30 FILES - span ew $ewspan ns $nsspan DIM $DIM\n");
    my $size = $mcols * $mrows * 2;
    prt("cols $mcols, rows $mrows, file size $size\n");

}

#########################################
### MAIN ###
#parse_args(@ARGV);
#process_in_file($in_file);
#do_test();  # output a LOG scale
#do_test3();
#do_test4();
#do_test5();
#do_test6();
do_test7();
pgm_exit(0,"");
########################################

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 $verb = VERB2();
    while (@av) {
        $arg = $av[0];
        if ($arg =~ /^-/) {
            $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);
                    }
                }
                $verb = VERB2();
                prt("Verbosity = $verbosity\n") if ($verb);
            } elsif ($sarg =~ /^l/) {
                if ($sarg =~ /^ll/) {
                    $load_log = 2;
                } else {
                    $load_log = 1;
                }
                prt("Set to load log at end. ($load_log)\n") if ($verb);
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set out file to [$out_file].\n") if ($verb);
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $arg;
            prt("Set input to [$in_file]\n") if ($verb);
        }
        shift @av;
    }

    if ($debug_on) {
        prtw("WARNING: DEBUG is ON!\n");
        if (length($in_file) ==  0) {
            $in_file = $def_file;
            prt("Set DEFAULT input to [$in_file]\n");
        }
    }
    if (length($in_file) ==  0) {
        pgm_exit(1,"ERROR: No input files found in command!\n");
    }
    if (! -f $in_file) {
        pgm_exit(1,"ERROR: Unable to find in file [$in_file]! Check name, location...\n");
    }
}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] in-file\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(" --load        (-l) = Load LOG at end. ($outfile)\n");
    prt(" --out <file>  (-o) = Write output to this file.\n");
}

# eof - template.pl
