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

my $CGI = new CGI;
my $output;
my $area;
$/ = "\n";

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

print $CGI->header();
print "<html>\n<head>\n\t<title>Mobile ARFOR gateway</title>\n</head>\n<body>\n";
print "<!-- area=\"$area\" -->\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 to retrieve the current ARFOR:<br>\n<form style=\"display:inline;\" action=\"arfor.pl\" method=\"post\"><select name=\"area\">\n";
foreach $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("Get ARFOR") . "</form><br>";

if ( $area ) {
  my $url = "http://reg.bom.gov.au/products/reg/area" . $area . "_arf.shtml";
  my @html = `curl --user bomw0007:aviation $url`;

  print "<hr>Area Forcast: AREA $area\n<pre>";

  my $state = 0;
  my $line;
  foreach $line (@html) {
    if ( $state == 0 && $line =~ /^<pre>/ ) {
      $state = 1;
    }

    if ( $state == 1 ) {
      if ( $line =~ /^<\/pre>/ ) {
        $state = 0;
      } else {
        $line =~ s/<.{2,3}>//g;
        $line =~ s/<\/.{2,3}>//g;
        print $line;
      }
    }
  }

  print "</pre>\n<hr><font size=\"-1\">ARFOR obtained from the Bureau of Meteorology<br><a href=\"index.html\">Back to Steves Mobile Resources</a></font>\n";
}

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

