#!/usr/bin/perl -w

use strict;
use Template;

use locale;
use POSIX qw(locale_h);
setlocale(LC_ALL, "sv_SE");


open MAP, "map.txt" or die $!;

# exit abbrevations
my $exab =
{
 N  => 'Norr',
 E  => 'Öster',
 S  => 'Söder',
 W  => 'Väster',
 NE => 'Nordöst',
 SE => 'Sydöst',
 SW => 'Sydväst',
 NW => 'Nordväst',
 U  => 'Upp',
 D  => 'Ned',
 B  => 'Tillbaka',
 R  => 'Höger',
 L  => 'Vänster',
};

my $place = {};

my $tmpl = Template->new({INCLUDE_PATH=>'tmpl'});

my $line = <MAP>;
PLACE:
while($line)
{
    $line =~ /^\* (\-?\d+) (.*?)\s*$/ or die "faulty header: $line\n";
    my $id = $1;
    my $name = $2;
    my $desc;
    my $pdirs = {};
    my $sdirs = {};
    my $dir;

    print "Processing $id\n";

    if( $name =~ /^(\w+)(.*)/ and $exab->{$1} )
    {
	$name = $exab->{$1} .":". $2;
	$dir = $1;
    }

    $line = <MAP>;
 DIR:
    while($line)
    {
	chomp $line;
	if( $line =~ /^\=\s*(.*)/ )
	{
	    $desc = $1;
	    print "  got desc\n";
	}
	elsif( length $line )
	{
	    $line =~ /^(.*?) (\-?\d+)\s*$/ or die "Faulty dir: $line";
	    if( $exab->{$1} )
	    {
		$pdirs->{$1} = $2;
	    }
	    else
	    {
		$sdirs->{$1} = $2;
	    }
	    print "  dir $1 -> $2\n";
	}
	else
	{
	    $line = <MAP>;
	    last DIR;
	}
	$line = <MAP>;
    }

    my $img = "missing";
    if( $id =~ /^(\d+)/ )
    {
	$img = "P".(1010000+$id);
    }

    my $vars =
    {
     id => $id,
     img => $img,
     name => $name,
     desc => $desc,
     pdirs => $pdirs,
     sdirs => $sdirs,
     exab => $exab,
     dir => $dir,
    };

    my $file = "html/$id.html";
    print "  processing\n";
    $tmpl->process('place.tt', $vars, $file) or die $tmpl->error();

    $place->{$id} = $vars;

    last unless defined $line;
}

print "\nControlling data:\n";

foreach my $id ( keys %$place )
{
    my $p = $place->{$id};
    print "  Checking $id\n";
    foreach my $dir ('N', 'S', 'E', 'W')
    {
	if( $p->{dir} and $p->{pdirs}{$dir} )
	{
	    print "    $dir\n";
	    unless( $p->{dir} eq $dir )
	    {
		die "Discrepancy in $id: ".$p->{dir}."\n";
	    }

	    my $destid = $p->{pdirs}{$dir};
	    my $dest = $place->{$destid};
	    if( $dest->{dir} and $dest->{dir} ne $dir )
	    {
		die "Discrepancy in $id -> $destid\n";
	    }

	}
    }

    foreach my $destid ( values %{$p->{pdirs}}, values %{$p->{sdirs}} )
    {
	unless( $place->{$destid} )
	{
	    die "Discrepancy in $id -> $destid\n";
	}
    }
}

