#!/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 Math::Geometry::Planar;
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";
require 'fg_wsg84.pl' or die "Unable to load fg_wsg84.pl ...\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.3 2014-11-09";
#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;
my ($u_min_lon,$u_min_lat,$u_max_lon,$u_max_lat);
my $u_got_bbox = 0;
my ($bgn_lon,$bgn_lat,$end_lon,$end_lat);
my $got_track = 0;
my $fudge = 0.01;    # degrees
my $out_xg = $temp_dir.$PATH_SEP."tempfix.xg";

# ### DEBUG ###
my $debug_on = 0;
my $def_file = 'CEDES';
#  <ident type="string">PIY</ident>
#  <ident type="string">ESP</ident>
# -t "-32.539167,117.074444,-33.680556,121.823889"

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

my $CDATROOT="F:/fgdata"; # 20140127 - 3.1
if (-d "X:/fgdata") {
    $CDATROOT = "X:/fgdata";    # 20141109 - 3.3
}
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 in_world_range($$) {
    my ($lt,$ln) = @_;
    return 0 if ($lt < -90);
    return 0 if ($lt >  90);
    return 0 if ($ln < -180);
    return 0 if ($ln >  180);
    return 1;
}
sub in_world($$) {
    my ($lon,$lat) = @_;
    if (($lat < -90)||
        ($lat > 90)||
        ($lon < -180)||
        ($lon > 180)) {
        return 0;
    }
    return 1;
}

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");
    }
}

my $min_nm = 20;
my $M2NM = 0.000539957;
my $swing = 30;
my %inds_used = ();

sub get_route($$$$$);

sub get_nearest($$$$) {
    my ($end,$ra,$rfix,$brng) = @_;
    my $lat = ${$end}[0];
    my $lon = ${$end}[1];
    my $max = scalar @{$ra};
    my ($i,$rf,$dist,$cnt,$flat,$flon,$res,$az1,$az2,$ok);
    my ($nxfix,$nxind,$nxdist);
    my $b1 = $brng + $swing;
    $b1 -= 360 if ($b1 >= 360);
    my $b2 = $brng - $swing;
    $b2 += 360 if ($b2 < 0);
    $cnt = 0;
    for ($i = 0; $i < $max; $i++) {
        next if (defined $inds_used{$i});
        $rf = ${$ra}[$i];
        $flat = ${$rf}[0];
        $flon = ${$rf}[1];
        $res = fg_geo_inverse_wgs_84($lat,$lon,$flat,$flon, \$az1, \$az2, \$dist );
        $ok = 0;
        if ($b1 > $b2) {
            if (($az1 <= $b1)&&
                ($az1 >= $b2)) {
                $ok = 1;
            }
        } else {
            if (($az1 >= $b1)&&
                ($az1 <= $b2)) {
                $ok = 1;
            }
        }
        if ($ok) {
            if ($cnt == 0) {
                $nxdist = $dist;
                $nxfix = $rf;
                $nxind = $i;
            } elsif ($dist < $nxdist) {
                $nxdist = $dist;
                $nxfix = $rf;
                $nxind = $i;
            }
            $cnt++;
            ###prt("az1 $az1 IS between $b1 and $b2\n");
        } else {
            ##prt("az1 $az1 is NOT between $b1 and $b2\n");
        }
    }
    if ($cnt > 0) {
        ${$rfix} = $nxfix;
        $inds_used{$nxind} = 1;
        return 1;
    }
    return 0;
}

