#!/usr/bin/perl -w
use strict;

use lib "../stat";
use Vector;
use Getopt::Long;

my $name = "NAME";
my $debug = 0;
my ($taxon, $dir, $exptsFile, $host, $synonymType);
print STDERR join("\t",@ARGV),"\n";
(GetOptions('taxon=i' => \$taxon,
		   'dir=s' => \$dir,
		   'field=s' => \$name,
		   'host=s' => \$host,
		   'expts=s' => \$exptsFile,
		   'debug=i' => \$debug,
		   'synonymType=i' => \$synonymType )
 && $taxon && $dir && $exptsFile)
    || die "Usage: SMDmatchGenes.pl -taxon taxon -dir dir -expts exptsFile [-field NAME -debug 20 -host lut]\n";

my $expts = Vector::readDelim($exptsFile,"Exptid");
foreach my $exptid (keys %{ $expts->{"Exptid"} }) {
    my $exptFile = "$dir/$exptid.xls";
    my $exptFileGZ = "$exptFile.gz";
    if (-f $exptFileGZ) {
	print STDERR "Running matchGenes for experiment $exptid\n";
        my $q = "'";
        my $cmd = "./matchGenes.pl -name $q$name$q -in $exptFile -genome $taxon -debug $debug"
                 . " -keepColumns 1 -matchOnly 0 -uniq 1";
        $cmd .= " -host $host" if $host;
        $cmd .= " -synonymType $synonymType" if defined $synonymType;
	system("gunzip -c $exptFileGZ > $exptFile") == 0 || die "Cannot unzip $exptFileGZ";
        print STDERR "$cmd > $dir/$exptid.VIMSS\n";
	system("$cmd > $dir/$exptid.VIMSS") == 0 || die "matchGenes.pl failed";
	system("rm $exptFile");
    }
}
