#!/usr/bin/perl
use strict;
use CGI;
use warnings;

my $CGI = new CGI;
my $output;
my $area;
my $aerodrome = $CGI->param('aerodrome');
$/ = "\n";

if ( $CGI->param('area') =~ /^\d\d$/ ) {
  $area = $CGI->param('area');
}

print $CGI->header();
print "<html>\n<head>\n\t<title>Mobile TAF gateway</title>\n</head>\n<body>\n";
print "<!-- area=\"$area\", aerodrome=\"$aerodrome\" -->\n";

my @area = qw(20 21 22 30 32 40 41 43 44 45 50 51 52 53 60 61 62 63 64 65 66 68 69 70 80 83 84 85 86);

print "Select area, then location to retrieve the current TAF:<br>\n<form style=\"display:inline;\" action=\"taf.pl\" method=\"post\"><select name=\"area\">\n";
foreach my $a (@area) {
  if ( $area eq $a ) {
    $output .= "\t<option selected name=\"$a\">$a</option>\n";
  } else {
    $output .= "\t<option name=\"$a\">$a</option>\n";
  }
}
print "$output</select>" . $CGI->submit("Show Locations") . "</form><br>";

if ( $area ) {
  print "<form style=\"display:inline;\" action=\"taf.pl\" method=\"post\">\n" . $CGI->hidden("area","$area") . "\n<select name=\"aerodrome\">\n";
  open FILE, " < area${area}_tafmet.shtml ";
  while (<FILE>) {
    #print "<!-- line = \"$_\" -->\n";
    if ( /td colspan=\"?2\"? valign=\"?to/) {
      chomp();
      s/<.{2,3}>//g;
      s/<td width="5%">.*$//g;
      s/<.*>//;
      s/\s+$//;
      s/\s{2,20}/ /g;
      s/\*//;
      if ( $aerodrome eq "$_" ) {
        print "<option selected name=\"$_\">$_</option>\n";
      } else {
        print "<option name=\"$_\">$_</option>\n";
      }
    }
  }
  print "</select>\n" . $CGI->submit("Get TAF") . "</form>";
}

if ( $aerodrome ) {
  print "<hr>\n<pre>TAF for $aerodrome:\n\n";
  my $url = "http://reg.bom.gov.au/products/reg/area" . $area . "_tafmet.shtml";
  my @html = `curl --user bomw0007:aviation $url`;
  my $line;
  my $state = 0;
  foreach $line ( @html ) {
    if ( $state == 0 ) {
      my $origline = $line;
      chomp($line);
      $line =~ s/<\/?..>//g;
      $line =~ s/\s+$//g;
      $line =~ s/\s+/ /g;
      #print "<!-- aerodrome = \"$aerodrome\", state = \"$state\", line = \"$line\" -->\n";
      if ( $line =~ /$aerodrome/ ) {
        $state = 1;
        $origline =~ s/^.*<pre>//;
        print "$origline";
        next;
      }
    }

    if ( $state == 1 ) {
      #print "<!-- aerodrome = \"$aerodrome\", state = \"$state\", line = \"$line\" -->\n";
      if ( $line =~ /td colspan=\"?2\"? valign=\"?to/ ) {
        $state = 0;
      } else {
        $line =~ s/<.{2}>//g;
        $line =~ s/<\/.{2}>//g;
        $line =~ s/.*<td width="5%">.*//g;
        $line =~ s/\s+$//g;
        $line =~ s/\s+/ /g;
        if (( $line !~ /^\s$/ ) && ( $line ne "" )) { print "$line\n"; }
      }
    }
  }
  print "<hr><font size=\"-1\">TAFs obtained from the Bureau of Meteorology<br><a href=\"index.html\">Back to Steves Mobile Resources</a></font>\n";
}

print "</body>\n</html>\n";

