#!/usr/bin/perl -Tw

#     V2M - Vcard to Mutt utility
#	Benjamin Gray (rwood@feel-bg.com)
#	July 2007
#	This perl script reads in a vcard file generated by Apple's 
#	Addressbook (and hopefully other Vcard files as well, though
#	frankly I can't be bothered to check) and converts them into 
#	a Mutt alias file.  If you have an addressbook that contains
#	diacritical marks for European languages Addressbook will produce
#	a Vcard file in UTF8 format; otherwise it will use ISO-8859-1.
#
#
#  a mutt alias file looks like the following:
# alias First_LastName Whatever the Name Is <address@example.foobar>
# alias Randall_Wood Benjamin Gray <address@example.foobar.org>
# 
# This is my first perl script ever; if you find a better way of doing things,
# let me know via the email address at my website feel-bg.com

# Thanks to Peter Watkins for the tip about using binmode to deal with UTF8 issues.


# binmode ( STDIN, ':utf16' );                                                             
# binmode ( STDOUT, ':encoding(iso-8859-1)' );

 my $mail;				# create a couple of variables 
 my $dashname;				# we'll need later
 my $realname;

# use open IN => ':encoding(utf16)'; # Default all open ()s to UTF16
# use open ':std'; #STDIN too, in case the script is pipelined

while ( <> )
{

	if  (/^FN:(.*)/i) 		# find a name - everything after FN:
	{
	s/FN://g;			# lop off the FN: at the beginning
	s/\s$//g;			# lop any extra blank spaces at the end
	$realname = $_;			# store it in a variable

	s/\s/_/g;			# replace spaces with underscores _
	$dashname = $_;			# store it in a variable
	print "alias $dashname $realname ";	#print name but not email address
	}

	elsif (/:{1}([^\s()\[\]{}@,]*	
                  @
                  [^\s()\[\]{}@,.]{1}
                  [^\s()\[\]{}@,]*
                  \.
                  [a-z0-9]{2,4})/xi)		# find an email address
	{
		$mail = $1;		# store it in a variable
		print "<$mail>\n";	# print it and a newline character
	}				# repeat
}
