#!/usr/bin/perl -w

use strict;
use lib "/usr2/people/khuang/bin/Genomics/Perl/modules";
#use lib "/usr2/people/alm/Genomics/Perl/modules";
use Genome;
use Gene;
use GenomicsUtils;
use Getopt::Long;

my $helpStr = qq{

    autoAnno.pl <taxId> <db> <outDir> (option)
	
	<db>: none, pfam, smart, cog, or kegg 

	if <db> eq none, meaning only retrieve protein sequences of <taxId>

};

unless (@ARGV>=3){die "$helpStr";}


connect("lut");
#setDebug(10); #uncomment this line for debugging the modules

########## Params #############

my ($taxId, $targetDb, $outDir) = @ARGV;

my $print = 0;
GetOptions( 
	    '-p' => \$print #$print == 1 meaning only print the blast/parse command list and not execute any.
	    );

$outDir =~ s/\/$//;
my $genome = Genome::new(taxonomyId=>$taxId);
my $faa = "$outDir/$taxId.faa";

################################

&makeFaa($genome, $faa);
&launch($faa, $targetDb, $outDir, $print) unless $targetDb eq 'none';
disconnect();
exit;

sub makeFaa($$){
    my ($genome, $faa) = @_;
   
    open FILE, ">$faa" or die "Can't write to $faa:$!\n";
    my $oldFH = select (FILE);
    foreach ( $genome->genes() ){
	
	print ">".$_->locusId()."\n".$_->protein()."\n";
	
    }
    select ($oldFH);
    close FILE;
    return;
}
sub launch($$$$$){
    my ($faa, $target, $outDir, $print) = @_;
    my $homeDir = "/usr2/people/khuang";
    my $perl = "$homeDir/bin";
    my $blastDir = "$homeDir/apps/blast";
    my %db = (
	      'cog' => "$homeDir/apps/cdd/Cog",
	      'pfam' => "$homeDir/apps/cdd/Pfam",
	      'smart' => "$homeDir/apps/cdd/Smart",
	      'kegg' => "$homeDir/apps/blast/db/kegg.clean.faa"

	      );
    my $outFile = "$outDir/$targetDb.out";
    my $oldFH = select (STDERR);

    #run BLASTP or RPSBLAST:

    if ($target eq 'kegg'){
	print "$blastDir/blastall -d $db{$target} -i $faa -p blastp -m 8 -e 1e-5 -o $outFile\n";
	system "$blastDir/blastall -d $db{$target} -i $faa -p blastp -m 8 -e 1e-5 -o $outFile" unless $print;
    }
    else{
	print "$blastDir/rpsblast -d $db{$target} -i $faa -m 8 -e 1e-5 -o $outFile\n";
	system "$blastDir/rpsblast -d $db{$target} -i $faa -m 8 -e 1e-5 -o $outFile" unless $print;
    }

    #Parse the results:
    
    my $selectedHits = ( ($target eq 'cog') || ($target eq 'kegg') )?'best':'all';

    print "$perl/parseBlastTab.pl $db{$target} -$selectedHits -i $outFile -hitInfo -detail\n";
    system "$perl/parseBlastTab.pl $db{$target} -$selectedHits -i $outFile -hitInfo -detail" unless $print;

    select ($oldFH);

    return;
}

