<?php
	//Description:
	//Parent_ID;Child|TFBS;Start;End;ID;Name
	header('Content-disposition: attachment; filename=reg_descriptions.csv'); 
	header('Content-Type: application/force-download');
	include ("connection.php");
	
	function printChildren($c, $b_id,$b_begin,$cp_id){	
		
		$khoueiry = "SELECT * FROM \"PROMOTER\" WHERE \"BASE_REG_ID\"=$cp_id AND \"PROMOTER_ID\"!=\"BASE_REG_ID\" AND \"MUTATION\"!='y';";	
		$stmt = pg_query($c,$khoueiry);
		
		while($row=pg_fetch_array($stmt)){
			$newcp_id = $row["PROMOTER_ID"];
			echo $b_id.";Child;".($row["BEGIN"]-$b_begin).";".($row["END"]-$b_begin).";".$row["PROMOTER_ID"].";".$row["NAME"]."\n";			
			printChildren($c, $b_id,$b_begin,$newcp_id);	  
		}
		  
	}
	
    $khoueiry = "SELECT * FROM \"PROMOTER\" WHERE \"IS_NATURAL\"='y' AND \"PROMOTER_ID\"=\"BASE_REG_ID\";";	
	$stmt = pg_query($c,$khoueiry);
	
	while($row=pg_fetch_array($stmt)){
	  	
	  	$base_id = $row["PROMOTER_ID"];
	  	$base_begin = $row["BEGIN"];
		
		//Print the TFBS	
	    $kh2 = "SELECT \"MOTIF_COORD_ID\", \"BEGIN\", \"STOP\", \"NAME\" FROM \"MOTIF_COORD\", \"MOTIF_REGUL\" WHERE \"PROMOTER_ID\"=$base_id AND \"MOTIF_COORD\".\"MOTIF_ID\"=\"MOTIF_REGUL\".\"MOTIF_ID\";";	
		$stmt2 = pg_query($c,$kh2);
		while($row2=pg_fetch_array($stmt2)){
			echo $base_id.";TFBS;".($row2["BEGIN"]-$base_begin).";".($row2["STOP"]-$base_begin).";".$row2["MOTIF_COORD_ID"].";".$row2["NAME"]."\n";
		}			
		
		//Print Child
		printChildren($c, $base_id,$base_begin,$base_id);
				  
	}	
		
?>