#!/usr/bin/perl

=head1 NAME

bec2syl-addr - bec2syl-addr convert address book from Becky! to Sylpheed.

=head1 SYNOPSIS

$ bec2syl-addr

STDIN: Address Files of Becky!
STDOUT: <person> tag set for address book of Sylpheed.

=head1 DESCRIPTION

 At first, you must copy files of Becky! address files(*.bab) to Linux.

(ex) under c:\Becky!\AddrBook\@Personal

 If you copy these files to home directory, you must type following on terminal.

$ cat ~/*.bab | bec2syl-addr > tmp.xml

 Next you have insert content of tmp.xml to ~/.sylpheed/addrbook-000001.xml etc...

=head1 AUTHOR

Yasumichi Akahoshi <yasumichi@users.sourceforge.jp>

=head1 SEE ALSO

al2syl-addr

=cut

# Declation to use library and module.
use Jcode;
require 'w2l-tools.pl';

# get first unique id from inner clock.
$uid = &makeuid();

# $vCard = "";

foreach $line (<STDIN>) {
	$line = jcode($line)->euc;	# convert character code
	$line =~ s/\r\n/\n/g;	# convert code of new line.
	chomp($line);		# remove code of new line.
	next if($line =~ /^BEGIN:VCARD$/);
	if($line =~ /^END:VCARD$/) {
		$uid = &putperson($uid, %vCard);
		undef %vCard;
		next;
	}
	if ($line =~ /^([^:]*):(.*)$/) {
		$vCard{$1} = $2;
	}
}

# make data of person.

sub putperson {
	my($uid, %vCard) = @_;

	# remove some datas.
	delete $vCard{'X-BECKY-IMAGE'};
	delete $vCard{'NOTE;ENCODING=QUOTED-PRINTABLE'};
	delete $vCard{'UID'};

	# start of person tag set
	my $cn = $vCard{'FN'};
	delete $vCard{'FN'};
	my($lastname,$firstname,$midname) = split(/;/, $vCard{'N'});
	delete $vCard{'N'};
	my $nick = $vCard{'X-BECKY-NICKNAME'};
	delete $vCard{'X-BECKY-NICKNAME'};
	print '  <person uid="'.$uid.'" first-name="'.$firstname.'" last-name="'.$lastname.'" nick-name="'.$nick.'" cn="'.$cn.'" >'."\n";
	$uid++;

	# convert address of e-mail.
	$email = $vCard{'EMAIL;PREF'};
	delete $vCard{'EMAIL;PREF'};
	print "    <address-list>\n";
	print '      <address uid="'.$uid.'" alias="" email="'.$email.'" remarks="" />'."\n";
	print "    </address-list>\n";
	$uid++;

	# convert other datas.
	print "    <attribute-list>\n";
	while(($key, $value) = each(%vCard)) {
		print '      <attribute uid="'.$uid.'" name="'.$key.'" >'.$value."</attribute>\n";
		$uid++;
	}
	print "    </attribute-list>\n";
	print "  </person>\n";

	return $uid;
}
