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

#given name of PDB file  generates "shelled" child pdb files
#ie atoms/molecules that take part  in convex hull of data set removed iteratively
#

$sourcefilename=$ARGV[0];

# create directory for intermediate pdb files if it doesnt exist
$_=$sourcefilename;
#print $sourcefilename;
/data\/pdb(.*)\..*/;
$pdbname=$1;

#MODIFIED remmed this to not generate extra files
#print "pdbnameis $pdbname \n";
#if directory doesnt exist create it
#if (! -e "results/$pdbname"){
#    mkdir("results/$pdbname",0777) || die "couldnt create pdb results directory";
#}


$count=0;

$continue=1;

while ($continue==1){
	#takes name of pdb file provided as param and produces qhull format file from it
	system("./genqhull.prl $sourcefilename  |./count.prl temp.qhull");

	#check how many points are in this iteration 
	$points=0;
	
	# list temp file lines and count them  if 5 points or less (7 lines) done
	
	#count points
	foreach $_ (`cat temp.qhull`){
	$points++;
	}

	if ($points>7){

		#calls qhull with that file as input and has it output vertices of convex hull
		#(qhull does this by giving int idices into the input list)
		#redirect output to 1.hull

		$test=system("cat temp.qhull|./qhull/qhull/qhull -Fx >temp.hull");
		
		#if problem with qhull execution quit
		#this primarily functions to guard against degenerate pointset cases

		if ($test!=0){
		    $continue=0;
		}
		#MODIFIED to not save intermediate files
		#$resultfilename="results/".$filename."/".$count.".pdb";
		$resultfilename="results/temp/".$count.".pdb";

		#now need to make call to program which given qhull output and pdb file
		#generates new shelled pdb file
		
		system("./rebuild.prl temp.hull $sourcefilename ".$resultfilename." ".$ARGV[0]);

		$sourcefilename=$resultfilename;;
		$count++;
	}
	else {
		$continue=0;
	}

} #end for for number of shells




