#!/usr/bin/perl

my @righe=<>;
my $item = "item";
print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
if ( $righe[0] =~ m/^[a-z][a-z0-9_-]+[\r\n]*$/i ) {
	$item = shift @righe;
	chomp $item;
} else {
	print <<OKBASTA;
	<!--
		Come prima riga può essere inserito
		il nome del nodo da usare al posto di "$item"
	-->
OKBASTA
}
@right = grep { /\t/ } @righe;
my $headOptions = {};
my @heads = getHeads();
my $qt = $#heads;

print "<root>\n";

while (my $riga = shift(@righe)) {
	chomp $riga;
	my @fields = split(/\t/,$riga);
	my @vals;
	for ($i=0; $i<=$qt; $i++) {
		my $h = $heads[$i];
		my $v = $fields[$i];
		my $switch = $headOptions->{$h} || {};
		next if ($v eq "" and ! $switch->{force});
		if ( $switch->{bool} ) {
			$v = ($v eq "" or $v =~ /^f0/i) ? "false()" : "true()";
		} elsif ( $switch->{Bool} ) {
			$v = ($v eq "" or $v =~ /^f0/i) ? "0" : "1";
		} else {
			$v =~ s/\&/\&amp;/g;
			$v =~ s/</\&lt;/g;
			$v =~ s/>/\&gt;/g;
			$v =~ s/"/\&quot;/g;
		}
		push(@vals,"$h=\"$v\"");
	}
	print "\t<$item ".join(' ',@vals)." />\n" if @vals;
}
print "</root>\n";


sub getHeads {
	my $heads = shift @righe;
	chomp $heads;
	my @heads = split(/\t/,$heads);
	my @out;
	foreach my $head (@heads) {
		if ( $head =~ s/ *\{([^\}]*)\} *// ) {
			my $v = "$1";
			my $out = {};
			$out->{force} = 1 if $v =~ /\!/;
			$out->{bool} = 1 if $v =~ /b/;
			$headOptions->{$head} = $out;
		}
		push @out,$head;
	}
	@out = map { s/^[^a-zA-Z]+//; s/ +$//; s/[^a-zA-Z0-9_-]/_/g; $_ } @out;
	return @out;
}