#!/usr/bin/perl -w
# NAME: fg_io_xml.pl
# AIM: View the contents of a FlightGear IO XML file
# 15/04/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 'logfile.pl' or die "Unable to load logfile.pl ...\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 $pgm_version ="0.0.1 2011-04-15";
my $load_log = 0;
my $in_file = '';
my $include_format = 0;
my $include_name = 0;
my $include_type = 0;
my $include_factor = 0;
my $include_offset = 0;

my $debug_on = 1;
my $def_file = 'C:\DTEMP\FG\ivao\17\cfg\squawk.xml';

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

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);
    my ($i,$len,$ch,$nc,$i2,$pc,$tag,$txt,$lasttag,$chunk,$dir,$tmp);
    my (@arr,$key,$val,$tmp2);
    $lnn = 0;
    $ch = '';
    my $intag = 0;
    my $inchunk = 0;
    $tag = '';
    $txt = '';
    my @tagstack = ();
    my @chunks = ();
    $chunk = '';
    $dir = '';
    my %attrs = ();
    foreach $line (@lines) {
        chomp $line;
        $lnn++;
        $line = trim_all($line);
        $len = length($line);
        for ($i = 0; $i < $len; $i++) {
            $pc = $ch;
            $ch = substr($line,$i,1);
            $i2 = $i + 1;
            $nc = ($i2 < $len) ? substr($line,$i2,1) : "";
            if ($intag) {
                if ($ch eq '>') {
                    $tag .= $ch;
                    $intag = 0;
                    if ($tag =~ /^<\?/) {
                        # header
                    } elsif ($tag =~ /^<!--/) {
                        # forget comments
                    } elsif ($tag =~ /^<\//) {
                        # close - time to store text
                        $tag =~ s/^<\///;
                        $tag =~ s/>$//;
                        if (@tagstack) {
                            $lasttag = pop @tagstack;
                        } else {
                            pgm_exit(1,"ERROR: $lnn: Closing tag [$tag], with NO open tag stack!\n");
                        }
                        if ($tag eq $lasttag) {
                            if ($tag eq 'chunk') {
                                $inchunk = 0;
                                if (length($chunk)) {
                                    $tmp = "$dir:";
                                    @arr = sort keys(%attrs);
                                    if (@arr) {
                                        $tmp2 = '';
                                        foreach $key (@arr) {
                                            $val = $attrs{$key};
                                            if ($key eq 'format') {
                                                $tmp2 .= " $key=\"$val\"" if ($include_format);
                                            } elsif ($key eq 'name') {
                                                $tmp2 .= " $key=\"$val\"" if ($include_name);
                                            } elsif ($key eq 'type') {
                                                $tmp2 .= " $key=\"$val\"" if ($include_type);
                                            } elsif ($key eq 'factor') {
                                                $tmp2 .= " $key=\"$val\"" if ($include_factor);
                                            } elsif ($key eq 'offset') {
                                                $tmp2 .= " $key=\"$val\"" if ($include_offset);
                                            } else {
                                                $tmp2 .= " $key=\"$val\"";
                                            }
                                        }
                                        if (length($tmp2)) {
                                            $tmp .= $tmp2;
                                            prt("$tmp\n");
                                            push(@chunks,$tmp);
                                        }
                                    }
                                    #$tmp = "$dir: $chunk";
                                    #prt("$tmp\n");

                                }
                                $chunk = '';
                                %attrs = (); # clear attributes
                            }
                            if (length($txt)) {
                                #prt("$lnn: <$lasttag> [$txt] </$tag> = Close tag\n");
                                if ($inchunk) {
                                    $chunk .= "; " if (length($chunk));
                                    $chunk .= "$tag=$txt";
                                    $attrs{$tag} = $txt;
                                }
                            } else {
                                #prt("$lnn: <$lasttag></$tag> = Close empty tag\n");
                            }
                        } else {
                            pgm_exit(1,"ERROR: TAG NOT EQUAL [$lasttag] vs [$tag]\n");
                        }
                    } else {
                        # open
                        $tag =~ s/^<//;
                        $tag =~ s/>$//;
                        if (length($txt)) {
                            prt("$lnn: Open tag = [$tag] with text [$txt]\n");
                        } else {
                            #prt("$lnn: Open tag = [$tag] NT\n");
                        }
                        push(@tagstack, $tag);
                        if ($tag eq 'chunk') {
                            $inchunk = 1;
                        } elsif ($tag eq 'output') {
                            $dir = $tag;
                        } elsif ($tag eq 'input') {
                            $dir = $tag;
                        }
                    }
                    $tag = '';
                    $txt = '';
                } else {
                    $tag .= $ch;
                }
            } else {
                if ($ch eq '<') {
                    $tag = $ch;
                    $intag = 1;
                } else {
                    $txt .= $ch;
                }
            }
        }
    }
}

#########################################
### MAIN ###
parse_args(@ARGV);
prt( "$pgmname: in [$cwd]: Hello, World...\n" );
process_in_file($in_file);
pgm_exit(0,"Normal exit(0)");
########################################
sub give_help {
    prt("$pgmname: version $pgm_version\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_file = $arg;
            prt("Set input to [$in_file]\n");
        }
        shift @av;
    }

    if ((length($in_file) ==  0) && $debug_on) {
        $in_file = $def_file;
    }
    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");
    }
}

# eof - template.pl
