#!/usr/bin/perl -wT --

use strict;

# List METAR-stations from NOAA
my %noaaStations;
open (FILE, "/tmp/index.html") or
	die "Cannot read NOAA METAR db. $?";
while (<FILE>) {
	next if (!/href="(\w{4})\.\w{3}"/);
	$noaaStations{$1} = 1;
#	print "$1\n";
}
close (FILE);

# Check against bot's METAR-list
open (FILE, "iSaa.METAR-cities.txt") or
	die "Cannot read bot's METAR db. $?";
my $country = "";
while (<FILE>) {
	# Comments
	if (/^#/) {
		print $_;
		next;
	}

	# Blank line terminates a country
	if (/^$/) {
		my $newStations = 0;
		foreach (keys(%noaaStations)) {
			next if (!$noaaStations{$_});
			next if ($country eq "" || !/^$country/);

			if ($newStations == 0) {
				print "# New stations\n";
			}
			$noaaStations{$_} = 0;
			print "$_;\n";
			++$newStations;
		}
		# Reset country
		$country = "";

		# This was an empty line. Print one.
		print "\n";
		next;
	}

	# Anything else, we must assume it is a METAR station
	die "Bad station $_!" if (!/^(\w{4});(.+)$/);
	if (!defined($noaaStations{$1})) {
		print "#$1;$2\n";
		next;
	}

	my $station = $1;
	my $description = $2;
	$country = $1 if ($station =~ /^(\w{2})\w{2}$/);

	if (!$noaaStations{$station}) {
		warn "Station $station appears twice!";
		print "#dup $station;$description\n";
		next;
	}

	# Check this station as processed
	$noaaStations{$station} = 0;
	print $_;
}
close (FILE);

# Print out any stations which have not been processed yet
my $newStations = 0;
foreach (keys(%noaaStations)) {
	next if (!$noaaStations{$_});

	if ($newStations == 0) {
		print "\n\n#\n# New stations\n";
	}
	print "$_;\n";
	++$newStations;
}
