#!/usr/bin/perl

#Copyright (C) 2006-2008 Keio University
#(Kris Popendorf) <comp@bio.keio.ac.jp> (2006)
#
#This file is part of Murasaki.
#
#Murasaki is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#Murasaki is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with Murasaki.  If not, see <http://www.gnu.org/licenses/>.

use Getopt::Long;
use Pod::Usage;
use File::Basename;
#use Data::Dump qw {dump};

BEGIN {
  unshift(@INC,(fileparse($0))[1].'perlmodules');
}
use Murasaki;
use Murasaki::KOG;
use strict;

my @kogmap;

our $podusageOpts={-message=>'Use --help or --man for more detailed help.',-verbose => 0,-exitval=>2};
my ($help,$man);
my $output;
my $opterr=
  GetOptions('help|?' => \$help, man => \$man,

	     'kog=s%' => sub {pod2usage($podusageOpts)
				unless($_[1] and $_[2] and $_[1]>0 and $_[2]=~m/^...$/);
			      $kogmap[$_[1]]=$_[2]},
	     'output=s' => \$output,
	    );

unless($output){
  $output=pop(@ARGV);
  if(!$output or -f $output){
    push(@ARGV,$output) if $output;
    $output=">-";
  }
}

pod2usage({-verbose=>1,-exitval=>2,-message=>'Need some input file...'}) if $#ARGV<0 or !$opterr;

open(our $outf,">$output") or die "Couldn't open $output for writing.";

setupKogmap(@ARGV);

my %kogs;
my $si=0;
foreach my $file (@ARGV){
  my $specs=$kogmap[$si];
  warn "Couldn't identify a species for input $file" if(grep(/\?/,$specs));
  unless($file=~m/\.cds$/){
    my $newf="$file.cds";
    system("$root/getcds.pl $file") unless -f $newf;
    $file=$newf;
  }
  open(my $inf,$file) or die "Couldn't open $file\n";
  while(<$inf>){
    chomp;
    my @a=split(/\t/);
    my $name="[?] $a[0] name2kog autogenerated";
    my $content="  $specs:  $a[4]";
    push(@{$kogs{$name}},$content);
  }
}continue{$si++}

my @usable=grep {scalar(@{$kogs{$_}})>1} (keys %kogs);
print $outf (map {$_."\n"} (map {($_,@{$kogs{$_}},undef)} @usable));

sub setupKogmap {
  my $kogre=join("|",Murasaki::KOG->knownCogs,Murasaki::KOG->knownKogs);
  my $i=0;
  my %aliases=Murasaki::KOG->commonAliases;
  foreach(@_){
    next if $kogmap[$i];
    my ($id)=m/($kogre)/;
    unless($id){ #try harder...
      foreach my $alias (keys(%aliases)){
	$id=$aliases{$alias} if (m/$alias/i);
      }
    }
    next unless $id;
    print STDERR "Identified $_ as KOG member $id\n";
    $kogmap[$i]=$id;
  }continue{$i++}
}

sub guessSpecies {
  my $file=pop;
  my @bits=split(/\./,$file);
  my $clue=$#bits>0 ? $bits[$#bits-1]:$file;
  return qw{hsa ptr mac mmu rno cfa bov pos avi} if $clue eq 'hcmmrdcoc'; #hacchy's alias for: human chimp macaq mouse rat dog cow oposs chick (note: i made up mac bov pos and avi)
  my @tokens=split(//,$clue);
  my %conv=(h=>'hsa',m=>'mmu',r=>'rno');
  my $unknown=0;
  return map {exists($conv{$_}) ? $conv{$_}:"??".(++$unknown)} @tokens;
}

__END__

=head1 NAME

names2kog.pl - builds a kog-set based only on gene "names"

=head1 SYNOPSIS

names2kog.pl [options] <input1> [input2 ... ] [output file]

=head1 OPTIONS

If "output file" exists, it is considered an input file.

Note: you can redefine what is considered a "name" from the .overrides file
(like say, to "product" or something).

 Other options:
--kog <seq_number>=<species> => for manually specifying 3 letter cog species
-o<filename>                 =>specify the output file.
