#!/usr/bin/perl -w
# NAME: scanhgt.pl
# AIM: Special SCAN of HGT files
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
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.1 2013-03-17";
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");
        }
    }
}

my $in_dir = "F:\\data\\DEM\\hgt";
my @hgt = ();
my $file_count = 0;
my $dir_count = 0;
my %hgt_files = ();

sub scan_directory($$$);

if (! -d $in_dir) {
    prt("Directory $in_dir does NOT exist!\n");
    exit(1)
}


sub fix_dir($) {
    my $rd = shift;
    if (length($rd) && (!(${$rd} =~ /(\\|\/)$/))) {
        ${$rd} .= $PATH_SEP;
    }
}

my %north = ();
my %south = ();
my %east = ();
my %west = ();

sub in_half_world($$) {
    my ($lat,$lon) = @_;
    if ( ($lat >= 0) && ($lat <= 90) &&
         ($lon >= 0) && ($lon <= 180) ) {
        return 1;
    }
    return 0;
}

sub process_hgt($) {
    my $ra = shift;
    my $max = scalar @{$ra};
    prt("Found $max hgt files...\n");
    my ($j,$file,$i,$ew,$lat,$ns,$lon);
    for ($i = 0; $i <= 180; $i++) {
        $east{$i} = 0;
        $west{$i} = 0;
        $north{$i} = 0;
        $south{$i} = 0;
    }
    for ($i = 0; $i < $max; $i++) {
        $file = ${$ra}[$i];
        if ($file =~ /(N|S|n|s)(\d{2})(E|W|e|w)(\d{3})\./) {
            $ns = uc($1);
            $lat = sprintf("%d",$2);
            $ew = uc($3);
            $lon = sprintf("%d",$4);
            if (in_half_world($lat,$lon)) {
                if ($ns eq 'N') {
                    $north{$lat} = 1;
                } else {
                    $south{$lat} = 1;
                }
                if ($ew eq 'E') {
                    $east{$lon} = 1;
                } else {
                    $west{$lon} = 1;
                }
            } else {
                prtw("WARNING: OOW $file!\n");
            }
        } else {
            prt("File does NOT comply [$file]\n");
            exit(1);
        }
    }
    my $msg = '';
    for ($j = 90; $j >=0 ; $j--) {
        $lat = $north{$j};
        $ns = sprintf("N%02d: ",$j);
        $msg .= $ns;
        for ($i = 180; $i >= 0; $i--) {
            $lon = $west{$i};
            if (($lat > 0) && ($lon > 0)) {
                $msg .= 'x';
            } else {
                $msg .= ' ';
            }
        }
        for ($i = 0; $i <= 180; $i++) {
            $lon = $east{$i};
            if (($lat > 0) && ($lon > 0)) {
                $msg .= 'x';
            } else {
                $msg .= ' ';
            }
        }
        $msg .= "\n";
    }
    for ($j = 0; $j <= 90 ; $j++) {
        $lat = $south{$j};
        $ns = sprintf("S%02d: ",$j);
        $msg .= $ns;
        for ($i = 180; $i >= 0; $i--) {
            $lon = $west{$i};
            if (($lat > 0) && ($lon > 0)) {
                $msg .= 'x';
            } else {
                $msg .= ' ';
            }
        }
        for ($i = 0; $i <= 180; $i++) {
            $lon = $east{$i};
            if (($lat > 0) && ($lon > 0)) {
                $msg .= 'x';
            } else {
                $msg .= ' ';
            }
        }
        $msg .= "\n";
    }
    prt("$msg\n") if (VERB9());
    ##$load_log = 1;
}

