#!/usr/bin/perl
# Builds a list of countries, sorted into regions.
use strict;
use warnings;

# Parameters.
my $iso3166tab=shift;
my $regionmap=shift;

# These are the regions to use. This specifies what order should be used.
# The use of gettext is only so that this file can contribute to the po
# files.
my @regions = (
	gettext("-- North America --"),
	gettext("-- Central America --"),
	gettext("-- South America --"),
	gettext("-- Caribbean --"),
	gettext("-- Europe --"),
	gettext("-- Asia --"),
	gettext("-- Africa --"),
	gettext("-- Atlantic Ocean --"),
	gettext("-- Indian Ocean --"),
	gettext("-- Oceania --"),
	gettext("-- Antarctica --"),
	gettext("-- other --"),
);

my %code2country;
my %codes_listed;
open (L, $iso3166tab) || die "$iso3166tab: $!";
while (<L>) {
	chomp;
	my ($code, $country) = split(' ', $_, 2);
	# Bubulle 5/25/2004 We should find a way to avoid enforcing ASCII
	# here
	if ($country !~ /^[-_A-Za-z0-9 !@#$%^&Z*()-_+={};:'",.<>?|]+$/) {
		print STDERR "Skipping country $country; not ASCII\n";
		next;
	}
	$code2country{$code}=$country;
	$codes_listed{$code}=0;
}

my %regions;
open (R, $regionmap) || die "$regionmap: $!";
while (<R>) {
	chomp;
	my ($code, $region) = split(' ', $_, 2);
	if (exists $code2country{$code}) {
		push @{$regions{$region}}, $code2country{$code};
		$codes_listed{$code}++;
	}
	elsif ($code ne 'unlisted') {
		print STDERR "skipping unknown country code, $code, in $regionmap but not in $iso3166tab\n";
	}
}
close R;

# Add any unlisted countries to "other".
foreach my $code (keys %codes_listed) {
	if ($codes_listed{$code} == 0) {
		push @{$regions{"-- other --"}}, $code2country{$code};
		print STDERR "unknown region for country $code, not in $regionmap\n";
	}
}

foreach my $region (@regions) {
	if (exists $regions{$region}) {
		print "$region\n";
		foreach my $country (sort @{$regions{$region}}) {
			print "$country\n";
		}
		delete $regions{$region};
	}
	else {
		print STDERR "skipping region $region; not in $regionmap\n";
	}
}

if (%regions) {
	print STDERR "skipping the following unlisted regions: ".
		join(" ", keys %regions)."\n";
}

# Dummy.
sub gettext {
	return shift;
}
