#!/usr/bin/perl
use strict;
use warnings;
use Pod::Usage;
use Getopt::Long;
use File::Basename;

# main
main : {
  # options hash table
  my %h_options;

  Getopt::Long::Configure( "no_ignorecase" );
  Getopt::Long::Configure( "bundling" );

  # retrieve all options
  GetOptions (\%h_options,
	      'h|help'
	     ) or  pod2usage( -verbose => 1 , noperldoc => 1) ;
	
  # help
  pod2usage( -verbose => 1 , noperldoc => 1) if (exists $h_options{'h'});
	
  # test ARGV parameters
  pod2usage( -verbose => 2 , noperldoc => 1) if (@ARGV < 2);

  my @a_fastq = @ARGV;
  my $cmp = 0;
  my $cmd;
  print "#seq";
  foreach my $fq ( @a_fastq ) {
    my $fqname = basename($fq);
    $fqname =~ s/\..*$//;
    $cmp++;
    if($cmp==1) {
      $cmd = "join -t '\t' -a1 -a2 -e'0' -11 -21 -o 0,1.2,2.2 $fq ";
      print "\t$fqname";
      print STDERR "Join $fq with ";
    }
    elsif($cmp==2) {
      $cmd.= " $fq > tmp.$$.2";
      print "\t$fqname";
      print STDERR "$fq...";
      `$cmd`;
      print STDERR "done\n";
    }
    else {
      $cmd = "join -t '\t' -a1 -a2 -e'0' -11 -21 -o 0,1.2,";
      my $t=3;
      while($t!=$cmp+1) {
	$cmd .= "1.$t,";
	$t++;
      }
      my $name = "tmp.$$.".($cmp-1);
      $cmd .= "2.2 $name $fq > tmp.$$.$cmp";
      print "\t$fqname";
      print STDERR "Join $fq...";
      `$cmd`;
      print STDERR "done\n";
      `rm $name`;
    }
  }
  print "\n".`cat tmp.$$.$cmp`;
  `rm -f tmp.$$.$cmp`;
}

=pod

=head1 NAME

        join.pl - Join files to produce count matrix

=head1 DESCRIPTION

        Build a matrix file sorted by first column like :
        key<tab>val<tab>val...
        Warning: each input file must be a two fields tab
                 separated (key<tab>val) sorted by key.

=head1 SYNOPSIS

        join.pl FILE1 [FILE2 ...] > ALL.matrix

=head1 OPTIONS

        -h,--help
	
=cut
