#!/usr/bin/perl

$fname          = $ARGV[0];
$ofname         = $ARGV[1];
$pat_file       = $ARGV[2];
$tmp_fasta_file = "tmp.fasta";


open( MYFILE, $fname ) or die "Cannot open file: $fname : $!";
open( OUTFILE, ">$ofname" ) or die "Cannot write to file: $ofname:  $!";
close( OUTFILE );
open( OUTFILE, ">>$ofname" ) or die "Cannot write to file: $ofname:  $!";


# Load all strings to match that will be used for pattern-matching against genenames
open( PATFILE, $pat_file ) or die "Cannot open file: $pat_file : $!";
my @patterns;
my $i = 0;
while ( <PATFILE> )
  {
    $_ =~ s/x/\-/;
    @patterns[ $i++ ] = $_;
  }
close( PATFILE );

while ( <MYFILE> )
  {
    my $a = $_;


    if( $a =~ /\>/ )
      {
	my @header = split " ", $a;

	for( my $ii = 0; $ii < @patterns; ++$ii )
	  {
#	    print "$header[1] $patterns[$ii]";
	    my $pattern = $patterns[$ii];
	    $pattern =~ s/\n//;
	    if( $header[1] =~ $pattern )
	      {
		my $line = <MYFILE>;
		while ( <MYFILE> )
		  {
		    $b = $_;
		    #print $_;
		    if( $_ =~ /\>/ )
		      {
			my @parts  = split 'T', $line;
			my @parts2 = split 'C', $parts[0];
			my @parts3 = split 'G', $parts2[0];
			my @parts4 = split 'A', $parts3[0];
			# print $parts4[0];
			my $sequence = $parts4[0];
			my $stripped_seq = $sequence;
			$stripped_seq =~ s/\n//g;
			$a =~ s/\n//;
			
			# Create temporary fasta file for getorf
			if( length( $stripped_seq ) )
			  {
			    my @parts = split " ", $a;
			    print OUTFILE ">$parts[1] chrX * -1 -1 ".length( $stripped_seq )."\n";
			    toupper( $sequence );
			    $sequence =~ s/\n//g;
			    print OUTFILE "$sequence";
			  }
			print OUTFILE "\n";
			last;
		      }
		    $line = $line.$_;
		  }
	      }
	  }
      }
  }

close( OUTFILE );


sub toupper( @ )
{
  for ( my $i = 0; $i < @_; ++$i )
    {
      $_[$i] =~ tr/[a-z]/[A-Z]/;
    }
}
