#!/usr/bin/perl -w
# NAME: findfix.pl
# AIM: Given the name of a fix, search for it...
# 11/02/2014 geoff mclane http://geoffair.net/mperl
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.2 2014-02-11";
my $load_log = 0;
my $find_fix = '';
my $verbosity = 0;
my $out_file = '';
my $use_xplane = 0;

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

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

my $CDATROOT="F:/fgdata"; # 20140127 - 3.1
my $FGROOT = (exists $ENV{'FG_ROOT'})? $ENV{'FG_ROOT'} : $CDATROOT;
my $FIXFILE 	  = "$FGROOT/Navaids/fix.dat.gz";	# the FIX data file

my $xp_fix = 'D:\FG\xplane\1000\earth_fix.dat';

my $fixdata = $FIXFILE;

# outfiles, if they do not exist
my $fg_csv = $temp_dir.$PATH_SEP."fg-fixes.csv";
my $xp_csv = $temp_dir.$PATH_SEP."xp-fixes.csv";

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 write_csv($$) {
    my ($ra,$file) = @_;
    my $csv = "latitude,longitude,name\n";
    my ($line,@arr,$len,$cnt);
    $cnt = 0;
    foreach $line (@{$ra}) {
        $line = trim_all($line);
        @arr = split(/\s+/,$line);
        $len = scalar @arr;
        next if ($len != 3);
        $cnt++;
        $csv .= join(",",@arr)."\n";
    }
    write2file($csv,$file);
    prt("Written $cnt fixes to $file\n");
}

my @fix_lines = ();
sub load_xp_fixes() {
    open NIX, "< $xp_fix" or pgm_exit(1,"Error: Unable to open $xp_fix!\n");
    @fix_lines = <NIX>;
    close NIX;
    if (! -f $xp_csv) {
        write_csv(\@fix_lines,$xp_csv);
    }
    return \@fix_lines;
}

sub load_fix_file {
    return \@fix_lines if (@fix_lines);
    if ($use_xplane) {
        return load_xp_fixes()
    }
	prt("\n[v9] Loading $fixdata file ...\n") if (VERB9());
	mydie("ERROR: Can NOT locate [$fixdata]!\n") if ( !( -f $fixdata) );
	open NIF, "gzip -d -c $fixdata|" or mydie( "ERROR: CAN NOT OPEN $fixdata...$!...\n" );
	@fix_lines = <NIF>;
	close NIF;
    prt("[v9] Got ".scalar @fix_lines." lines to scan...from $fixdata\n") if (VERB9());
    if (! -f $fg_csv) {
        write_csv(\@fix_lines,$fg_csv);
    }
    return \@fix_lines;
}

my %fixes_found = ();
my %fix_dupes = ();

sub find_fix($) {
    my $fix = shift;
    my $ra = load_fix_file();
    my $max = scalar @{$ra};
    prt("Searching for $fix, in $max lines of file $fixdata\n") if (VERB9());
    my ($line,$i,$tline,@arr,$test,$lat,$lon,$len,$i2,$fnd,$rfla);
    $fnd = 0;
    my @lines = ();
    my $lncnt = 0;
    for ($i = 0; $i < $max; $i++) {
        $i2 = $i + 1;
        $line = ${$ra}[$i];
        $line = trim_all($line);
        @arr = split(/\s+/,$line);
        $len = scalar @arr;
        next if ($len != 3);
        $lncnt++;
        $lat = $arr[0];
        $lon = $arr[1];
        $test = $arr[2];
        # prt("$i2: Fix $test $lat $lon\n");
        if ($test eq $fix) {
            prt("Found $fix $lat $lon\n") if (VERB5());
            $fnd++;
            push(@lines,$line);
            $fixes_found{$fix} = [] if (!defined $fixes_found{$fix});
            $rfla = $fixes_found{$fix};
            push(@{$rfla},$line);
        }
    }
    ### $load_log = 1;
    if ($fnd) {
        prt("Fix $fix found $fnd times - ");
        prt(join(" ",@lines));
        prt("\n");
    } else {
        prt("Fix $fix NOT found in $max lines...\n");
    }
}

