#!/usr/bin/perl

use strict;
use warnings;

if(-e "$ENV{HOME}/scripts/jaiswallab/interactome_scripts/find_species.pl") {
	require "$ENV{HOME}/scripts/jaiswallab/interactome_scripts/find_species.pl";
}elsif(-e "$ENV{HOME}/jaiswallab_svn/interactome_scripts/find_species.pl") {
	require "$ENV{HOME}/jaiswallab_svn/interactome_scripts/find_species.pl";
}


if($#ARGV != 0) {
	print "usage: fasta_verify.pl fasta_file\n";
	exit;
}

my $in_file = $ARGV[0];

my $species = find_species($in_file);

open(in_file, "$in_file");

my $prev_line_is_header = 0;

my $counter = 0;

my %gene_id_hash;

my $error_counter = 0;
my $gene_counter = 0;

while(<in_file>) {
	my $line = $_;
	chomp $line;
	$counter++;
	
	# detect if two lines in a row are headers, if they are, print error and give line #
	my $curr_line_is_header = 0;
	if($line =~ /^>/) {
		$curr_line_is_header = 1;
		$gene_counter++;
	}
	
	if($curr_line_is_header == 1 && $prev_line_is_header == 1) {
		print "Error: Header found with no sequence data on line $counter in file $in_file\n";
		$error_counter++;
	}
	
	if($line =~ /Sequence\sunavailable/ && $prev_line_is_header == 1) {
			print "Error: Sequence unavailable text found on line $counter in file $in_file\n";
			$error_counter++;
	}
	
	# detect if line after header is blank
	if($line !~ /^[a-zA-Z*.]/ && $prev_line_is_header == 1) {
		print "Error: Blank line found on line $counter in file $in_file\n";
		$error_counter++;
	}

	# detect if line after header only contains a star - is effectively a bland line
	if($line =~ /^[*]$/ && $prev_line_is_header == 1) {
		print "Error: Blank line found on line $counter in file $in_file\n";
		$error_counter++;
	}
	
	# detect if header line has tabs in it
	if($curr_line_is_header ==1 && $line =~ /\t/) {
		print "Error: Tab character in header on line $counter in file $in_file\n";
		print "Reccommend using sed 's/\\t/\|/g' to replace tabs with pipe symbols\n";
		$error_counter++;
	}

	# set prev_line_header info for next time through loop
	if($curr_line_is_header) {
		$prev_line_is_header = 1;
		my $gene = find_gene($line,$species);
		#my $gene = $line; # use if already gone through fasta_header_fix.pl
		if(!defined($gene_id_hash{$gene})) {
			$gene_id_hash{$gene} = $line;
		}else{
			print "Error: gene $gene has multiple sequences associated with it in file $in_file\n";
			$error_counter++;
		}
	}else{
		$prev_line_is_header = 0;
	}
}

print "Number of errors = $error_counter\n";
print "Number of genes  = $gene_counter\n";
