#!/usr/bin/perl -w
# NAME: fgscenery.pl
# AIM: Given a fg scenery directory, search and report what scenery is available...
# Note: This is a complete REWRITE of fgscenery.pl
# 29/03/2011 geoff mclane http://geoffair.net/mperl
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use File::Spec; # File::Spec->rel2abs($rel); # we are IN the SLN directory, get ABSOLUTE from RELATIVE
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 location and \@INC content.\n";
require 'fg_wsg84.pl' or die "Unable to load fg_wsg84.pl ...\n";
require "Bucket2.pm" or die "Unable to load Bucket2.pm ...\n";
# log file stuff
my ($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 $load_log = 1;
my $in_dir = '';

my $debug_on = 1;
my $def_dir = 'C:\FG\Scenery-1.0.1';

### program variables
my @warnings = ();
my $cwd = cwd();
my $os = $^O;
my ($gchunk,$gtile);
my @btg_files = ();
my @stg_files = ();
my @apt_files = ();
my @fg_chunks = ();
my @fg_tiles = ();
my @icao_list = ();
my $tot_btg_cnt = 0;
my $tot_stg_cnt = 0;
my $tot_apt_cnt = 0;

# forward ref
sub process_in_dir($$);

# debug
my $dbg_01 = 0; # show scenery
my $dbg_02 = 0; # show stg files
my $dbg_03 = 0; # show airports
my $dbg_04 = 0; # show tiles
my $dbg_05 = 0; # show stg,stg,apt counts

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_dir($$) {
    my ($dir,$dep) = @_;
    if (! opendir(DIR, $dir)) {
        pgm_exit(1,"ERROR: Unable to open directory [$dir]\n"); 
    }
    my @dfiles = readdir(DIR);
    closedir(DIR);
    my $lncnt = scalar @dfiles;
    prt("Processing $lncnt items, from [$dir]...\n") if ($dep == 0);
    $dir .= "\\" if ( !($dir =~ /(\\|\/)$/) );
    my ($file,$ff,$dcnt,$fcnt,$ndir);
    my @dirs = ();
    my @files = ();
    foreach $file (@dfiles) {
        next if ($file eq '.');
        next if ($file eq '..');
        $ff = $dir.$file;
        if (-d $ff) {
            push(@dirs,$ff);
        } elsif (-f $ff) {
            push(@files,$ff);
        } else {
            prtw("WARNING: Not DIR or FILE! What is this [$ff]\n");
        }
    }
    $dcnt = scalar @dirs;
    $fcnt = scalar @files;
    my ($ew,$lon,$ns,$lat,$icao,$index,$nfil,$curr,$nm,$dr);
    prt("Found $dcnt directories, and $fcnt files...\n") if ($dep == 0);
    if ($dep == 0) {
        foreach $ndir (@dirs) {
            if ($ndir =~ /[\\\/]Terrain$/) {
                process_in_dir($ndir,$dep + 1);
            }
        }
    } elsif ($dep == 1) {
        foreach $ndir (@dirs) {
            if ($ndir =~ /[\\\/](e|w)(\d{3})(n|s)(\d{2})$/) {
                $ew = $1;
                $lon = $2;
                $ns = $3;
                $lat = $4;
                $gchunk = "$ew$lon$ns$lat";
                prt("Got CHUNK $gchunk (10x10)\n");
                push(@fg_chunks,$gchunk);
                process_in_dir($ndir,$dep + 1);
            } else {
                prtw("WARNING: What is this CHUNK directory [$ndir]\n");
            }
        }
    } elsif ($dep == 2) {
        my $tile_cnt = 0;
        foreach $ndir (@dirs) {
            if ($ndir =~ /[\\\/](e|w)(\d{3})(n|s)(\d{2})$/) {
                $ew = $1;
                $lon = $2;
                $ns = $3;
                $lat = $4;
                $gtile = "$ew$lon$ns$lat";
                prt(" Got TILE $gchunk/$gtile\n") if ($dbg_04);
                push(@fg_tiles,$gchunk);
                $tile_cnt++;
                process_in_dir($ndir,$dep + 1);
            } else {
                prtw("WARNING: What is this TILE directory [$ndir]\n");
            }
        }
        prt("Got $tile_cnt tiles for chunk $gchunk\n");
    } elsif ($dep == 3) {
        my $btg_cnt = 0;
        my $stg_cnt = 0;
        my $apt_cnt = 0;
        $curr = "$gchunk/$gtile";
        foreach $nfil (@files) {
            ($nm,$dr) = fileparse($nfil);
            $curr = "$gchunk/$gtile/$nm";
            if ($nfil =~ /[\\\/](\d+)\.btg\.gz$/) {
                $index = $1;
                prt("   Got SCENERY [$index] $curr\n") if ($dbg_01);
                push(@btg_files,$nfil);
                $btg_cnt++;
            } elsif ($nfil =~ /[\\\/](\d+)\.stg$/) {
                $index = $1;
                push(@stg_files,$nfil);
                prt("   Got STGFILE [$index] $curr\n") if ($dbg_02);
                $stg_cnt++;
            } elsif ($nfil =~ /[\\\/](\w+)\.btg\.gz$/) {
                $icao = $1;
                push(@apt_files,$nfil);
                push(@icao_list,$icao);
                prt("   Got AIRPORT [$icao] $curr\n") if ($dbg_03);
                $apt_cnt++;
            } else {
                prtw("WARNING: CHECKME - What is this? [$nfil] $curr\n");
            }
        }
        $curr = "$gchunk/$gtile";
        prt("Got $stg_cnt stg, $btg_cnt btg files, and $apt_cnt airport tiles for $curr\n") if ($dbg_05);
        $tot_btg_cnt += $btg_cnt;
        $tot_stg_cnt += $stg_cnt;
        $tot_apt_cnt += $apt_cnt;
    }

    if ($dep == 0) {
        my $acnt = scalar @icao_list;
        my $ccnt = scalar @fg_chunks;
        my ($tmp,$wrap);
        if ($tot_stg_cnt == $tot_btg_cnt) {
            prt("Got $tot_stg_cnt stg/btg, and $tot_apt_cnt airports\n");
        } else {
            prt("Got $tot_stg_cnt stg, $tot_btg_cnt btg files, and $tot_apt_cnt airports\n");
        }
        prt("Got $ccnt CHUNKS, $acnt AIRPORTS...\n");
        foreach $tmp (@fg_chunks) {
            prt("$tmp ");
        }
        prt("\n") if ($ccnt);
        $wrap = 0;
        foreach $tmp (@icao_list) {
            $wrap++;
            if ($wrap > 18) {
                prt("\n");
                $wrap = 0;
            }
            prt("$tmp ");
        }
        prt("\n") if ($acnt);

    }
}

#########################################
### MAIN ###
parse_args(@ARGV);
process_in_dir($in_dir,0);
pgm_exit(0,"Normal exit(0)");
########################################
sub give_help {
    prt("$pgmname: version 0.0.1 2010-09-11\n");
    prt("Usage: $pgmname [options] in-file\n");
    prt("Options:\n");
    prt(" --help (-h or -?) = This help, and exit 0.\n");
}
sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have 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)");
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_dir = File::Spec->rel2abs($arg);
            prt("Set input driectory to [$in_dir]\n");
        }
        shift @av;
    }

    if ((length($in_dir) ==  0) && $debug_on) {
        $in_dir = $def_dir;
    }
    if (length($in_dir) ==  0) {
        pgm_exit(1,"ERROR: No input directory found in command!\n");
    }
    if (! -d $in_dir) {
        pgm_exit(1,"ERROR: Unable to find in directory [$in_dir]! Check name, location...\n");
    }
}

# eof - fgscenery.pl
