#!/usr/local/bin/perl 
#takes all localhull files and compiles into reports 
# localhullaminoacid.txt has sum for each entry 
# localhullpercentphobicity.txt has percent hydrophobicity
# localhullaveragephobicity.txt has average hydrophobicity

open (PHOBICOUT, ">localhullpercentphobicity.txt")||die "could not create reportfile";
open (COUNTOUT, ">localhullaminoacid.txt")||die "could not createreportfile";
open (AVEOUT, ">localhullaveragephobicity.txt")||die "could not create  report";

@files=qw(`ls *.localhull`);
initphobicityhash();

while (<@files>){
	#print $_ ."\n";
	(/(.*)\.localhull/);
	print PHOBICOUT $1."\t";
	print AVEOUT $1."\t";
	open (LOCALRESULT, $_);
	$phobic=0;
	$phylic=0;
	$count=0;
	$averagetotal=0;
	while(<LOCALRESULT>){
		#file is a list of amino acids
		#add entry to count for it
		$total{$_}+=1;

		# calc average and print it 
		#print $_."\n";
		/(.*)\n/;
		$currentacid=$phobicityhash{$1};
        	if($currentacid!=undef){
                	if ($currentacid>.1) {$phobic++;}
                	if ($currentacid<-.51){$phylic++;}      
			$count++;
			$averagetotal+=$currentacid;
		}
		#else {print $1."\n";}
	} # end while for one output file
	close LOCALRESULT;

	#print "count is ".$count." total is ".$averagetotal."\n";
	if ($count!=0){
	    print AVEOUT $averagetotal/$count."\t".$count."\n";
	}
	else {
	    print AVEOUT "-1\n";
	}

	if ($phylic+$phobic!=0){
        	print PHOBICOUT $phobic/($phylic+$phobic)."\t".$count."\n";
	}
	else {
        	print PHOBICOUT "-1"."\n";    
	}

} #done going over files


# print count to countfile
@thelist=keys(%total);
for ($counter=0;$counter<@thelist;$counter++){
	$val= "\t".$total{$thelist[$counter]}."\n";
	$_=$thelist[$counter];
	/(.*)\n/;
	print COUNTOUT $1.$val;
}

close PHOBICOUT;
close COUNTOUT;
close AVEOUT;
# end main

# intializes hash that contains hydrophobicity values
sub initphobicityhash
{
	# read in hydrophobicity values
	open (HYDRO, "scale.txt");
	while (<HYDRO>){
        	#print "in while";
        	/(.*)\s+(-?\d+\.\d+).*/;
        	$phobicityhash{$1}=$2;
	}        
}