sub gen_ascii() {
    my ($fil,$n,$e,$msg,$ns,$ew);
    $msg = '';
    for ($n = 90; $n >= 0; $n--) {
        $ns = sprintf("N%02d",$n);
        $msg .= "$ns: ";
        for ($e = 180; $e > 0; $e--) {
            $ew = sprintf("W%03d",$e);
            $fil = $ns.$ew;
            if (defined $hgt_files{$fil}) {
                $msg .= 'x';
            } else {
                $msg .= ' ';
            }
        }
        $msg .= '|';
        for ($e = 0; $e <= 180; $e++) {
            $ew = sprintf("E%03d",$e);
            $fil = $ns.$ew;
            if (defined $hgt_files{$fil}) {
                $msg .= 'x';
            } else {
                $msg .= ' ';
            }
        }
        $msg .= "\n";
    }
    for ($n = 1; $n <= 90; $n++) {
        $ns = sprintf("S%02d",$n);
        $msg .= "$ns: ";
        for ($e = 180; $e > 0; $e--) {
            $ew = sprintf("W%03d",$e);
            $fil = $ns.$ew;
            if (defined $hgt_files{$fil}) {
                $msg .= 'x';
            } else {
                $msg .= ' ';
            }
        }
        $msg .= '|';
        for ($e = 0; $e <= 180; $e++) {
            $ew = sprintf("E%03d",$e);
            $fil = $ns.$ew;
            if (defined $hgt_files{$fil}) {
                $msg .= 'x';
            } else {
                $msg .= ' ';
            }
        }
        $msg .= "\n";
    }
    prt("$msg\n");
    $load_log = 1;
}

sub show_hgt_list() {
    my @arr = sort keys %hgt_files;
    my $fil = '';
    my $wrap = 10;
    my $cnt = 0;
    foreach $fil (@arr) {
        prt("$fil ");
        $cnt++;
        if ($cnt == $wrap) {
            prt("\n");
            $cnt = 0;
        }
    }
    if ($cnt) {
        prt("\n");
    }
    # $load_log = 1;
}

sub scan_directory($$$) {
    my ($dir,$ra,$lev) = @_;
    my ($file,$ff,$n,$d,$e);
    my @dirs = ();
    if (opendir(DIR,$dir)) {
        my @files = readdir(DIR);
        closedir(DIR);
        fix_dir(\$dir);
        $dir_count++;
        foreach $file (@files) {
            next if ($file eq '.');
            next if ($file eq '..');
            $ff = $dir.$file;
            if (-d $ff) {
                push(@dirs,$ff);
            } elsif (-f $ff) {
                if ($file =~ /\.hgt$/i) {
                    push(@{$ra},$ff);
                    $file_count++;
                    if (($file_count % 1000) == 0) {
                        prt("Got $file_count hgt files...\n");
                    }
                    ($n,$d,$e) = fileparse($file, qr/\.[^.]*/);
                    $n = uc($n);
                    $hgt_files{$n} = 1;
                }
            } else {
                prt("WHAT is THIS $ff\n");
                exit(1);
            }
        }
        foreach $dir (@dirs) {
            scan_directory($dir,$ra,($lev+1));
        }
    } else {
        prt("WARNING: can NOT open $dir!");
    }
    if ($lev == 0) {
        prt("In $dir_count directories, found $file_count hgt files...\n");
    }
}


#########################################
### MAIN ###
#parse_args(@ARGV);
#process_in_file($in_file);
prt("Moment, scanning directory $in_dir...\n");
scan_directory($in_dir,\@hgt,0);
# push(@hgt,"F:\\data\\DEM\\hgt\\Icelandv2\\n63w014.hgt");
#process_hgt(\@hgt);
#show_hgt_list();
gen_ascii();
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);
    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);
                    }
                }
                prt("Verbosity = $verbosity\n") if (VERB1());
            } elsif ($sarg =~ /^l/) {
                if ($sarg =~ /^ll/) {
                    $load_log = 2;
                } else {
                    $load_log = 1;
                }
                prt("Set to load log at end. ($load_log)\n") if (VERB1());
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set out file to [$out_file].\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $arg;
            prt("Set input to [$in_file]\n") if (VERB1());
        }
        shift @av;
    }

    if ($debug_on) {
        prtw("WARNING: DEBUG is ON!\n");
        if ((length($in_file) ==  0) && $debug_on) {
            $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
