#!/home/fxing/localperl/bin/perl-static 

eval 'exec /home/fxing/localperl/bin/perl-static  -S $0 ${1+"$@"}'
    if 0; # not running under some shell

use warnings;
use strict "vars";
use strict "refs";

use FindBin;
use lib "$FindBin::Bin/../lib";

BEGIN{
   #what to do on ^C
   $SIG{'INT'} = sub {
      print STDERR "\n\naborted by user!!\n\n";
      exit (1);
   };
}

use Dumper::GFF::GFFV3;
use Iterator::Any;
use Iterator::Fasta;
use Iterator::GFF3;
use Fasta;
use GFFDB;
use Cwd;
use maker::auto_annotator;
use GI;

$|  = 1;

my $usage = "
Usage:

     gff3_preds2models <gff3 file> <pred list>

     This script converts two level GFF3 features match/match_part
     commonly used for alignments or gene predictions and conversts
     them into three level gene/mRNA/exon gene features.  Useful
     for converting features for use with MAKERs GFF3 pass-through
     options.

";

if(@ARGV != 2){
    print $usage;
    exit(1);
}

my $gff3_in = shift @ARGV;
my $list = shift @ARGV;

my %index;
open(IN, "< $list");
while(defined (my $line = <IN>)){
    chomp $line;
    $line =~ s/^\s+|\s+$//g;
    $index{$line}++;
}
close(IN);

#--set up gff database
my ($gff3_base) = $gff3_in =~ /(.*)\.gff3?$/;
my $db_file = "$gff3_base.db";
my $GFF_DB = new GFFDB($db_file);
$GFF_DB->add_maker($gff3_in, {pred_pass => 1});
$GFF_DB->do_indexing;
my $build = $GFF_DB->last_build;

#---load genome multifasta/GFF3 file
my $iterator = new Iterator::Any(-gff => $gff3_in);

#build output gff3
my $gff3_out = "$gff3_base.pred_keepers.gff";

my $GFF3 = Dumper::GFF::GFFV3->new("$gff3_out",
				   $build,
				   Cwd::cwd
				   );

my %p_fastas;
my %t_fastas;

#---iterate over each sequence in the fasta
while (my $fasta = $iterator->nextFasta){
    #get fasta parts
    my $seq_id  = Fasta::getSeqID(\$fasta);
    my $seq_ref = Fasta::getSeqRef(\$fasta);
    
    $GFF3->set_current_contig($seq_id, $seq_ref);
    my $pred_gff = $GFF_DB->phathits_on_contig($seq_id,
					       $seq_ref,
					       'pred'
					       );
    #==MAKER annotations built here
    my $annotations = maker::auto_annotator::annotate($fasta,
						      $fasta,
						      '0',
						      [],
						      [],
						      [],
						      $pred_gff,
						      [],
						      Cwd::cwd,
						      $build,
						      { _predictor => ['pred_gff'],
							single_exon => '1',
							organism_type => 'eukaryotic',
							min_protein => 1,
							AED_threshold => 1
						      },
						     );

    my @keepers;

    foreach my $ann (@{$annotations->{abinit}}){
	my ($name) = $ann->{t_structs}->[0]->{t_name} =~ /^([^\s\t\n]+)/;
	push(@keepers, $ann) if(exists $index{$name});
    }
    
    #--- GFF3
    $GFF3->add_genes(\@keepers);
    #$GFF3->resolved_flag; #adds ### between contigs
    
    #--- building fastas for annotations (grows with iteration)
    GI::maker_p_and_t_fastas(\@keepers,
			     [],
			     [],
			     \%p_fastas,
			     \%t_fastas,
			     );
}

#--- write GFF3 file
$GFF3->finalize();   
#--- write fastas for ab-initio predictions

#--Write annotation fasta files now that all chunks are finished
GI::write_p_and_t_fastas(\%p_fastas, \%t_fastas, "$gff3_base.pred_keepers", Cwd::cwd);
