#!/usr/bin/perl -w
# NAME: groundnet.pl
# AIM: Quite specific - Read a FG airport groundnet.xml and show info
# 30/08/2013 geoff mclane http://geoffair.net/mperl
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use XML::Simple;
use Data::Dumper;
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_icao = '';
my $verbosity = 0;
my $out_file = '';
my $scenery = 'D:\Scenery\terrascenery\data\Scenery\Airports';

# ### DEBUG ###
my $debug_on = 0;
my $def_icao = 'EBBR';

### 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 @freq_types = qw( GROUND DEPARTURE AWOS APPROACH TOWER UNICOM CLEARANCE );
my %short_types =( 
    'GROUND' => 'GND',
    'DEPARTURE' => 'DEP',
    'APPROACH' => 'APP',
    'TOWER' => 'TWR',
    'UNICOM' => 'UNI',
    'CLEARANCE' => 'CLR'
    );

sub get_freqs($) {
    my $ra = shift; # \@lines
    my %freqs = ();
    my ($i,$cnt,$line,$len,$off,$tmp);
    $cnt = scalar @{$ra};
    for ($i = 0; $i < $cnt; $i++) {
        $line = trim_all(${$ra}[$i]);
        $len = length($line);
        next if ($len == 0);
        $off = index($line, '<frequencies>');
        if ($off >= 0) {
            $line = substr($line,$off+13);
            $i++;
            last;
        }
    }
    if ($i < $cnt) {
        # get the freq block
        for (; $i < $cnt; $i++) {
            $tmp = trim_all(${$ra}[$i]);
            $len = length($tmp);
            next if ($len == 0);
            $off = index($tmp, '</frequencies>');
            if ($off >= 0) {
                $line .= substr($tmp,0,$off) if ($off > 0);
                last;
            } else {
                $line .= $tmp;
            }
        }
        if ($i < $cnt) {
            prt("$line\n") if (VERB9());
            $len = length($line);
            my $tag = '';
            my $txt = '';
            my ($ch,$intag,$last_tag,$rva);
            $intag = 0;
            for ($i = 0; $i < $len; $i++) {
                $ch = substr($line,$i,1);
                if ($intag) {
                    if ($ch eq '>') {
                        #prt("Close tag\n");
                        if ($tag =~ /^\//) {
                            $tag = substr($tag,1);
                            if ($tag eq $last_tag) {
                                if (length($txt)) {
                                    prt("$tag $txt\n") if (VERB5());
                                    $freqs{$tag} = [] if (!defined $freqs{$tag});
                                    $rva = $freqs{$tag};
                                    push(@{$rva},$txt);
                                } else {
                                    pgm_exit(1,"xml tag <$tag> with NO TEXT!\n");
                                }
                                $txt = '';
                            } else {
                                pgm_exit(1,"xml tag <$last_tag> NOT closed by <$tag>\n");
                            }

                        } else {
                            $last_tag = $tag; # this is what we are collecting
                        }
                        $intag = 0;
                    } else {
                        $tag .= $ch;
                    }
                } elsif ($ch eq '<') {
                    $intag = 1;
                    #prt("Start tag\n");
                    $tag = '';
                } else {
                    $txt .= $ch;
                }
            }
        } else {
            prt("Failed to find </frequencies>!\n");
        }
    } else {
        prt("Failed to find <frequencies>!\n");
    }

    return \%freqs;
}

