<?php

//-------------------------------------------------------------------------------
// TRE_Module.php
// Handle checking, parsing, and writing of Nexus tree (.tre) files 
//
// written by Bart Meganck, Royal Museum for Central Africa
// bart.meganck@africamuseum.be
//
//
// This program is free & open source, under the GNU General Public License, v.2
// See : http://www.gnu.org/copyleft/gpl.html for more details.
//
//-------------------------------------------------------------------------------

class TRE_Module
{

	// array of arrays for storing point data
	private $points_array = array (

		 "id_array" => array(),
		 "name_array" => array(),
		 "latitude_array" => array(),
		 "longitude_array" => array(),
		 "coord_accuracy_array" => array(),
		 "begin_date_array" => array(),
		 "end_date_array" => array()
 
		 );
		 
		 
	private $input_file;
	private $input_line;
	private $input_fields = array();
	private $point_count = 0;
	private $output_file;
	private $return_string = "";
	
	// public function checkTREFile($input_file_path) {
	
		// check number of input_fields
		// check the used field delimiter
		// check first line : column headers or not ?
		// check each field, common errors like lat/lon switching 
	
	//	} // function checkTREFile 
	
	
	
	
	
	
	
	
	// search for a line with an equal sign 
	// see if that line has got multiple brackets
	// if so : BINGO ! read in from first bracket till semicolon
	