sub get_route($$$$$) {
    my ($bgn,$end,$ra,$lev,$pos) = @_;
    my $blat = ${$bgn}[0];
    my $blon = ${$bgn}[1];
    my $bnam = ${$bgn}[2];
    my $elat = ${$end}[0];
    my $elon = ${$end}[1];
    my $enam = ${$end}[2];
    my ($az1,$az2,$dist,$nm,$clat,$clon,$fix,$flat,$flon,$fnam);
    my $res = fg_geo_inverse_wgs_84($blat,$blon,$elat,$elon, \$az1, \$az2, \$dist );
    $nm = ($dist * $M2NM * 10) / 10;
    return if ($nm < $min_nm);
    $res = fg_geo_direct_wgs_84( $blat, $blon, $az1, ($dist / 2), \$clat, \$clon, \$az2 );
    my $nend = [$clat,$clon,'cent'];
    if (get_nearest( $nend, $ra, \$fix, $az1 )) {
        $flat = ${$fix}[0];
        $flon = ${$fix}[1];
        $fnam = ${$fix}[2];
        $nend = [$flat,$flon,$fnam];
        get_route($bgn,$nend,$ra,($lev+1),'T');
        ##############################################################################
        $res = fg_geo_inverse_wgs_84($blat,$blon,$flat,$flon, \$az1, \$az2, \$dist );
        prt("$lev:$pos: From: $bnam $blat,$blon to ");
        prt("Fix: $flat,$flon $fnam ");
        $az1 = int($az1 * 10) / 10;
        $nm = int($dist * $M2NM * 10) / 10;
        prt("On: $az1, $nm nm.\n");
        ##############################################################################
        get_route($nend,$end,$ra,($lev+1),'B');
    }
}

sub add_fix_xg($$$) {
    my ($lat,$lon,$name) = @_;
    my $txt = "anno $lon $lat $name\n";
    return $txt;
}

sub mycmp_decend_n4 {
   return 1 if (${$a}[4] < ${$b}[4]);
   return -1 if (${$a}[4] > ${$b}[4]);
   return 0;
}
sub mycmp_ascend_n4 {
   return 1 if (${$a}[4] > ${$b}[4]);
   return -1 if (${$a}[4] < ${$b}[4]);
   return 0;
}


