#!/usr/bin/perl

use strict;

print "opening file: $ARGV[0]\n";
open FILE, "$ARGV[0]" or die $!.$ARGV[0];

my $counter=0;
my $prefix="vcardsplit";
my $suffix=".vcf";
my $uid=""; #rename to uid

while (my $line = <FILE>) {
  if($line =~ /BEGIN:VCARD/) {
   rename_and_close_file();
   $counter++;
   open FOUT, ">$prefix$counter$suffix" or die $!;
   $uid="";
  }
  
if($line =~ /^UID:([A-Za-z0-9]*)/) {
  $uid=$1;
}
  if(!<FOUT>) { #file is ready
    print FOUT $line;
  } else {
    #print "ignoreing line: $line\n"
  }
}
rename_and_close_file();
print "wrote $counter files\n";
close FILE;
close OUT;


# closes FOUT and renames the file to $uid if it is set.
sub rename_and_close_file {
   if(!<FOUT>) {
    close FOUT; 
    if($uid ne '') {
      rename("$prefix$counter$suffix", $uid);
    }
   }
}