# Example
# <Parking index="127" type="gate" name="nq" number="127" lat="N50 53.939" 
# lon="E04 28.103" heading="156" radius="27" pushBackRoute="588" airlineCodes="" />
sub get_parking($) {
    my $ra = shift;
    my %park = ();
    my ($i,$cnt,$line,$len,$off,$tmp);
    $cnt = scalar @{$ra};
    $park{Parking} = [];
    for ($i = 0; $i < $cnt; $i++) {
        $line = trim_all(${$ra}[$i]);
        $len = length($line);
        next if ($len == 0);
        $off = index($line, '<parkingList>');
        if ($off >= 0) {
            $line = substr($line,$off+13);
            $i++;
            last;
        }
    }
    if ($i >= $cnt) {
        prt("Failed to find <parkingList>!\n");
        return %park;
    }
    for (; $i < $cnt; $i++) {
        $tmp = trim_all(${$ra}[$i]);
        $len = length($tmp);
        next if ($len == 0);
        $off = index($tmp, '</parkingList>');
        if ($off >= 0) {
            $line .= substr($tmp,0,$off) if ($off > 0);
            last;
        } else {
            $line .= " $tmp";
        }
    }
    if ($i >= $cnt) {
        prt("Failed to find </parkingList>!\n");
        return %park;
    }
    $len =length($line);
    prt("len $len $line\n") if (VERB9());
    my ($ch,$pc,$intag,$tag,$txt,$inats,$rpa,$tg,$tx);
    $intag = 0;
    $inats = 0;
    my $hadname = 0;
    my $hadnum = 0;
    $ch = '';
    $rpa = $park{Parking};
    for ($i = 0; $i < $len; $i++) {
        $pc = $ch;
        $ch = substr($line,$i,1);
        if ($intag) {
            if ($ch eq '>') {
                $intag = 0;
                $txt =~ s/\s*\/$//;
                prt("$tag $txt\n") if (VERB9());
                if ($tag eq 'Parking') {
                    my @a = space_split($txt); # split on spaces, honoring quotes
                    #push(@{$rpa}, \@a);
                    my %h = ();
                    $hadname = 0;
                    $hadnum = 0;
                    foreach $tmp (@a) {
                        my @a2 = split("=",$tmp);
                        $cnt = scalar @a2;
                        if ($cnt == 2) {
                            $tg = $a2[0];
                            $tx = strip_quotes($a2[1]);
                            if (defined $h{$tg}) {
                                prtw("WARNING: tag $tg REPEATED in [$txt]!\n");
                            }
                            $tx = ' ' if (length($tx) == 0);
                            $h{$tg} = $tx;
                            if ($tg eq 'name') {
                                $hadname = 1
                            } elsif ($tg eq 'number') {
                                $hadnum = 1;
                            }
                        } else {
                            prtw("WARNING: tg $tag item $tmp did NOT split in 2 = $cnt\n");
                        }
                    }
                    push(@{$rpa}, \%h);
                    if (($hadname == 0)||($hadnum == 0)) {
                        prtw("WARNING: NO name/num [$tag $txt]\n");
                    }
                } else {
                    prtw("WARNING: Skipped tag [$tag in parkingList\n");
                }
                $tag = '';
                $txt = '';
            } else {
                if ($inats) {
                    $txt .= $ch;
                } elsif ($ch =~ /\s/) {
                    $inats = 1;
                } else {
                    $tag .= $ch;
                }
            }
        } elsif ($ch eq '<') {
            $intag = 1;
            $inats = 0;
            $tag = '';
            $txt = '';
        }
    }
    return \%park;
}

# build file name like 'D:\Scenery\terrascenery\data\Scenery\Airports\E\B\B\EBBR.groundnet.xml'
sub process_in_icao($) {
    my $icao = shift;
    my $dir = $scenery;
    pgm_exit(1,"ERROR: Invalid ICAO [$icao]\n") if (length($icao) < 3);
    my ($ch,$i,$file,$key,$val,$ref,$name,$val2,$msg,$tmp);
    for ($i = 0; $i < 3; $i++) {
        $ch = substr($icao,$i,1);
        $dir .= $PATH_SEP.$ch;
    }
    $file = $dir.$PATH_SEP.$icao.".groundnet.xml";
    if (!-f $file) {
        prt("Warning: Can NOT locate file [$file]\n");
        return;
    }
    if (!open INF, "<$file") {
        prt("ERROR: Can NOT OPEN file [$file]\n");
        return;
    }
    my @lines = <INF>;
    close INF;
    my $lncnt = scalar @lines;
    prt("Loaded [$file]... $lncnt lines...\n");
    my $rf = get_freqs(\@lines);
    my @arr = sort keys(%{$rf});
    foreach $key (@arr) {
        $val = ${$rf}{$key};
        $key = $short_types{$key} if (defined $short_types{$key});
        #$msg .= "$key: ".join(" ",@{$val})." ";
        $msg .= "$key: ";
        foreach $tmp (@{$val}) {
            $msg .= $tmp / 100;
            $msg .= " ";
        }
    }
    prt("$msg\n");

    my $rp = get_parking(\@lines);
    my $rpa = ${$rp}{Parking};
    # array of hash for Parking
    $val = scalar @{$rpa};
    my ($rh);
    my ($ph,$ll,$sec1,$sec2,$pos);
    my ($index,$numb,$line,$cnt,$type,@kys);
    $cnt = 0;
    my %hash = ();
    my %htypes = ();
    $cnt = 0;
    foreach $rh (@{$rpa}) {
        $cnt++;
        ###my @kys = sort keys(%{$rh});
        ### prt(join(" ",@kys)."\n");
        ###foreach $key (@kys) {
        ### $val = ${$rh}{$key};
        undef($index);
        undef($name);
        undef($numb);
        undef($type);
        $index = ${$rh}{index} if (defined ${$rh}{index});
        $name = ${$rh}{name} if (defined ${$rh}{name});
        $numb = ${$rh}{number} if (defined ${$rh}{number});
        $type = ${$rh}{type} if (defined ${$rh}{type});
        if ($name && $numb) {
            #next if ($name =~ /Startup\s+Location/);
            next if ($name =~ /Start/i);
            #push(@arr,"$name$numb");
            $hash{"$name$numb"} = $type ? $type : 1;
        } else {
            prt("Record $cnt does not have a 'name' or 'number'!\n");
        }
        $htypes{$type} = 1 if ($type);
    }
    @arr = keys(%hash);
    $cnt = scalar @arr;
    $type = scalar keys(%htypes);
    $tmp = join(", ", sort keys(%htypes));
    prt("Got $val Parking hashes... $cnt with unque name/number, $type types, $tmp, excluding 'Startup...'\n");
    if (VERB9()) {
        foreach $rh (@{$rpa}) {
            @kys = sort keys(%{$rh});
            ### prt(join(" ",@kys)."\n");
            foreach $key (@kys) {
                $val = ${$rh}{$key};
                if (($key eq 'lat') || ($key eq 'lon')) {
                    if ($val =~ /^([NSEW])(\d+)\s+(\d+)\.(\d+)$/) {
                        $ph = $1;
                        $ll = $2;
                        $sec1 = $3;
                        $sec2 = $4;
                        $pos = $ll + ($sec1 / 60);  # add in minutes
                        $pos += ($sec2 / 1000) / 60;
                        $pos = -$pos if (($ph eq 'W') || ($ph eq 'S'));
                        # prt("$key=\"$pos\" ");
                        prt("$key=\"$val\" ");
                    } else {
                        prt("CHECK $key=\"$val\" ");
                    }
                } elsif ($key eq 'pushBackRoute') {
                } elsif ($key eq 'airlineCodes') {
                } else {
                    prt("$key=\"$val\" ");
                }
            }
            prt("\n");
        }
    } else {
        $line = '';
        foreach $tmp (sort @arr) {
            $line .= "$tmp ";
            if (length($line) > 100) {
                prt("$line\n");
                $line = '';
            }
        }
        prt("$line\n") if (length($line));
    }
}