sub search_fix_bbox() {
    my $ra = load_fix_file();
    my $max = scalar @{$ra};
    ###prt("Searching for $fix, in $max lines of file $fixdata\n") if (VERB9());
    prt("Processing $max fix, get those in box $u_min_lon,$u_min_lat,$u_max_lon,$u_max_lat, fudge=$fudge.\n");
    my ($i,$i2,$line,@arr,$len,$lncnt,$lat,$lon,$name,$dist2);
    $lncnt = 0;
    if ($fudge > 0) {
        $u_min_lon -= $fudge;
        $u_min_lat -= $fudge;
        $u_max_lon += $fudge;
        $u_max_lat += $fudge;
    }
    my @fix_fnd = ();
    my $tmpxg = "# Generated by $pgmname on ".lu_get_YYYYMMDD_hhmmss_UTC(time())."\n";
    $tmpxg .= "color gray\n";
    $tmpxg .= "# bounding box\n";
    $tmpxg .= "$u_min_lon $u_min_lat\n";
    $tmpxg .= "$u_min_lon $u_max_lat\n";
    $tmpxg .= "$u_max_lon $u_max_lat\n";
    $tmpxg .= "$u_max_lon $u_min_lat\n";
    $tmpxg .= "$u_min_lon $u_min_lat\n";
    $tmpxg .= "NEXT\n";
    $tmpxg .= "color yellow\n";
    for ($i = 0; $i < $max; $i++) {
        $lncnt++;
        $i2 = $i + 1;
        $line = ${$ra}[$i];
        $line = trim_all($line);
        @arr = split(/\s+/,$line);
        $len = scalar @arr;
        next if ($len != 3);
        $lat = $arr[0];
        $lon = $arr[1];
        $name = $arr[2];
        if (($lon >= $u_min_lon) &&
            ($lon <= $u_max_lon) &&
            ($lat >= $u_min_lat) &&
            ($lat <= $u_max_lat)) {
            prt("$line\n") if (VERB5());
            push(@fix_fnd, [$lat,$lon,$name]);
            $tmpxg .= add_fix_xg($lat,$lon,$name);
        }
    }
    if ($got_track) {
        $tmpxg .= "# the track\n";
        $tmpxg .= "color red\n";
        $tmpxg .= "$bgn_lon $bgn_lat\n";
        $tmpxg .= "$end_lon $end_lat\n";
        $tmpxg .= "NEXT\n";
    }
    if (length($out_xg)) {
        write2file($tmpxg,$out_xg);
        prt("Written fix xg to $out_xg\n");
    }
    $len = scalar @fix_fnd;
    prt("Found $len fix, in bbox $u_min_lon,$u_min_lat,$u_max_lon,$u_max_lat, fudge=$fudge.\n");
    if ($got_track) {
        my ($az1,$az2,$dist,$nm,$paz1,$clat,$clon,$bgn,$end,$nm2);
        my $res = fg_geo_inverse_wgs_84($bgn_lat,$bgn_lon,$end_lat,$end_lon, \$az1, \$az2, \$dist );
        $paz1 = int(($az1+0.5) * 10) / 10;
        $nm = int($dist * $M2NM * 10) / 10;
        prt("Track is $bgn_lat,$bgn_lon to $end_lat,$end_lon, bearing $paz1, dist $nm nm.\n");
        $bgn = [ $bgn_lat, $bgn_lon, "Bgn" ];
        $end = [ $end_lat, $end_lon, "End" ];
        ### get_route($bgn,$end,\@fix_fnd,0,'S');
        my $p1 = [$bgn_lon,$bgn_lat];
        my $p2 = [$end_lon,$end_lat];
        #my $p1 = [get_radians($bgn_lon),get_radians($bgn_lat)];
        #my $p2 = [get_radians($end_lon),get_radians($end_lat)];
        @arr = ();
        if (VERB5()) {
            prt("Longitude Latitude Name Dist ");
            prt("from start ");
            prt("to track ");
        }
        for ($i = 0; $i < $len; $i++) {
            $ra = $fix_fnd[$i];
            #push(@fix_fnd, [$lat,$lon,$name]);
            $lat = ${$ra}[0];
            $lon = ${$ra}[1];
            $name = ${$ra}[2];
            my $p3 = [$lon,$lat];
            #my $p3 = [get_radians($lon),get_radians($lat)];
            my $p123 = [$p1,$p2,$p3];

            $dist2 = abs(DistanceToLine($p123)) * 1000; # WHAT UNITS ARE THESE??????????
            $nm2 = int($dist2 * 10) / 10;

            $res = fg_geo_inverse_wgs_84($bgn_lat,$bgn_lon,$lat,$lon, \$az1, \$az2, \$dist );
            $nm = int($dist * $M2NM * 10) / 10;
            $az1 = int($az1 * 10) / 10;
            if (VERB5()) {
                prt("$lat $lon $name ");
                prt(sprintf("%5.1f nm, ",$nm));
                prt(sprintf("on %5.1f ",$az1));
                prt(sprintf("%5.1f ",$nm2));
                ###prt("$dist2 ");
                prt("\n");
            }
            #           0    1    2     3      4     5
            push(@arr, [$lon,$lat,$name,$dist2,$dist,$az1]);
        }
        my @narr = sort mycmp_ascend_n4 @arr; 
        $len = scalar @narr;
        prt("\nSorted $len list...\n");
        for ($i = 0; $i < $len; $i++) {
            $ra    = $narr[$i];
            $lon   = ${$ra}[0];
            $lat   = ${$ra}[1];
            $name  = ${$ra}[2];
            $dist2 = ${$ra}[3];
            $dist  = ${$ra}[4];
            $az1   = ${$ra}[5];
            prt("$lat $lon $name ");
            $nm = int($dist * $M2NM * 10) / 10;
            prt(sprintf("%5.1f nm, ",$nm));
            $az1 = int($az1 * 10) / 10;
            prt(sprintf("on %5.1f ",$az1));
            $nm2 = int($dist2 * 10) / 10;
            prt(sprintf("%5.1f ",$nm2));
            prt("\n");
        }


    }
}


