#!/usr/bin/perl

# Take 2 column list of values, and convert to table form.
# input is comma separate pair, double quotes allow use of comma in value
# eg:
#	A,1
#	A,3
#	B,2
#	C,1
#	"D E,F",3
# output:
#	,1,2,3
#	A,Y,,Y
#	B,,Y,
#	C,Y,,
#	"D E,F",,,Y

$sep=",";
$xsrt=1;
$ysrt=1;
while ($#ARGV >= 0) {
	if ($ARGV[0] !~ /^-/) {
		last;
	}
	if ($ARGV[0] eq "--") {
		shift;
		last;
	}
	if ($ARGV[0] eq "-n") {
		$xsrt=2;
		$ysrt=2;
		shift;
		next;
	}
	if ($ARGV[0] eq "-c") {
		if ($#ARGV >= 1) {
			$sep=$ARGV[1];
			shift;
			shift;
			next;
		}
	}
	if ($ARGV[0] =~ /^-c(.)$/) {
		$sep=$1;
		shift;
		next;
	}
	print STDERR "Usage: $0 [-c<X>] [-n] [<files>]\n";
	print STDERR "\t-c\tColumn separator (default is comma)\n";
	print STDERR "\t-n\tForce numeric sort of rows/cols\n";
	exit 1;
}

while ($l=<>) {
	$l =~ s/[\r\n]//g;
	$l =~ s/\s+/ /g;
	$l =~ s/^ //;
	$l =~ s/ $//;
	($x, $y, $z)=qspl($sep, $l);
	if ($xsrt == 1 && $x !~ /^[0-9]+$/) {
		$xsrt=0;
	}
	if ($ysrt == 1 && $y !~ /^[0-9]+$/) {
		$ysrt=0;
	}
	if ($z eq "") {
		$z="Y";
	}
	$r{$x}=1;
	$c{$y}=1;
	$a{"$x $y"}=$z;
}

if ($xsrt) {
	@xa = sort { $a <=> $b } keys %r;
} else {
	@xa = sort keys %r;
}
if ($ysrt) {
	@ya = sort { $a <=> $b } keys %c;
} else {
	@ya = sort keys %c;
}

foreach $y (@ya) {
	print ",$y";
}
print "\n";
foreach $x (@xa) {
	print "$x";
	foreach $y (@ya) {
		print "," . $a{"$x $y"};
	}
	print "\n";
}

# quoted split function:
#	qspl(ch, str)
# splits str on ch, but not when quoted
# returns array
sub qspl() {
	local ($c, $s)=@_;
	local @a;
	local $v;
	local $q;
	local $i;
	local $e;

	@a=();
	$q=0;

	$i=0;
	$e="";
	for ($i=0; $i < length($s); $i++) {
		$v=substr($s, $i, 1);
		if ($q) {
			if ($v eq "\"") {
				$q=0;
			}
		} elsif ($v eq "\"") {
			$q=1;
		} elsif ($v eq $c) {
			push @a, $e;
			$e="";
			next;
		}
		$e .= $v;
	}
	push @a, $e;

	return @a;
}
