#!/usr/bin/perl

use MIME::QuotedPrint;

mkdir "./out";

my %entry;
my $file_counter = 0;

while (<STDIN>)
{
   if (!(/^$/))
   {
      # non-empty line
      chomp;   # remove trailing newline
      /:/;     # match the colon = key:value separator
      $entry{$`} = $';   # key = "left of match", value = "right of match"
   }
   else
   {
      # empty line (separator)
      my @hashkeys = keys %entry;
      if ($#hashkeys + 1 > 0)
      {
         # the hash table has accumulated some data = is non-empty
         open(OUTFILE,">./out/" . $file_counter++ . ".vcf");

         print OUTFILE "BEGIN:VCARD\n";
         print OUTFILE "VERSION:2.1\n";
         print OUTFILE "N;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:" . encode_qp( $entry{"N"} , "", TRUE ) . ";;;;\n";
         print OUTFILE "TEL;CELL:" . $entry{"TEL;TYPE=PREF,VOICE"} . "\n";
         print OUTFILE "END:VCARD\n";

         close(OUTFILE);
         %entry = ();  # clear the hash table
      }
      # else the hash table is empty, do nothing
   }
}

