#!/usr/bin/perl -w

#################################GENERATE PREDICTED ANNOTATION FILES###############################################
#####                                                                                                         #####
###################################################################################################################

my $counter=0;
my $maxcount=`ls Grouped_Blat_Clustered/Cluster/ | wc -l`;
$maxcount++;
my $min=0;
my $max=0;
my $min_gff=0;
my $max_gff=0;
my $is_annotated=0;				

while($counter<$maxcount)
{
	if(open(CLUSTER, "< Grouped_Blat_Clustered/Cluster/dpl_ortho_cluster_$counter.blatout"))
	{
		while(<CLUSTER>)
		{
			my @column=split(" ", $_);

			if($column[1] =~ /(\S*)/)
			{
				my $contig=$1;
				
				if($column[3]>$column[2])
				{
					$min = $column[2];
					$max = $column[3];
				}
				else
				{
					$min = $column[3];
					$max = $column[2];
				}

				$is_annotated=0;				
				
				foreach(`grep $contig $gff_file | grep -E 'gene|repeat|biological|transcript|RNA|CDS|exon'`)				
				{
					my @column2=split(" ", $_);

							if($column2[4]>$column2[3])
							{
								$min_gff = $column2[3];
								$max_gff = $column2[4];
							}
							else
							{
								$min_gff = $column2[4];
								$max_gff = $column2[3];
							}
							
							my $tol=10;
							
							if(($min_gff>($min-$tol) && $min_gff<($max+$tol)) || ($max_gff>($min-$tol) && $max_gff<($max+$tol)) || ($min_gff<($min-$tol) && $max_gff>($max+$tol)) || ($min_gff>($min-$tol) && $max_gff<($max+$tol)))
							{
								$is_annotated=1;
							}
				}
				

				if($is_annotated==0)
				{
					open(ANNOTATION, ">> Grouped_Blat_Clustered/Predicted_Annotation/Predicted_Annotation_$counter.txt");
					print ANNOTATION $contig."\t".$column[2]."\t".$column[3]."\t".$column[5]."\t".($max-$min)."\t".$column[0]."\t".$column[4]."\n";
					close(ANNOTATION);
				}
				
			}
		}

		close(CLUSTER);
	}

		$counter++;
}