#!/usr/bin/perl
# The Missing Textutils, Ondrej Bojar, obo@cuni.cz
# http://www.cuni.cz/~obo/textutils
#
# 'tab2list' is a complement to list2tab. It reads a 2-dimensional table and
# produces a list in the form: row label - column label - value.
#
# Think about using tab2list on two separate tables, concatenating the lists
# and then formatting it to a single table with list2tab.
#
# $Id: tab2list,v 1.4 2009-04-02 11:58:45 bojar Exp $
#

use Getopt::Long;
use strict;

my $keycols = 1;
my $usage = 0;
my $no_headline = 0;
GetOptions(
  "keycols=i" => \$keycols,
  "no-headline" => \$no_headline,
  "usage" => \$usage,
  "help"=>\$usage,
) or exit(1);

if ($usage) {
  print STDERR "usage: tab2list < infile > outfile
  Options:
    --keycols=X  ... How many cols from left are to be kept (default: 1)
    --no-headline ... The first line is content line already, there are no
                      column names.
";
  exit 0;
}

$keycols--;

my @headline;
if (!$no_headline) {
  $_ = <>;
  chomp;
  @headline = split /\t/, $_;
}

while (<>) {
  chomp;
  my @line = split /\t/, $_;
  my $head = "";
  foreach my $i (0 .. $keycols) {
    $head .= "$line[$i]\t";
  }
  chop $head;
  foreach my $i ($keycols+1 .. $#line) {
    print "$head";
    print "\t$headline[$i]" if ! $no_headline;
    print "\t$line[$i]\n";
  }
}
