#!/perl -w
# listap01.pl
# AIM: Read FlightGear apt.dat.gz file, and list AIRPORTS within ...
use strict;
use warnings;
use Env qw(HOME FG_ROOT);	# for reading HOME and FG_ROOT
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $outfile = 'temp.'.$0.'.txt';
if ($0 =~ /\w{1}:\\.*/) {
	my @tmpsp = split(/\\/,$0);
	$outfile = 'temp.'.($tmpsp[-1]).'.txt';
}
open_log($outfile);
prt( "$0 ... Hello, World ...\n" );

# other variables
my $FGROOT = (exists $ENV{FG_ROOT}) ? $FG_ROOT : "F:\\FG0910-4\\data";
my $APTFILE 	  = "$FGROOT/Airports/apt.dat.gz";	# the airports data file
my @aptlist = ();
my $acnt = 0;
my $scnt = 0;
my $apt = '';
my $rwy = '';
my $rcnt = 0;
my $mxrcnt = 50;
# degug stuff
my $dbg1 = 0; # show airport line from file ...
my $dbg2 = 0; # show breakdown of airport line ...
my $dbg3 = 1; # show runway/taxiway line ...

prt( "Opening, and scanning [$APTFILE] ...\n" );
# if the airport data file exists, it is opened, otherwise the script stop
if ( -e $APTFILE ) {
	open (APT, "gzip -d -c $APTFILE|") or die "I can't open $APTFILE\n" ;
} else {
	mydie ("ERROR: File $APTFILE does not exist ...\n" );
}
# we look inside the file to find our airports
while (<APT>) {
	# 1   3799 0 0 E46  02 Ranch
	if (/^1\s+\d+\s\d\s\d\s(\w+)\s(.+)/ ) {
		chomp;
		$apt = $_;
		### my @aptheader = split (/\s+/, $_, 6);
		my @aptheader = split (/\s+/, $apt, 6);
		push(@aptlist, \@aptheader);
		prt( "$apt ...\n" ) if ($dbg1);
		if ($dbg2) {
			foreach my $a (@aptheader) {
				prt("[$a] ");
			}
			prt("\n");
		}
	} elsif (/^10\s+\d+(.+)/) {
		# 1   2         3           4    5       6       7         8       9   10     11 121314   15
		# 10  29.874897 -103.697127 05x  50.00   3500    0.0000    0.0000  100 111111 04 0 0 0.25 0
		chomp;
		$rwy = $_;
		my @rwylist = split (/\s+/, $rwy);
		$scnt = scalar @rwylist;
		if ($rwylist[3] ne 'xxx') {
			prt( "$rwy ...($scnt)\n" ) if ($dbg3);
			$rcnt++;
			if ($rcnt > $mxrcnt) {
				last;
			}
		}
	}
}
close APT;
$acnt = scalar @aptlist;
prt( "Got list of $acnt airports ...\n" );

close_log($outfile,1);
exit(0);

# eof
