#!/usr/bin/perl

=head1 NAME

csv2syl-addr - An filter convert address book from csv to Sylpheed.

=head1 SYNOPSIS

$ csv2syl-addr

STDIN:	Address book data of CSV which is exported Outlook Express etc.

STDOUT:	<person> tag set for Sylpheed

=head1 DESCRIPTION

Example:

$ iconv -f sjis -t iso-2022-jp hoge.csv | csv2syl-addr > tmp.xml

=head1 AUTHOR

Yasumichi Akahoshi <yasumichi@users.sourceforge.jp>

=head1 SEE ALSO

al2syl-addr, bec2syl-addr

=cut

require 'w2l-tools.pl';

# The first line is field names.
$firstline = <STDIN>;
$firstline =~ s/\r\n/\n/g;

@fields = split(/,/, $firstline);
$fldcnt = @fields;

%items = (
	'dummy'	=>	1,
);

$uid = &makeuid();

# convert each line.
foreach $line (<STDIN>) {
	undef %items;
	$line =~ s/\r\n/\n/g;
	@datas = split(/,/, $line);
	if(@datas == $fldcnt) {
		for($i=0; $i<$fldcnt; $i++) {
			chomp($fields[$i]);
			chomp($datas[$i]);
			$items{$fields[$i]} = $datas[$i];
		}
		$uid = &putperson($uid, %items);
	}
}

# generate datas of person.
sub putperson {

	my ($uid, %items) = @_;

	# person tag start
	my $cn = $items{'ɽ̾'};
	delete $items{'ɽ̾'};
	my $lastname = $items{'̾'};
	delete $items{'̾'};
	my $firstname = $items{''};
	delete $items{''};
	my $nick = $items{'˥å͡'};
	delete $items{'˥å͡'};
	print '  <person uid="'.$uid.'" first-name="'.$firstname.'" last-name="'.$lastname.'" nick-name="'.$nick.'" cn="'.$cn.'" >'."\n";
	$uid++;

	# convert e-mail
	$email = $items{'Żҥ᡼ ɥ쥹'};
	delete $items{'Żҥ᡼ ɥ쥹'};
	print "    <address-list>\n";
	print '      <address uid="'.$uid.'" alias="" email="'.$email.'" remarks="" />'."\n";
	print "    </address-list>\n";
	$uid++;

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

	return $uid;
}