	public function readPointsFromTREFile($input_file_path) {
	
		$this->point_count = 0;
	
		$this->input_file = fopen($input_file_path,"r");
		
		$this->input_line = trim(fgets($this->input_file));
		
		$i=0;
		
		// skip all lines till we find the "translate" block
		while ((strpos($this->input_line,"TRANSLATE") === FALSE ) && (!feof($this->input_file)) ) {
			
				$this->input_line = trim(fgets($this->input_file));
				$i++;
			
		}
		
		// now read in alle the lines in the "translate" block, containing 
		// all the info we need : 
		// 1. the ID number of the taxon as used in the tree descriptions
		// 2. the label of the taxon : we'll use this to connect the tree information
		//     harvested here to the taxon point coordinates we get from the .csv file 
		
		//echo($i);
		
		// get rid of nasty whitespaces
		$inputstring = str_replace(" ","",$inputstring);


		$levels = array();


		$tempstring = $inputstring;
		$cnt = 0;
		$tl=0;
		$id = "my_id".$cnt;
		$i=1;

		// we search for a comma, then we check both sides of it
		//  if we find an opening bracket on the left and a closing bracket to the right,
		// we replace that part with a single node. So we replace the node pairs from the bottom
		// up, as long as we find comma's (no more comma's means all pairs have been substituted
		// by single nodes )
		while (substr_count($inputstring,",")>1) {

			$pos = strpos($inputstring,",",$fwpos);
			
			$fwpos = $pos + 1;
			$rwpos = $pos - 1;
			
			$ffwd=substr($inputstring,$fwpos,1); 
			$frwd=substr($inputstring,$rwpos,1); 

			// look forward till we find a bracket
			while ($ffwd <> ")" && $ffwd <> "(") {

				$ffwd=substr($inputstring,$fwpos,1); 
				$fwpos++;

			} // while $ffwd

			// check what kind of bracket we found
			if ($ffwd == "(") { /* not the type we were looking for : ignore */ }
			elseif ($ffwd == ")") { 
			
				// this could be something, if we find a matching opening bracket
				//  on the other side : look backwards for that
				while ($frwd <> ")" && $frwd <> "(") {

					$frwd=substr($inputstring,$rwpos,1); 
					$rwpos--;

				} // while $frwd

				// check what kind of bracket we found
				if ($frwd == "(")  {	  // yes! we have a hit ! 
	
			  		$cutstring = substr($inputstring,$rwpos+1,($fwpos-$rwpos-1));
			  		$no_brack1 = str_replace(")","",$cutstring);
			  		$no_brackets = str_replace("(","",$no_brack1);
			 		$pieces = explode(",",$no_brackets);

			  		$tempstring =  str_replace($cutstring,$id,$inputstring);
  		 	 		$cnt +=1;
  		 

  		 
  		  if (array_key_exists ($pieces[0],$levels)) {
  		  $lvl1 = $levels ["$pieces[0]"]["level"]; 
  		  }
  		  else {$levels ["$pieces[0]"]["level"] = 1;
  		          $lvl1=1;}

				  if (array_key_exists ($pieces[1],$levels)) {
			$lvl2 = $levels ["$pieces[1]"]["level"];
				  }
  		  else {$levels ["$pieces[1]"]["level"] = 1;
  		        $lvl2=1;}
  		  

  		    		 $lvl = max($lvl1,$lvl2)+1;
  		    	

  		  $levels["$id"]["level"] = $lvl;
  		  
  		  $lat["$id"]= min($lat[$pieces[0]],$lat[$pieces[1]]) + (( max($lat[$pieces[0]],$lat[$pieces[1]])
  		  		- min($lat[$pieces[0]],$lat[$pieces[1]]) ) /2);
  		  
  		  $lon["$id"]= min($lon[$pieces[0]],$lon[$pieces[1]]) + (( max($lon[$pieces[0]],$lon[$pieces[1]])
  		  		- min($lon[$pieces[0]],$lon[$pieces[1]]) ) /2);
  		  
  		  
  		  
  		  if (array_key_exists($pieces[0],$lat)) {
  		  
  		   //echo ($lvl);
  		  
  		   $outstring .= $lat[$pieces[0]].",".$lon[$pieces[0]].",";
  		   $outstring .= ($levels ["$pieces[0]"]["level"])*12000;
  		   $outstring .= "\n";

  		     $outstring .= $lat[$pieces[0]].",".$lon[$pieces[0]].",";
  		     $outstring .= ($lvl)*12000;
  		     $outstring .= "\n";
  		   
  		     
  		      		  
  		  }
  		  
  		    		  if (array_key_exists($pieces[1],$lat)) {
  		  
 

  		    
  		    $outstring .= $lat[$pieces[1]].",".$lon[$pieces[1]].",";
  		    $outstring .= ($lvl)*12000;
  		     $outstring .= "\n";

  		     
  		       		   // echo("<br/>");
  		     
  		     $outstring .= $lat[$pieces[1]].",".$lon[$pieces[1]].",";
  		     $outstring .= (($levels ["$pieces[1]"]["level"])*12000);
  		     $outstring .= "\n";
  		     
  		    // echo("<br/>");
  		      		  
  		  }

  		  
  		  // $color += 150;
  		  
  		$outstring .= ' </coordinates>
      </LineString>

    </Placemark>';
    
 //  $outstring .= ' <Placemark>
	//		<name>id1</name>
			

	//		<Point>
	//			<coordinates>';
	//			 $outstring .= $lat[$pieces[0]].",".$lon[$pieces[0]].",";
  	//	   $outstring .= $lvl*12000;
		//		$outstring .= '</coordinates>
	//		</Point>
	//	</Placemark>';
  		  
  		  
  		  // echo $lvl;
  		  
  		 $id = "my_id".$cnt;
  		 //echo($fwpos);
  		 $fwpos = $fwpos - ($fwpos-$rwpos-1);
  		 
  		 

  		   		    		   		 // echo ("<br/>");
  		 //echo($fwpos);
  		 // echo ("<br/>");
  		 // echo($tempstring);
	
	} // if $frwd


} // elseif
else {};


//$worksub = substr($inputstring,$pos,$len);
//$single = substr($worksub,0,1);

	
	//while ($single<>")" && $single<>"(" ) {
				
			//$worksub = substr($inputstring,$i,$count);		
			//$count++;
			//$single = substr($worksub,$count,1);
			//echo ($worksub);
			//echo('<br/>');
			//echo("$i");
			//echo($single);
			//echo('<br/>');
		
//		} // while
		
//		if ($single == ")") {}
//		else {}



$inputstring = $tempstring;
// }  // for $i


//echo ($tempstring);

$i++;
 } // while $inputstring <> ""
		
		//while (!feof($this->input_file)) {
		
	
		//	$this->points_array["id_array"][$this->point_count] = $this->input_fields[0];
		//	$this->points_array["name_array"][$this->point_count] = $this->input_fields[1];
		//	$this->points_array["latitude_array"][$this->point_count] = $this->input_fields[2];
		//	$this->points_array["longitude_array"][$this->point_count] = $this->input_fields[3];
		//	$this->points_array["coord_accuracy_array"][$this->point_count] = $this->input_fields[4];
		//	$this->points_array["begin_date_array"][$this->point_count] = $this->input_fields[5];
		//	$this->points_array["end_date_array"][$this->point_count] = $this->input_fields[6];
			
		//	$this->input_line = trim(fgets($this->input_file));
		//	$this->point_count++;
		
		//} 
		
		fclose($this->input_file);
	
		return($this->points_array);
	
	} //function readPointsFromTREFile
		 
} // class TRE_Module

?>