sub process_in_icao_as_XML($) {
    my $icao = shift;
    my $dir = $scenery;
    pgm_exit(1,"ERROR: Invalid ICAO [$icao]\n") if (length($icao) < 3);
    my ($ch,$i,$file,$key,$val,$ref,$name,$val2,$msg);
    for ($i = 0; $i < 3; $i++) {
        $ch = substr($icao,$i,1);
        $dir .= $PATH_SEP.$ch;
    }
    $file = $dir.$PATH_SEP.$icao.".groundnet.xml";
    if (!-f $file) {
        prt("Can NOT locate file [$file]\n");
        return;
    }
    prt("Loading [$file]\n");
    my $xml = XMLin($file);
    #prt(Dumper($xml));
    #$load_log = 1;
    $key = 'frequencies';
    if (defined ${$xml}{$key}) {
        $val = ${$xml}{$key};
        $ref = ref($val);
        prt("key $key is a $ref\n");
        if ($ref eq 'HASH') {
            $msg = '';
            foreach $name (@freq_types) {
                if (defined ${$val}{$name}) {
                    $val2 = ${$val}{$name};
                    $ref = ref($val2);
                    $name = $short_types{$name} if (defined $short_types{$name});
                    if (length($ref) == 0) {
                        $msg .= "$name: $val2 ";
                    } elsif ($ref eq 'ARRAY') {
                        $msg .= "$name: ".join(" ",@{$val2})." ";
                    } else {
                        prtw("WARNING: $key $name Uncoded ref [$ref] FIX ME\n");
                    }
                }
            }
            prt("$key: $msg\n") if (length($msg));
        } else {
            prtw("WARNING: $key is NOT a HASH! It is [$ref] FIX ME\n");
        }
    }

}


#########################################
### MAIN ###
parse_args(@ARGV);
process_in_icao($in_icao);
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 =~ /^d/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $scenery = $sarg;
                if (! -d $scenery) {
                    pgm_exit(1,"ERROR: Can NOT locate $scenery!\n");
                }
                prt("Set scenery path to [$scenery].\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_icao = $arg;
            prt("Set input to [$in_icao]\n") if (VERB1());
        }
        shift @av;
    }

    if ($debug_on) {
        prtw("WARNING: DEBUG is ON!\n");
        if (length($in_icao) == 0) {
            $in_icao = $def_icao;
            prt("Set DEFAULT input to [$in_icao]\n");
        }
    }
    if (length($in_icao) ==  0) {
        pgm_exit(1,"ERROR: No input ICAO found in command!\n");
    }
}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] ICAO\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");
    prt(" --data <path> (-d) = Set new data path. (def=$scenery)\n");

    prt("\nAim: Given an ICAO, search for the file - \n");
    prt(" ${scenery}${PATH_SEP}I${PATH_SEP}C${PATH_SEP}A${PATH_SEP}ICAO.groundnet.xml\n");
    prt("and if found, display contents.\n");
}

# eof - template.pl
