#!/usr/local/bin/perl -w

#given name of PDB file calculates for all CA's the %hydrophobic in 2.7A distance
# and in 5.6 A distance

#@CAx;
#@CAy;
#@CAz;

# read in hydrophobicity values
open (HYDRO, "results/scale.txt")||die "couldnt open scale";
while (<HYDRO>){
	#print "in while";
	/(.*)\s+(-?\d+\.\d+).*/;
	$phobicityhash{$1}=$2;
}

open (RESULT,">results/circlereport.txt")||die "couldnt open result";

@files=qw(`ls data/*.ent`);

while (<@files>){
    $sourcefilename=$_;
#    print RESULT $sourcefilename."\t";
    findCAposition();
#print $CAx[0]." ".$CAy[0]." ".$CAz[0];

    for ($caindex=0;$caindex<$#CAx;$caindex++){
	findinSpheres($CAx[$caindex],$CAy[$caindex],$CAz[$caindex]); 
	print "\n";
#print "phobic ".$phobic."phylic ".$phylic;
#	print RESULT $sourcefilename."\t";
	if ($phobic+$phylic<1){
#	    print RESULT "-1\t";
}
	else {
	    print RESULT ($phobic/($phobic+$phylic))."\t";
	}

	if ($phobic2+$phylic2<1){
#	    print RESULT "-1\t";
}
	else {
	    print RESULT ($phobic2/($phobic2+$phylic2))."\n";
	}
    }

    print RESULT "\n";
} # end while files



close RESULT;

#end main program

# goes through file to find amino acids within range of this
sub findinSpheres{
    $x=$_[0];;
    $y=$_[1];
    $z=$_[2];
    open (SOURCE, $sourcefilename)||die "couldn't open source in findin";
    $priorvalue=-1;
    $phobic=0;
    $phylic=0;
    $phobic2=0;
    $phylic2=0;

    while (<SOURCE>){
	if (/ATOM\s+\S+\s+\S+\s(\S+)\s+(\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+\d+.+\d+.+\d+.+/){
	    #print "matched atom";
	    
	    $distance=($x-$3)**2+($y-$4)**2+($z-$5)**2;
	#print $distance."\n";
	    $distance=$distance**.5;

	 #   print $distance."\n";
	 #   print $2."\n";
	    if (($priorvalue!=$2)&& ($distance<5.4)){
		
	#print "in inner sphere molecule".$1." at distance".$distance."\n" ;
		#print $phobicityhash{$1};
		$phob=$phobicityhash{$1};

		if ($phob>.1) {$phobic=$phobic+1;}
		if ($phob<-.51){$phylic=$phylic+1;}
	     }
	    else {
	
		if (($priorvalue ne $2)&& ($distance<11.2)){
		 #   print "new molecule ".$1." at distance ".$distance."\n";
		 #   print $phobicityhash{$1};
		    $phob=$phobicityhash{$1};
		    if ($phob>.1) {$phobic2=$phobic2+1;}
		    if ($phob<-.51){$phylic2=$phylic2+1;}
		} #end if

	    } #end else

	    $priorvalue=$2;
	}

    } #end of while 

    close SOURCE;
}

# goes through source file and stores xyz values for CA in arra
sub findCAposition{
    $counter=0;
    open (SOURCE, $sourcefilename)||die "couldnt open souce";
    while (<SOURCE>){
	if (/HETATM\s.+\s+CA.+\s+\d+\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+\d+.+\d+.+\d+.+/){
	    $CAx[$counter]=$1;
	    $CAy[$counter]=$2;
	    $CAz[$counter]=$3;
	    $counter++;
	}
    }
	close SOURCE;
}

