#! /usr/bin/perl -w

use Geo::Postcodes::Update ();

################################################################################
#                                                                              #
#   This program converts the danish postcodes to a suitable data structure.   #
#                                                                              #
#            !!! This is done on the library file 'DK.pm' itself !!!           #
#                                                                              #
################################################################################

Geo::Postcodes::Update::update('DK', 'Print_vis.html', \&parse_DK);

sub parse_DK
{
  my %location;    # postcode      > location
  my %address;     # postcode      > address
  my %owner;       # postcode      > owner
  my %type;        # postcode      > type

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

  my @out;

  foreach (@_)
  {
    $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} = "BX";
        }
        elsif ($address =~ /Ufrankerede svarforsendelser/)
        {
          $type   {$postcode} = "PP";
        }      
        elsif ($owner)
        {
          $type   {$postcode} = "IO"; # Personlig ejer
        }      
        else
        {
          $type   {$postcode} = "ST"; # gadeadresse
          $address{$postcode} = $address;
        }
      }

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

      @tabledata = ();
    }
  }

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

  return (@out, "\n");
}
