#!/usr/bin/perl

$COLS = 3;
$COLFORM = 'rr';

$tabform = join('', ($COLFORM) x $COLS);

# $FORMAT = "%s, %s\t%3s\n";
$FORMAT = " %s %s & %s";
$SPACE = " & \\qquad \\qquad";
# $SPACE = " & ";

sub trailer {
  my $line = shift;
#  ($line % 5 != 4) ? "\\\\\n" : "\\\\ \\hline \n";
  "\\\\\n";
}


$PRE = qq{
  \\documentstyle[landscape,simplemargins]{article}
  \\pagestyle{empty}
%%  \\setlength{\\topmargin}{-.25in}
%%  \\setlength{\\evensidemargin}{-.5in}
%%  \\setlength{\\oddsidemargin}{-.5in}
  \\setallmargins{0pt}
  \\settopmargin{1.2in}
  \\setleftmargin{.5in}
  \\setlength{\\parindent}{0in}
  \\begin{document}

  \\Large
  \\begin{tabular}{$tabform}
};

$POST = qq{
  \\end{tabular}
  \\end{document}
};

while (<>) {
  s/\#.*$//;			# Strip comments
  next unless /\S/;		# Skip blank lines

  if (/^TABLE\s*(.*):/) {	# New table!
    $TABLE = $1;
    next;
  }

  chomp;
  ($last,$first,$lalpha, $falpha,$veg) = split(/,/, $_);
  push @names, [$last, $first, 
		$lalpha || $last, $falpha || $first,
		$TABLE];
  $VEG{$TABLE}++ if $veg =~ /^V/;
}

@names = sort {$a->[2] cmp $b->[2]
		 || $a->[3] cmp $b->[3]} @names;
$N = @names;
print STDERR "There were $N guests in all.\n";


for ($i = $COLS; $i > 0; $i--) {
  push @cols, [splice(@names, 0, &up(@names/$i))];
}

print $PRE;

for (;;) {
  my @names;
  my $p;
  my $done = 1;
  for ($i=0; $i< $COLS; $i++) {
    my $c = $cols[$i];
    my $g = shift @$c;
    push @names, $g if $g;
    push @who, join(" ", $names[-1][1], $names[-1][0]) if @names;
  }
  print STDERR "Doing row with (@who)\n";
  undef @who;
  foreach $n (@names) {
    $done = 0, last if $n;
  }
  last if $done;
  while ($p = shift @names) {
    my ($last, $first, $lalpha, $falpha, $table) = @$p;
    printf $FORMAT, $first, $last, $table;
    if (@names) {
      print $SPACE;
    } else {
      print &trailer($lineno);
    }
  }
  $lineno++;
}

print $POST;

foreach $table (sort {$a <=> $b } keys %VEG) {
  my $n = $VEG{$table};
  next unless $n;
  my $s = $n == 1 ? '' : 's';
  print STDERR "At table $table: $VEG{$table} vegetarian$s.\n",
            
      if $VEG{$table};
}
exit 0;

sub up {
  my $i = shift;
  return $i if $i == int $i;
  return int($i+1);
}
