#!/usr/bin/perl -w
# NAME: findaps.pl
# AIM: There is a BIG findap[nn].pl - This is a SIMPLER version
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 '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";
require "Bucket2.pm" or die "Unable to load Bucket2.pm ...\n";
my $CDATROOT="C:/FGCVS/FlightGear/data";
# my $CDATROOT="C:/FGCVS/FlightGear/data";
# =============================================================================
# This NEEDS to be adjusted to YOUR particular default location of these files.
my $FGROOT = (exists $ENV{'FG_ROOT'})? $ENV{'FG_ROOT'} : $CDATROOT;
#my $FGROOT = (exists $ENV{'FG_ROOT'})? $ENV{'FG_ROOT'} : "C:/FG/27/data";
# file spec : http://data.x-plane.com/file_specs/Apt810.htm
my $APTFILE 	  = "$FGROOT/Airports/apt.dat.gz";	# the airports data file
my $NAVFILE 	  = "$FGROOT/Navaids/nav.dat.gz";	# the NAV, NDB, etc. data file
# add these files
my $FIXFILE 	  = "$FGROOT/Navaids/fix.dat.gz";	# the FIX data file
my $AWYFILE       = "$FGROOT/Navaids/awy.dat.gz";   # Airways data
# =============================================================================

my $MY_F2M = 0.3048;
my $MY_M2F = 3.28083989501312335958;
my $SG_METER_TO_NM = 0.0005399568034557235;