sub find_fixes() {
    my ($fix,$cnt,$line,$rfla,@arr2,$lat,$lon);
    $cnt = scalar @find_fixes;
    prt("Searching for $cnt fixes...\n");
    foreach $fix (@find_fixes) {
        find_fix($fix);
    }
    ############################################
    # SORT the fixes alphabetically
    my @arr = sort keys(%fixes_found);
    my $cnt2 = scalar @arr;
    my $json = '';
    if ($cnt2) {
        prt("Found $cnt2 of $cnt fixes...\n");
        $json .= "{\"FIXES\":[\n";
        $cnt2 = 0;
        foreach $fix (@arr) {
            $rfla = $fixes_found{$fix};
            foreach $line (@{$rfla}) {
                @arr2 = split(/\s+/,$line);
                $lat = $arr2[0];
                $lon = $arr2[1];
                $json .= ",\n" if ($cnt2);
                $json .= "{\"N\":\"$fix\",\"lat\":$lat,\"lon\":$lon}";
                $cnt2++;
            }
        }
        $json .= "\n]}\n";
        if ($cnt2) {
            if (length($out_file)) {
                write2file($json,$out_file);
                prt("JSON for $cnt2 fixes written to $out_file\n");
            } else {
                prt($json);
                prt("No output file -o <file> command found.\n");
            }
        }
    }
    my $msg1 = '';
    my $msg2 = '';
    foreach $fix (@find_fixes) {
        $cnt2 = 0;
        foreach $line (@arr) {
            if ($fix eq $line) {
                $cnt2 = 1;
                last;
            }
        }
        if ($cnt2) {
            # found
            $msg1 .= ' ' if (length($msg1));
            $msg1 .= $fix;
        } else {
            # not found
            $msg2 .= ' ' if (length($msg2));
            $msg2 .= $fix;
        }
    }
    if (length($msg2)) {
        prt("Of $cnt, found $msg1, but no find of $msg2\n");
    } else {
        prt("Appears all $cnt fixes found.\n");
    }
}

#########################################
### MAIN ###
parse_args(@ARGV);
#process_in_file($find_fix);
find_fixes();
pgm_exit(0,"");
########################################

sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have a following argument!\n") if (!@av);
}

sub load_input_file($) {
    my $file = shift;
    if (open INP, "<$file") {
        my @lines = <INP>;
        close INP;
        my ($line);
        my @inputs = ();
        foreach $line (@lines) {
            chomp $line;
            $line = trim_all($line);
            next if (length($line) == 0);
            push(@inputs,$line);
        }
        if (@inputs) {
            parse_args(@inputs);
        }
    } else {
        pgm_exit(1,"Error: Unable to load input file $file\n");
    }
}

sub parse_args {
    my (@av) = @_;
    my ($arg,$sarg);
    my $verb = VERB2();
    my %dupes = ();
    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 =~ /^i/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $in_input++;
                load_input_file($sarg);
                $in_input--;
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set out file to [$out_file].\n") if ($verb);
            } elsif ($sarg =~ /^x/) {
                $use_xplane = 1;
                prt("Set to use x-plane data file [$xp_fix].\n") if ($verb);
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $find_fix = $arg;
            prt("Set input to [$find_fix]\n") if ($verb);
            if (!defined $dupes{$arg}) {
                $dupes{$arg} = 1;
                push(@find_fixes,$find_fix);
            }
        }
        shift @av;
    }
    if (! $in_input) {
        if ($debug_on) {
            prtw("WARNING: DEBUG is ON!\n");
            if (length($find_fix) ==  0) {
                $find_fix = $def_file;
                push(@find_fixes,$find_fix);
                prt("Set DEFAULT input to [$find_fix]\n");
            }
        }
        if (length($find_fix) ==  0) {
            pgm_exit(1,"ERROR: No input 'fix' found in command!\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");
    prt(" --xplane      (-x) = Use x-plane earth_fix_dat.\n");
    prt(" --in <file>   (-i) = Use file line separated list of inputs.\n");

}

# eof - template.pl
