#! /usr/bin/perl -w

use HTML::Parser ();

# Program for  konvertere det danske postverkets postnmummertabell
# (Print_vis.html) til en passende datastruktur.

my $in     = "bin/Print_vis.html";
my $out    = "DK.pm";
my $source = "$out." . time;

# die "Unable to locate the file $in"     unless -e $in";
# die "Unable to locate the file $source" unless -e $source";

rename($out, $source) or die "Unable to rename file $out";

open(IN,     $in)     or die "Unable to open the file $in";
open(SOURCE, $source) or die "Unable to open the file $source";
open(OUT,    ">$out") or die "Unable to open the file $out";

## Copy the old file

my $part = 1; # 1 (first) 2 (skip) 3 (last)
my @part1;
my @part3;

foreach (<SOURCE>)
{
  if (/\#\# bin\/mkpostalinfo begin/)
  {
    $part = 2; # This part we skip.
  }
  elsif (/\#\# bin\/mkpostalinfo end/)
  {
    $part = 3;
  }
  if    ($part == 1) { push(@part1, $_); }
  elsif ($part == 3) { push(@part3, $_); }
}

close SOURCE;

print OUT @part1;

print OUT "## bin/mkpostalinfo begin\n";
print OUT "## This data structure was auto generated on " . localtime() . ". Do NOT edit it!\n\n";

my %location;    # postcode      > location
my %address;     # postcode      > address
my %owner;       # postcode      > owner
my %type;        # postcode      > type

my $skip = 1;
my @tabledata;
my @codes;

foreach (<IN>)
{
  $skip = 0 if /START/;
  next if $skip;

  next unless m|>(.*)</td>|;

  my $item = $1;

  $item =~ tr/"/'/;

  push(@tabledata, $item);

  if (@tabledata == 4)
  {
    ## print "**", join("|", @tabledata), "**\n";

    my($postcode, $location, $address, $owner) = @tabledata;

    push(@codes, $postcode); 

    $location{$postcode} = $location;

    if ($address)
    {
      if ($address eq "Postboks")
      {
        $type{$postcode} = "B";
      }
      elsif ($address =~ /Ufrankerede svarforsendelser/)
      {
        $type   {$postcode} = "U";
      }      
      elsif ($owner)
      {
        $type   {$postcode} = "P"; # Personlig eier
      }      
      else
      {
        $type   {$postcode} = "G";
        $address{$postcode} = $address;
      }
    }

    if ($owner)
    {
      $owner{$postcode}= $owner;
    }

    @tabledata = ();
  }
}

close IN;

foreach (@codes) # sort keys %location)
{
  print OUT  "\$location{'" . $_ . "'} = \"" . $location{$_} . "\";";
  print OUT " \$address{'"  . $_ . "'} = \"" . $address{$_}  . "\";"  if $address{$_};
  print OUT " \$owner{'"    . $_ . "'} = \"" . $owner{$_}    . "\";"  if $owner{$_};
  print OUT " \$type{'"     . $_ . "'} = \"" . $type{$_}     . "\";"  if $type{$_};
  print OUT "\n";
}

print OUT "\n";

print OUT @part3;

close OUT;
