#! /usr/bin/perl -w

use strict;
use Geo::Postcodes::Update ();

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

Geo::Postcodes::Update::update('NO', 'tilbud5.txt', \&parse_NO);

################################################################################

sub parse_NO
{
  my %fix_type;

  $fix_type{B} = 'STBX'; # The first field is the value used in 'tilbud5.txt'. #
  $fix_type{F} = 'MU';   #   The second field is my international code.        #
  $fix_type{G} = 'ST';
  $fix_type{K} = 'IO';
  $fix_type{P} = 'BX';
  $fix_type{S} = 'SX';

  my %location;       # postcode       > location
  my %borough_number; # postcode       > borough number
  my %borough;        # borough number > borough
  my %type;           # postcode       > type

  my($postcode, $location, $borough_number, $borough, $type);

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

  my @out;

  foreach (@_)
  {
    tr/\235\217//; # Fix curious coding of 8-bit characters.

    ($postcode, $location, $borough_number, $borough, $type) 
      = unpack("A4A32A4A30A", $_);

    $location      {$postcode}       = $location;
    $borough_number{$postcode}       = $borough_number;
    $borough       {$borough_number} = $borough;
#    $type          {$postcode}       = $type;
    $type          {$postcode}       = $fix_type{$type};
  }

  foreach (sort keys %location)
  {
    push(@out,  "\$borough_number{'" . $_ . "'} = '" . $borough_number{$_} . "';");
    push(@out, " \$type{'"    . $_ . "'} = '" . $type{$_}    . "';");
    push(@out, " \$location{'"    . $_ . "'} = '" . $location{$_}    . "';\n");
  }

  push(@out, "\n");

  foreach (sort keys %borough)
  {
    push(@out, "\$borough{'" . $_ . "'} = '" . $borough{$_} . "';\n");
  }

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