#!/usr/bin/perl


my $listc  = $ARGV[0];
my $fname  = $ARGV[1];


open( MYFILE, $fname )      or die "Cannot open: $!";
open( CANDFILE, $listc )    or die "Cannot open: $!";

%name2length;
%name2header;
%name2seq;
while ( <MYFILE> )
{
  $a = $_;

  if( $a =~ /\>/ )
    {
      my @parts = split " ", $a;
      $parts[0] =~ s/\>//g;
      $name2length{ $parts[0] } = $parts[5];
      $name2header{ $parts[0] } = $a;
      $name2seq{ $parts[0] }     = <MYFILE>;
    }
}


@isInCandidates;
my $counter = 0;
while ( <CANDFILE> )
{
  $_ =~ s/\n//;
  $isInCandidates[ $counter++ ] = $_;

  open( OUTFILE, ">alignX/$_.txt" )  or die "Cannot write to file: alignX/$!\n\nNote: Need to create a directory named alignX!\n\n";
  print OUTFILE $name2header{ $_ };
  print OUTFILE $name2seq{ $_ };
  close( OUTFILE );
}



for( $j = 0; $j < @isInCandidates; ++$j )
  {
    print " GENE = ".$isInCandidates[$j]."\n";
    for( $i = 2; $i < @ARGV; ++$i )
      {
#	print $ARGV[$i]."\n";
	
	open( UTRFILE, $ARGV[$i] );
	
	while( <UTRFILE> )
	  {
	    $a = $_;
	    if ( $a =~ /\>/ )
	      {
		if( $a =~ $isInCandidates[ $j ] )
		  {
		
		    my $seq = <UTRFILE>;
		    my $length = $name2length{ $isInCandidates[ $j ] };
		    my $seqlength = length( $seq ) - 1;
		    my $start = $seqlength - $length + 1;
		    if( $start lt 0 ) { $start = 0; }
		    my $last_part = substr( $seq, $start, $length );
		
		    open( OUTFILE, ">>alignX/$isInCandidates[ $j ].txt" );
		    print OUTFILE $a;
		    print OUTFILE $last_part;
		    close( OUTFILE );
		  }
	      }
	  }
      }
  }
