#!/usr/bin/perl


my $fname  = $ARGV[0];
my $utrfil = $ARGV[1];
my $listc  = $ARGV[2];
my $ofname = $ARGV[3];
my $extra  = $ARGV[4];
my $tmp_fasta_file = "tmp.fasta";


if( @ARGV  ne 5 )
  {
    print "Wrong number of arguments!\n";
    print "Syntax: ./utr2multifasta.pl cer1.ffn utr5_2000.fasta list_cand.txt toOrfPlot.ttt extra \n";
    exit( 1 );
  }


open( MYFILE, $fname )      or die "Cannot open: $!";
open( UTRFILE, $utrfil )    or die "Cannot open: $!";
open( CANDFILE, $listc )    or die "Cannot open: $!";
open( OUTFILE, ">$ofname" ) or die "Cannot write to: $!";

%name2length;
while ( <MYFILE> )
{
  $a = $_;

  if( $a =~ /\>/ )
    {
      my @parts = split " ", $a;
      $parts[0] =~ s/\>//g;
      $name2length{ $parts[0] } = $parts[5];
    }
}

%isInCandidates;
while ( <CANDFILE> )
{
  $_ =~ s/\n//;
  $isInCandidates{ $_ } = 1;
}



while( <UTRFILE> )
  {
    $a = $_;
    if( $a =~ /\>/ )
      {
	my @parts = split " ", $a;
	$parts[0] =~ s/\>//g;
	my @names = split "_", $parts[0];
	if( $isInCandidates{ $parts[1] }  )
	  {
	    my $length = $name2length{ $parts[1] } + $extra;
	    my $seq = <UTRFILE>;
	    my $seqlength = length( $seq ) - 1;
	    my $start = $seqlength - $length + 1;
	    if( $start lt 0 ) { $start = 0; }
	    my $last_part = substr( $seq, $start, $length );
	
	    open( TMPOUTFILE, ">$tmp_fasta_file" ) or die "Cannot write to file: $ofname:  $!";
	    
	    my $l = length( $last_part ) - 1;
	    print TMPOUTFILE ">$names[0]_$parts[1]_".$l."\n";
	    print TMPOUTFILE "$last_part";
	    close( TMPOUTFILE );

	    system( "getorf -minsize 0 -sequence $tmp_fasta_file -outseq out_tmp.ffn -find 3 -reverse false 2> /tmp/nada.txt" );
	
	    extractInformationFromGetOrf( $header[1] );
	  }
      }
  }




sub extractInformationFromGetOrf( $$ )
  {
    open( uORFfile, "out_tmp.ffn" ) or die "Cannot open file: $fname : $!";
    open( OUTFILE2, ">>$ofname" ) or die "Cannot write to file: $ofname:  $!";
    while ( <uORFfile> )
      {
	if( $_ =~ /\>/ )
	  {
	    my $a = $_;
	    my @parts  = split ' ', $a;
	    my $start = $parts[1];
	    $start =~ s/\[//;
	    my $stop = $parts[3];
	    $stop =~ s/\]//;

	    my @names = split "_", $parts[0];
	    my $length = $names[2];
	    $names[0] =~ s/\>//g;
	    my $species_name = $names[0]."_".$names[3]." ".$names[1];
	    print OUTFILE2 "$species_name  $start $stop $length\n";
	    #print "$species_name $_[0] $start $stop $length\n";
	  }
      }
    close( uORFfile );
    close( OUTFILE2 );
  }

