#!/usr/bin/perl -w use strict;


## test arguments
if (@ARGV == 0){
	die "Supply a filename as argument";
}

use Text::ParseWords;

open INPUT, "$ARGV[0]" or die "Can't open input file $ARGV[0]: $!";
open TMP, ">csv2xml.tmp" or die "Can't open temp file: $!";

# petit nettoyage
$ligne=<INPUT>;
print TMP $ligne ;

$count_tmp = 0;
while ($ligne=<INPUT>){
#	$ligne =~ s/é/&#130;/g ;
#	$ligne =~ s/â/&#131;/g ;
#	$ligne =~ s/ä/&#132;/g ;
#	$ligne =~ s/à/&#133;/g ;
#	$ligne =~ s/ç/&#135;/g ;
#	$ligne =~ s/ê/&#136;/g ;
#	$ligne =~ s/è/&#137;/g ;
#	$ligne =~ s/ï/&#138;/g ;
#	$ligne =~ s/î/&#139;/g ;
#	$ligne =~ s/Ä/&#141;/g ;
#	$ligne =~ s/É/&#143;/g ;
#	$ligne =~ s/ô/&#144;/g ;
#	$ligne =~ s/ö/&#145;/g ;
#	$ligne =~ s/û/&#147;/g ;
#	$ligne =~ s/ù/&#148;/g ;
#	
#   scalar(@tab)
    $count = ($ligne =~ tr/"//);
	if (($count+$count_tmp) < 54){
	   $count_tmp += $count;
	   chomp($ligne);
	   $ligne = $ligne."<br/>";
	}else{
	  $count_tmp =0;
	}
	print TMP $ligne ;
}

close TMP;
close INPUT;
open INPUT, "csv2xml.tmp" or die "Can't open input file csv2xml.tmp: $!";

print "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
#print "<!DOCTYPE rows SYSTEM \"jpilot.dtd\">\n";

print "<adressbook>";
$ligne = <INPUT> ;
$ligne=~ s/\s//g;
my @champs = split(/,/, $ligne);
if ($champs[0] eq "CSVaddress:Category"){
  $champs[0]="Category";
}

while (<INPUT>) {
	chop;
	my @fields = quotewords(",", 0, $_);
	print "<person>\n";
	my $i = 0;
	foreach $field (@fields) {
		if ($field ne "" ){
			print "\t<$champs[$i]>$field</$champs[$i]>\n";
		}
		$i++;
	}
	print "</person>\n";
}

print "</adressbook>\n";