# log file stuff
our ($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 $VERS = "0.0.1 2011-11-27";
my $load_log = 0;
my $in_icao = '';
my $verbosity = 0;
my $debug_on = 0;
my $del_icao = 'KTEX';
my $out_xml = '';

my $aptdat = $APTFILE;
my $navdat = $NAVFILE;
my $g_fixfile = $FIXFILE;
my $g_awyfile = $AWYFILE;

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

# apt.dat.gz CODES - see http://x-plane.org/home/robinp/Apt810.htm for DETAILS
my $aln =     '1';	# airport line
my $rln =    '10';	# runways/taxiways line
my $sealn =  '16'; # Seaplane base header data.
my $heliln = '17'; # Heliport header data.  
my $twrln =  '14'; # Tower view location. 
my $rampln = '15'; # Ramp startup position(s) 
my $bcnln =  '18'; # Airport light beacons  
my $wsln =   '19'; # windsock

# Radio Frequencies # AWOS (Automatic Weather Observation System), ASOS (Automatic Surface Observation System)
my $minatc = '50'; # ATIS (Automated Terminal Information System). AWIS (Automatic Weather Information Service)
my $unicom = '51'; # Unicom or CTAF (USA), radio (UK) - open channel for pilot position reporting at uncontrolled airports.
my $cleara = '52'; # Clearance delivery.
my $goundf = '53'; # ground
my $twrfrq = '54';	# like 12210 TWR
my $appfrq = '55';  # like 11970 ROTTERDAM APP
my $maxatc = '56'; # Departure.
my %off2name = (
    0 => 'ATIS',
    1 => 'Unicom',
    2 => 'Clearance',
    3 => 'Ground',
    4 => 'Tower',
    5 => 'Approach',
    6 => 'Departure'
);

# offset 10 in runway array
my %runway_surface = (
    1  => 'Asphalt',
    2  => 'Concrete',
    3  => 'Turf/grass',
    4  => 'Dirt',
    5  => 'Gravel',
    6  => 'H-Asphalt', # helepad (big 'H' in the middle).
    7  => 'H-Concrete', # helepad (big 'H' in the middle).
    8  => 'H-Turf', # helepad (big 'H' in the middle).
    9  => 'H-Dirt', # helepad (big 'H' in the middle). 
    10 => 'T-Asphalt', # taxiway - with yellow hold line across long axis (not available from WorldMaker).
    11 => 'T-Concrete', # taxiway - with yellow hold line across long axis (not available from WorldMaker).
    12 => 'Dry Lakebed', # (eg. at KEDW Edwards AFB).
    13 => 'Water' # runways (marked with bobbing buoys) for seaplane/floatplane bases (available in X-Plane 7.0 and later). 
);

# =====================================================================================================
my $lastln = '99'; # end of file

# program variables
my @g_aptlist = ();
my $totaptcnt = 0;
my $totrwycnt = 0;

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

#//////////////////////////////////////////////////////////////////////
#//
#// Convert a cartexian XYZ coordinate to a geodetic lat/lon/alt.
#// This function is a copy of what's in SimGear,
#//  simgear/math/SGGeodesy.cxx.
#//
#////////////////////////////////////////////////////////////////////////
#// High-precision versions of the above produced with an arbitrary
#// precision calculator (the compiler might lose a few bits in the FPU
#// operations).  These are specified to 81 bits of mantissa, which is
#// higher than any FPU known to me:
my $SGD_PI = 3.1415926535;

my $SQUASH  = 0.9966471893352525192801545;
my $STRETCH = 1.0033640898209764189003079;
my $POLRAD  = 6356752.3142451794975639668;

my $SG_RAD_TO_NM  = 3437.7467707849392526;
my $SG_NM_TO_METER  = 1852.0000;
my $SG_METER_TO_FEET  = 3.28083989501312335958;
my $SGD_PI_2    = 1.57079632679489661923;
my $SG_RADIANS_TO_DEGREES = 180.0 / $SGD_PI;

my $EQURAD = 6378137.0;

my $E2 = abs(1 - ($SQUASH*$SQUASH));
my $ra2 = 1/($EQURAD*$EQURAD);
my $e2 = $E2;
my $e4 = $E2*$E2;

#//////////////////////////////////////////////////////////////////////
#//  This is the inverse of the algorithm in localLat().  It
#//  returns the (cylindrical) coordinates of a surface latitude
#//  expressed as an "up" unit vector.
#//////////////////////////////////////////////////////////////////////
#static void surfRZ (double upr, double upz, double* r, double* z)
sub surfRZ($$$$) {
    my ($upr,$upz,$rr,$rz) = @_;
    # // We are
    #// converting a (2D, cylindrical) "up" vector defined by the
    #// geodetic latitude into unitless R and Z coordinates in
    #// cartesian space.
    my $R = $upr * $STRETCH;
    my $Z = $upz * $SQUASH;
    #// Now we need to turn R and Z into a surface point.  That is,
    #// pick a coefficient C for them such that the point is on the
    #// surface when converted to "squashed" space:
    #//  (C*R*SQUASH)^2 + (C*Z)^2 = POLRAD^2
    #//   C^2 = POLRAD^2 / ((R*SQUASH)^2 + Z^2)
    my $sr = $R * $SQUASH;
    my $c = $POLRAD / sqrt($sr*$sr + $Z*$Z);
    $R *= $c;
    $Z *= $c;
    ${$rr} = $R;
    ${$rz} = $Z;
}   #// surfRZ()
#//////////////////////////////////////////////////////////////////////

# void sgCartToGeod ( const Point3D& CartPoint , Point3D& GeodPoint )
sub sgCartToGeod($$) {
    my ($rCartPoint,$rGeodPoint) = @_;
    #// according to
    #// H. Vermeille,
    #// Direct transformation from geocentric to geodetic ccordinates,
    #// Journal of Geodesy (2002) 76:451-454
    my $x = ${$rCartPoint}[0];
    my $y = ${$rCartPoint}[1];
    my $z = ${$rCartPoint}[2];
    my $XXpYY = $x*$x+$y*$y;
    my $sqrtXXpYY = sqrt($XXpYY);
    my $p = $XXpYY*$ra2;
    my $q = $z*$z*(1-$e2)*$ra2;
    my $r = 1/6.0*($p+$q-$e4);
    my $s = $e4*$p*$q/(4*$r*$r*$r);
    my $t = pow(1+$s+sqrt($s*(2+$s)), 1/3.0);
    my $u = $r*(1+$t+1/$t);
    my $v = sqrt($u*$u+$e4*$q);
    my $w = $e2*($u+$v-$q)/(2*$v);
    my $k = sqrt($u+$v+$w*$w)-$w;
    my $D = $k*$sqrtXXpYY/($k+$e2);
    ${$rGeodPoint}[0] = (2*atan2($y, $x+$sqrtXXpYY)) * $SG_RADIANS_TO_DEGREES; # lon
    my $sqrtDDpZZ = sqrt($D*$D+$z*$z);
    ${$rGeodPoint}[1] = (2*atan2($z, $D+$sqrtDDpZZ)) * $SG_RADIANS_TO_DEGREES; # lat
    ${$rGeodPoint}[2] = (($k+$e2-1)*$sqrtDDpZZ/$k) * $SG_METER_TO_FEET;        # alt
}   #// sgCartToGeod()

#//////////////////////////////////////////////////////////////////////
#// opposite of sgCartToGeod
#//////////////////////////////////////////////////////////////////////
#void sgGeodToCart ( double lat, double lon, double alt, double* xyz )
sub sgGeodToCart($$$$) {
    my ($lat, $lon, $alt, $rxyz) = @_;
    #// This is the inverse of the algorithm in localLat().  We are
    #// converting a (2D, cylindrical) "up" vector defined by the
    #// geodetic latitude into unitless R and Z coordinates in
    #// cartesian space.
    my $upr = cos($lat);
    my $upz = sin($lat);
    my ($r, $z);
    surfRZ($upr, $upz, \$r, \$z);
    #// Add the altitude using the "up" unit vector we calculated
    #// initially.
    $r += $upr * $alt;
    $z += $upz * $alt;
    #// Finally, convert from cylindrical to cartesian
    ${$rxyz}[0] = $r * cos($lon);
    ${$rxyz}[1] = $r * sin($lon);
    ${$rxyz}[2] = $z;
}   #// sgGeodToCart()
#//////////////////////////////////////////////////////////////////////

# LOAD apt.dat.gz
# details see : http://data.x-plane.com/file_specs/Apt810.htm
# Line codes used in apt.dat (810 version) 
# Airport Line - eg 
# 0  1    2   3   4    5++
# 1  1050 0   0   YGIL Gilgandra
# ID AMSL Twr Bld ICAO Name
# Code (apt.dat) Used for 
# 1 Airport header data. 
# 16 Seaplane base header data. No airport buildings or boundary fences will be rendered in X-Plane. 
# 17 Heliport header data.  No airport buildings or boundary fences will be rendered in X-Plane. 
# 10 Runway or taxiway at an airport. 
# 14 Tower view location. 
# 15 Ramp startup position(s) 
# 18 Airport light beacons (usually "rotating beacons" in the USA).  Different colours may be defined. 
# 19 Airport windsocks. 
# 50 to 56 Airport ATC (Air Traffic Control) frequencies. 
# runway
# 0  1           2          3   4       5    6         7             8 9      10  11   12    13    14     15
# 10 -31.696928  148.636404 15x 162.00  4204 0000.0000 0000.0000    98 121121  5   0    2    0.25   0     0000.0000
# rwy lat        lon        num true    feet displament/extension  wid lights surf shld mark smooth signs VASI
sub load_apt_data {
    my ($cnt,$msg);
    prt("[v9] Loading $aptdat file ...\n") if (VERB9());
    mydie("ERROR: Can NOT locate $aptdat ...$!...\n") if ( !( -f $aptdat) );
    ###open IF, "<$aptdat" or mydie("OOPS, failed to open [$aptdat] ... check name and location ...\n");
    open IF, "gzip -d -c $aptdat|" or mydie( "ERROR: CAN NOT OPEN $aptdat...$!...\n" );
    my @lines = <IF>;
    close IF;
    $cnt = scalar @lines;
    prt("[v9] Got $cnt lines to scan...\n") if (VERB9());
    my ($add,$alat,$alon);
    $add = 0;
    my ($off,$atyp,$az,@arr,@arr2,$rwyt,$glat,$glon,$rlat,$rlon);
    my ($line,$apt,$diff,$rwycnt,$icao,$name,@runways,$version);
    my ($aalt,$actl,$abld,$ftyp,$cfrq,$frqn,@freqs);
    $off = 0;
    $az = 0;
    $glat = 0;
    $glon = 0;
    $apt = '';
    $rwycnt = 0;
    @runways = ();
    @freqs = ();
    $msg = '[v1] ';
    #$msg .= "Search ICAO [$apticao]...";
    $msg .= " got $cnt lines, FOR airports,rwys,txwys... ";
    foreach $line (@lines) {
        $line = trim_all($line);
        if ($line =~ /\s+Version\s+/i) {
            @arr2 = split(/\s+/,$line);
            $version = $arr2[0];
            $msg .= "Version $version";
            last;
        }
    }
    prt("$msg\n") if (VERB1());
    my $lncnt = 0;
    foreach $line (@lines) {
        $lncnt++;
        $line = trim_all($line);
        ###prt("$line\n");
        my @arr = split(/ /,$line);
        if (($line =~ /^$aln\s+/)||	    # start with '1'
            ($line =~ /^$sealn\s+/)||   # =  '16'; # Seaplane base header data.
            ($line =~ /^$heliln\s+/)) { # = '17'; # Heliport header data.  
            # 0  1   2 3 4     
            # 17 126 0 0 EH0001 [H] VU medisch centrum
            # ID ALT C B NAME++
            if (length($apt)) {
                if ($rwycnt > 0) {
                    # average position
                    $alat = $glat / $rwycnt;
                    $alon = $glon / $rwycnt;
                    $off = -1;
                    $az = 400;
                    @arr2 = split(/ /,$apt);
                    $atyp = $arr2[0]; # airport, heleiport, or seaport
                    $aalt = $arr2[1]; # Airport (general) ALTITUDE AMSL
                    $actl = $arr2[2]; # control tower
                    $abld = $arr2[3]; # buildings
                    $icao = $arr2[4]; # ICAO
                    $name = join(' ', splice(@arr2,5)); # Name
                    ##prt("$diff [$apt] (with $rwycnt runways at [$alat, $alon]) ...\n");
                    ##prt("$diff [$icao] [$name] ...\n");
                    #push(@g_aptlist, [$diff, $icao, $name, $alat, $alon, -1, 0, 0, 0, $icao, $name, $off, $dist, $az]);
                    my @f = @freqs;
                    my @r = @runways;
                    #                 0      1      2      3      4      5      6    7
                    push(@g_aptlist, [$atyp, $icao, $name, $alat, $alon, $aalt, \@f, \@r]);
                    ### prt("[v9] $icao, $name, $alat, $alon, $aalt, $rwycnt runways\n") if (VERB9());
                } else {
                    prtw("WARNING: Airport with NO runways! $icao, $name, $alat, $alon, $aalt\n");
                }
            }
            $apt = $line;
            $rwycnt = 0;
            @runways = ();  # clear RUNWAY list
            @freqs = (); # clear frequencies
            $glat = 0;
            $glon = 0;
            $totaptcnt++;	# count another AIRPORT
        } elsif ($line =~ /^$rln\s+/) {
            # 10  36.962213  127.031071 14x 131.52  8208 1595.0620 0000.0000   150 321321  1 0 3 0.25 0 0300.0300
            # 10  36.969145  127.020106 xxx 221.51   329 0.0 0.0    75 161161  1 0 0 0.25 0 
            $rlat = $arr[1];
            $rlon = $arr[2];
            $rwyt = $arr[3]; # text 'xxx'=taxiway, 'H1x'=heleport, else a runway
            ###prt( "$line [$rlat, $rlon]\n" );
            if ( $rwyt ne "xxx" ) {
                $glat += $rlat;
                $glon += $rlon;
                $rwycnt++;
                push(@runways, \@arr);
                $totrwycnt++;
            }
        } elsif ($line =~ /^5(\d+)\s+/) {
            # frequencies
            $ftyp = $1;
            $cfrq = $arr[1];
            $frqn = $arr[2];
            $add = 0;
            if ($ftyp == 0) {
                $add = 1; # ATIS
            } elsif ($ftyp == 1) {
                $add = 1; # Unicom
            } elsif ($ftyp == 2) {
                $add = 1; # clearance
            } elsif ($ftyp == 3) {
                $add = 1; # ground
            } elsif ($ftyp == 4) {
                $add = 1; # tower
            } elsif ($ftyp == 5) {
                $add = 1; # approach
            } elsif ($ftyp == 6) {
                $add = 1; # departure
            }
            if ($add) {
                push(@freqs, \@arr); # save the freq array
            } else {
                pgm_exit(1, "WHAT IS THIS [5$ftyp $cfrq $frqn] [$line]\n FIX ME!!!");
            }
        } elsif ($line =~ /^$lastln\s?/) {	# 99, followed by space, count 0 or more ...
            prt( "Reached END OF FILE ... \n" ) if (VERB9());
            last;
        }
    }

    # do any LAST entry
    $add = 0;
    $off = -1;
    $az = 0;
    if (length($apt) && ($rwycnt > 0)) {
        $alat = $glat / $rwycnt;
        $alon = $glon / $rwycnt;
        $off = -1;
        $az = 400;
        #$off = near_given_point( $alat, $alon, \$dist, \$az );
        #$dlat = abs( $c_lat - $alat );
        #$dlon = abs( $c_lon - $alon );
        #$diff = int( ($dlat * 10) + ($dlon * 10) );
        @arr2 = split(/ /,$apt);
        $atyp = $arr2[0];
        $aalt = $arr2[1];
        $actl = $arr2[2]; # control tower
        $abld = $arr2[3]; # buildings
        $icao = $arr2[4];
        $name = join(' ', splice(@arr2,5));
        ###prt("$diff [$apt] (with $rwycnt runways at [$alat, $alon]) ...\n");
        ###prt("$diff [$icao] [$name] ...\n");
        ###push(@g_aptlist, [$diff, $icao, $name, $alat, $alon]);
        ##push(@g_aptlist, [$diff, $icao, $name, $alat, $alon, -1, 0, 0, 0, $icao, $name, $off, $dist, $az]);
        my @f = @freqs;
        my @r = @runways;
        #                 0      1      2      3      4      5      6    7
        push(@g_aptlist, [$atyp, $icao, $name, $alat, $alon, $aalt, \@f, \@r]);
        $totaptcnt++;	# count another AIRPORT
    }
    $cnt =scalar @g_aptlist;
    prt("[v9] Done scan of $lncnt lines for $cnt airports, $totrwycnt runways...\n") if (VERB9());
}

sub mycmp_decend_dist {
   return -1 if (${$a}[8] < ${$b}[8]);
   return 1 if (${$a}[8] > ${$b}[8]);
   return 0;
}

sub set_lat_stg($) {
    my ($rl) = @_;
    ${$rl} = sprintf("%2.7f",${$rl});
}

sub set_lon_stg($) {
    my ($rl) = @_;
    ${$rl} = sprintf("%3.7f",${$rl});
}

sub process_in_icao($) {
    my ($find_icao) = @_;
    load_apt_data();
    my $rapts = \@g_aptlist;
    my @found = ();
    my $cnt = scalar @{$rapts};
    ##                 0      1      2      3      4      5      6    7
    #push(@g_aptlist, [$diff, $icao, $name, $alat, $alon, $aalt, \@f, \@r]);
    my ($i,$atyp,$icao,$name,$alat,$alon,$aalt,$rfreq,$rrwys,$rwycnt,$len);
    prt("Searching $cnt airports for ICAO [$find_icao]...\n") if (VERB1());
    my $minn = 0;
    for ($i = 0; $i < $cnt; $i++) {
        $atyp = ${$rapts}[$i][0];
        $icao = ${$rapts}[$i][1];
        $name = ${$rapts}[$i][2];
        $alat = ${$rapts}[$i][3];
        $alon = ${$rapts}[$i][4];
        $aalt = ${$rapts}[$i][5];
        $rfreq = ${$rapts}[$i][6];
        $rrwys = ${$rapts}[$i][7];
        if ($icao eq $find_icao) {
            $rwycnt = scalar @{$rrwys};
            prt("[v1] Found $icao, $name, $alat, $alon, $aalt, $rwycnt runways\n") if (VERB1());
            push(@found, $i);
        }
        $len = length($name);
        $minn = $len if ($len > $minn);
    }
    if (!@found) {
        prt("No airport found with ICAO of $find_icao!\n");
        return;
    }
    if (scalar @found > 1) {
        prtw("WARNING: Found ".scalar @found." matching ICAO!\n");
    }
    my $fnd = $found[0];
    $i = $fnd;
    my ($fatyp,$ficao,$fname,$falat,$falon,$faalt,$frfreq,$frrwys,$frwycnt);
    $fatyp = ${$rapts}[$i][0];
    $ficao = ${$rapts}[$i][1];
    $fname = ${$rapts}[$i][2];
    $falat = ${$rapts}[$i][3];
    $falon = ${$rapts}[$i][4];
    $faalt = ${$rapts}[$i][5];
    $frfreq = ${$rapts}[$i][6];
    $frrwys = ${$rapts}[$i][7];
    ${$rapts}[$i][8] = 0;
    my ($s,$az1,$az2,$distnm);
    ##                 0      1      2      3      4      5      6    7
    #push(@g_aptlist, [$diff, $icao, $name, $alat, $alon, $aalt, \@f, \@r]);
    for ($i = 0; $i < $cnt; $i++) {
        next if ($i == $fnd);
        $alat = ${$rapts}[$i][3];
        $alon = ${$rapts}[$i][4];
        #sub fg_geo_inverse_wgs_84 {
        #my ($lat1, $lon1, $lat2, $lon2, $az1, $az2, $s) = @_;
        fg_geo_inverse_wgs_84($falat,$falon,$alat,$alon,\$az1,\$az2,\$s);
        ${$rapts}[$i][8] = $s;
    }
    my @newarr = sort mycmp_decend_dist @{$rapts};
    $rapts = \@newarr;
    my $max = 20;
    my $done = 0;
    my $xhele = 1;
    my $xsea = 1;
    my $xold = 1;
    $minn = 0;
    for ($i = 0; $i < $cnt; $i++) {
        $name = ${$rapts}[$i][2];
        next if (($name =~ /\[H\]/) && $xhele);
        next if (($name =~ /\[S\]/) && $xsea);
        next if (($name =~ /\[X\]/) && $xold);
        $len = length($name);
        $minn = $len if ($len > $minn);
        $done++;
        last if ($done == $max);
    }
    $done = 0; # restart done counter
    for ($i = 0; $i < $cnt; $i++) {
        $atyp = ${$rapts}[$i][0];
        $icao = ${$rapts}[$i][1];
        $name = ${$rapts}[$i][2];
        $alat = ${$rapts}[$i][3];
        $alon = ${$rapts}[$i][4];
        $aalt = ${$rapts}[$i][5];
        $rfreq = ${$rapts}[$i][6];
        $rrwys = ${$rapts}[$i][7];
        $s     = ${$rapts}[$i][8];
        next if (($name =~ /\[H\]/) && $xhele);
        next if (($name =~ /\[S\]/) && $xsea);
        next if (($name =~ /\[X\]/) && $xold);
        $distnm = $s * $SG_METER_TO_NM;
        $distnm = (int($distnm * 10) / 10);
        if ($distnm == int($distnm)) {
            $distnm .= ".0";
        }
        $distnm = ' '.$distnm while (length($distnm) < 7);
        $name .= ' ' while (length($name) < $minn);
        $icao .= ' ' while (length($icao) < 4);
        set_lat_stg(\$alat);
        set_lon_stg(\$alon);
        $aalt = ' '.$aalt while (length($aalt) < 6);
        prt("$icao, $name, $alat, $alon, $aalt, $distnm\n");
        $done++;
        last if ($done == $max);
    }
}

#########################################
### MAIN ###
parse_args(@ARGV);
### prt( "$pgmname: in [$cwd]: Hello, World...\n" );
process_in_icao($in_icao);
pgm_exit(0,"");
########################################
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");
}

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 =~ /^l/) {
                $load_log = 1;
                prt("Set to load log at end.\n") if (VERB1());
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_xml = $sarg;
                prt("Set out file to [$out_xml].\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_icao = $arg;
            prt("Set input to [$in_icao]\n");
        }
        shift @av;
    }

    if ((length($in_icao) ==  0) && $debug_on) {
        $in_icao = $del_icao;
        $verbosity = 9;
    }
    if (length($in_icao) ==  0) {
        pgm_exit(1,"ERROR: No input files found in command!\n");
    }
}

# eof - findaps.pl