#########################################
### MAIN ###
parse_args(@ARGV);
#process_in_file($find_fix);
if ($u_got_bbox) {
    search_fix_bbox();
} else {
    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 get_bbox($) {
    my $bbox = shift;
    my @arr = split(",",$bbox);
    my $cnt = scalar @arr;
    if ($cnt != 4) {
        prt("bbox $bbox failed to split into 4 on comma!\n");
        return 0;
    }
    $u_min_lon = $arr[0];
    $u_min_lat = $arr[1];
    if (!in_world($u_min_lon,$u_min_lat)) {
        prt("min-lon $u_min_lon or min-lat $u_min_lat NOT in world range!\n");
        return 0;
    }
    $u_max_lon = $arr[2];
    $u_max_lat = $arr[3];
    if (!in_world($u_max_lon,$u_max_lat)) {
        prt("max-lon $u_max_lon or max-lat $u_max_lat NOT in world range!\n");
        return 0;
    }
    if ($u_min_lon >= $u_max_lon) {
        prt("min-lon $u_min_lon GTE max-lon $u_max_lon!\n");
        return 0;
    }
    if ($u_min_lat >= $u_max_lat) {
        prt("min-lat $u_min_lat GTE max-lat $u_max_lat!\n");
        return 0;
    }
    $u_got_bbox = 1;
    return 1;
}

sub get_track($) {
    my $bbox = shift;
    my @arr = split(",",$bbox);
    my $cnt = scalar @arr;
    if ($cnt != 4) {
        prt("track $bbox failed to split into 4 on comma!\n");
        return 0;
    }
    $bgn_lat = $arr[0];
    $bgn_lon = $arr[1];
    if (!in_world_range($bgn_lat,$bgn_lon)) {
        prt("bgn-lat $bgn_lat or bgn-lon $bgn_lon NOT in world range!\n");
        return 0;
    }
    $end_lat = $arr[2];
    $end_lon = $arr[3];
    if (!in_world_range($end_lat,$end_lon)) {
        prt("end-lat $end_lat or end-lon $end_lon NOT in world range!\n");
        return 0;
    }
    my ($minlat,$minlon,$maxlat,$maxlon);
    $minlat = $bgn_lat < $end_lat ? $bgn_lat : $end_lat;
    $minlon = $bgn_lon < $end_lon ? $bgn_lon : $end_lon;
    $maxlat = $bgn_lat > $end_lat ? $bgn_lat : $end_lat;
    $maxlon = $bgn_lon > $end_lon ? $bgn_lon : $end_lon;
    $bbox = "$minlon,$minlat,$maxlon,$maxlat";
    if (!get_bbox($bbox)) {
        prt("get_bbox($bbox) failed!\n");
        return 0;
    }
    $got_track = 1;
    return 1;
}

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 =~ /^b/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                if (!get_bbox($sarg)) {
                    pgm_exit(1,"Error: Failed to get min-lon,min-lat,max-lon,max_lat from '$sarg'!\n");
                }
            } elsif ($sarg =~ /^t/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                if (!get_track($sarg)) {
                    pgm_exit(1,"Error: Failed to get bgn-lat,bgn-lon,end-lat,end-lon from '$sarg'!\n");
                }
            } 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) && !$u_got_bbox ) {
            pgm_exit(1,"ERROR: No input 'fix', 'bbox' nor 'track' 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");
    prt(" --bbox <bbox> (-b) = Find all navs within the bounding box.\n");
    prt(" --track <b,e> (-t) = Find all navs along a track, bgn-lat,bgn-lon,end-lat,end-lon.\n");
    prt(" --fudge <deg> (-f) = Expand bbox by this fudge factor. (def=$fudge)\n");
    prt(" bbox = min-lon,min-lat,max-lon,max-lat\n");
    prt(" Default fix file $fixdata ");
    if (-f $fixdata) {
        prt("ok");
    } else {
        prt("NOT FOUND");
    }
    prt("\n");

}

# eof - findfix.pl
