<?php
/*
	update-interactions.php
	@author: Daniel Sobral
	
	Provide functions to update interaction evidence when the status of an in-situ is changed
	
*/

/*
	Auxiliary function to simplify anatomy annotations
	Given a set of anatomical annotationsm it returns the simplest 
	set of annotations that the given set can originate
	e.g. if "a7.13" and "a7.13*" are annotated, it returns "a7.13 cell pair"
	
	parameters:
		$hierarch - anatomical hierarchy for the relevant stage
		$root - Root node in the hierarchy (typically "Whole Embryo")
		$lead_lsts - An array that associates to each anatomy a list of anatomy leafs
			e.g. "a7.13 cell pair" gives (a7.13 and a7.13*)
		$region_lst - An array of terms to simplify
	
	returns:
		an array of simplified terms
	
*/	
 
function simplify_hierarchy($hierarch,$root,$leaf_lsts,$region_lst){

	$ret_list = (array) null;	
	$expand_list = (array) null;
	foreach($region_lst as $region){ 
		if(isset($leaf_lsts[$region])){	$expand_list = array_merge($expand_list,$leaf_lsts[$region]); }
	}
	$parent_list = array($root);

	while(count($expand_list)>0){
		$child_list = (array)null;
		foreach ($parent_list as $cur_anat){		
			$cur_leafs = (array)null;	
			if(isset($leaf_lsts[$cur_anat])) { $cur_leafs = $leaf_lsts[$cur_anat]; }
			if(count(array_intersect($cur_leafs,$expand_list))>=count($cur_leafs)){
				$ret_list[]=$cur_anat;
			} else { 
				if(isset($hierarch[$cur_anat])){
					$child_list = array_merge($child_list, $hierarch[$cur_anat]);	
				}
			}
		}
		if(count($child_list)==0){ 	break; }
		$parent_list = $child_list;
	}		
	return $ret_list;
}

/*
	Deletes Interactions that use a given ISH as evidence
	$c - connection to ANISEED
	$ish - ISH for which evidences must be deleted 
*/
/*
function delete_evidence($c, $ish){
	$stmt = pg_query($c,"BEGIN");
	$khoueiry = "DELETE FROM \"REG_EVIDENCE\" WHERE \"EVIDENCE\"=".$ish.";";
	$stmt = pg_query($c,$khoueiry);
	$khoueiry = "DELETE FROM \"REG_EVIDENCE\" WHERE \"CONTROL\"=".$ish.";";
	$stmt = pg_query($c,$khoueiry);
	$stmt = pg_query($c,"END") or print "<h1>Error updating Interaction Database: contact administrators!</h1>";
}
*/

/*
	Adds Interactions using a given ISH as evidence
	(removes previous evidence using the given ISH)
	$c - connection to ANISEED
	$ish - new ISH evidences
*/
function update_evidence($c,$ish){
	//first delete all interactions that may have been based on this ISH
	
	//delete_evidence($c, $ish);	
	$khoueiry = "DELETE FROM \"REG_EVIDENCE\" WHERE \"EVIDENCE\"=".$ish.";";
	$stmt = pg_query($c,$khoueiry);
	$khoueiry = "DELETE FROM \"REG_EVIDENCE\" WHERE \"CONTROL\"=".$ish.";";
	$stmt = pg_query($c,$khoueiry);
	
	//Lets start by getting all information form the given in-situ; ignore embryo manipulations for the moment
	$khoueiry = "SELECT * FROM \"IN_SITU\" WHERE \"IN_SITU_ID\"=".$ish." AND \"IN_SITU_ID\" NOT IN (SELECT \"IN_SITU_ID\" FROM \"EMBRYO_MANIP\");";
	$stmt = pg_query($c,$khoueiry);
	if($ishinfo=pg_fetch_array($stmt)){
		//Only use curated and not private ISHs
		if(($ishinfo["CHECKED"]=='y') && ($ishinfo["PRIVATE"]!='y')){					
					
			//Variables required for later use 
			$hierarchy=(array) null;
			$anat_lst=(array) null;
			$inv_hierarchy=(array) null;
			$parent_lsts=(array) null;
			$leaf_lsts=(array) null;				
			$root;
			
			//Obtain values for most of the variables
			$khoueiry = "SELECT A.\"ANAT_ID\" AS \"CHILD\", B.\"ANAT_ID\" AS \"PARENT\", B.\"NAME\" FROM 
		\"ANAT_ENTITY\" A, \"ANAT_ENTITY\" B WHERE A.\"CHILD_OF\"=B.\"ANAT_ID\" AND A.\"DEV_STAGE_ID\"=".$ishinfo["DEV_STAGE_ID"].";";
			
			$stmt = pg_query($c,$khoueiry);	
			while($row=pg_fetch_array($stmt)){
				$inv_hierarchy[$row["CHILD"]]=$row["PARENT"];	
				$hierarchy[$row["PARENT"]][]=$row["CHILD"];
				$anat_lst[$row["CHILD"]]=1;	
				$anat_lst[$row["PARENT"]]=1;			
				if($row["NAME"]=='Whole embryo'){ $root = $row["PARENT"]; }
			}

			//Obtain lists of leafs - auxiliary data
			foreach ($anat_lst as $anat => $bogus){		
				$cur_par = $anat;		
				$par_lst=(array) null;
				while(true){
					$par_lst[count($par_lst)] = $cur_par;
					if(!isset($inv_hierarchy[$cur_par])){
						break;
					} 
					$cur_par = $inv_hierarchy[$cur_par];
				}
				$parent_lsts[$anat] = $par_lst;
				$to_process=array($anat);
				while(count($to_process)>0){
					$cur = array_pop($to_process);
					if(!isset($hierarchy[$cur])){
						$leaf_lsts[$anat][] = $cur;
					} else {
						foreach($hierarchy[$cur] as $child){
							array_push($to_process, $child);
						}
					}					
				}		
			}
			// End obtain auxiliary data
			
			//get expression data for this ISH and simplify it, divided by Targets...
			
			//Get data for constructs first...
			$construct_expression_data=(array) null;	
			$khoueiry = "SELECT DISTINCT \"TARGET_ID\", \"REGION_ID\" FROM \"TARGET\" WHERE \"IN_SITU_ID\"=$ish 
				AND \"TARGET_ID\" IN (SELECT \"CONSTRUCTION_ID\" FROM \"CONSTRUCTION\")";
			$stmt = pg_query($c,$khoueiry);	
			while($row=pg_fetch_array($stmt)){ 
				$arr = (array)null;
				if(isset($construct_expression_data[$row["TARGET_ID"]])){
					$arr = $construct_expression_data[$row["TARGET_ID"]];
				}
				if(isset($leaf_lsts[$row["REGION_ID"]])){
					$arr = array_merge($arr,$leaf_lsts[$row["REGION_ID"]]);
					$arr = array_unique($arr);
				}
				$construct_expression_data[$row["TARGET_ID"]] = $arr;			
			}
			foreach ($construct_expression_data as $construct_id => $regions){		
				update_reg_evidence($c, $ish, $ishinfo, $construct_id, $regions,
									$hierarchy,$root,$leaf_lsts,$parent_lsts);
			}
			
			// Get true gene expression... constructs have no immediate cluster_id associated so this query will return empty in that case...
			$gene_expression_data=(array) null;	
			$khoueiry = " SELECT DISTINCT \"CLUSTER_ID\", \"REGION_ID\" FROM \"TARGET\", \"TARGET_TO_CLUSTER\"
			WHERE \"TARGET\".\"TARGET_ID\"=\"TARGET_TO_CLUSTER\".\"TARGET_ID\" AND \"IN_SITU_ID\"=$ish";
			$stmt = pg_query($c,$khoueiry);	
			while($row=pg_fetch_array($stmt)){ 
				$arr = (array)null;
				if(isset($gene_expression_data[$row["CLUSTER_ID"]])){
					$arr = $gene_expression_data[$row["CLUSTER_ID"]];
				}
				if(isset($leaf_lsts[$row["REGION_ID"]])){
					$arr = array_merge($arr,$leaf_lsts[$row["REGION_ID"]]);
					$arr = array_unique($arr);
				}
				$gene_expression_data[$row["CLUSTER_ID"]] = $arr; 
			}			
			
			
			foreach ($gene_expression_data as $cluster_id => $regions){			
			
				update_ish_evidence($c, $ish, $ishinfo, $cluster_id, $regions,
									$hierarchy,$root,$leaf_lsts,$parent_lsts);
			}
			
		}
	}
}

/*
	Auxiliary function
	Add evidence related to in-situ data
*/
function update_ish_evidence($c, $ish, $ishinfo, $cluster_id, $regions, 
								$hierarch,$root,$leaf_lsts,$parent_lsts){
														
	$stage = $ishinfo["DEV_STAGE_ID"];
	
	////////////////////////////////////////JGI
	$khoueiry = "SELECT \"IN_SITU_ID\" FROM \"IN_SITU\" WHERE 
		\"DEV_STAGE_ID\"=$stage AND \"CHECKED\"='y' AND \"PRIVATE\"='n' AND ";			
	
	if($ishinfo["WILD_TYPE"]=='y'){	
		$khoueiry = $khoueiry . "\"IN_SITU_ID\" IN (SELECT \"IN_SITU_ID\" FROM \"MUTANT\") AND 
			\"IN_SITU_ID\" NOT IN (SELECT \"IN_SITU_ID\" FROM \"EMBRYO_MANIP\") AND ";
	} else {
		$khoueiry = $khoueiry . " \"WILD_TYPE\"='y' AND ";
	}	
	$khoueiry = $khoueiry . "\"IN_SITU_ID\" IN 
	(SELECT DISTINCT \"IN_SITU_ID\" FROM \"TARGET\" WHERE \"TARGET_ID\" IN 
			(SELECT \"TARGET_ID\" FROM \"TARGET_TO_CLUSTER\" WHERE \"CLUSTER_ID\"='$cluster_id'))";
	
	$comp_insitus=(array) null;
	$stmt = pg_query($c,$khoueiry);
	while($row=pg_fetch_array($stmt)){ $comp_insitus[] = $row["IN_SITU_ID"]; }
	
	
	$stmt = pg_query($c,$khoueiry);
	while($row=pg_fetch_array($stmt)){ $comp_insitus[] = $row["IN_SITU_ID"]; }	
	
	$comp_insitus = array_unique($comp_insitus);
	
	////Go through all ISH
	for ($k=0;$k<count($comp_insitus);$k++) {	
	
	
		$cur_ish = $comp_insitus[$k];
			
		//TODO: Carefull: Each ISH can only have 1 target... otherwise this causes problems!
		$khoueiry = "SELECT DISTINCT \"REGION_ID\", \"ANAT_ENTITY\".\"NAME\" FROM \"TARGET\", \"ANAT_ENTITY\" WHERE \"REGION_ID\"=\"ANAT_ID\" AND \"IN_SITU_ID\"=".$cur_ish;	
		$stmt = pg_query($c,$khoueiry);
		$comp_regions=(array) null;		
		while($row=pg_fetch_array($stmt)){ 
			if(isset($leaf_lsts[$row["REGION_ID"]])){
				$comp_regions = array_unique(array_merge($comp_regions,$leaf_lsts[$row["REGION_ID"]]));		
			}
		}		
			
		//Obtain perturbed genes,
		$up_down = (array) null;	
		$conflicts = (array) null;
		
		$khoueiry = "SELECT \"NAME\", \"UP_DOWN\" FROM \"MUTANT\" WHERE \"IN_SITU_ID\"=";
		if($ishinfo["WILD_TYPE"]=='n'){	
			$khoueiry = $khoueiry.$ish;
		} else {
			$khoueiry = $khoueiry.$cur_ish;
		}
		$stmt = pg_query($c,$khoueiry);	
				
		$count = 0;
		while($row=pg_fetch_array($stmt)){ 
			$up_down[$row["NAME"]] = $row["UP_DOWN"];
			$count++;						
		}					
		if($count !== 1) { continue; }	
			
		//Find the names for the perturbed genes
		$pert_trans = (array) null;	
		foreach ($up_down as $name => $pert){  
			$khoueiry = "SELECT \"GENE_CLUSTER_ID\" FROM \"GENE_CONCEPT\" WHERE \"GENE_MODEL_ID\" IN 
				(SELECT \"GENE_ID\" FROM \"GENE\" WHERE \"NAME\"='$name');";
			$stmt = pg_query($c,$khoueiry);	
			if($row=pg_fetch_array($stmt)){ 
				$pert_trans[$name] = $row["GENE_CLUSTER_ID"]; 
			}
		}
			
		$stage = $ishinfo["DEV_STAGE_ID"];
		
		$wt_ish = $ish;
		$mut_ish = $cur_ish;
		$wt_regions = $regions;
		$mut_regions = $comp_regions;
		if($ishinfo["WILD_TYPE"]=='n'){	
			$wt_ish = $cur_ish;
			$mut_ish = $ish;
			$wt_regions = $comp_regions;
			$mut_regions = $regions;
		}
		
		foreach ($up_down as $pert_gene => $perturbation) {
				
			$aff_gene = $pert_trans[$pert_gene];
			
			if(!in_array($pert_gene, $conflicts)){
				$up_regions = (array)null;
				$down_regions = (array)null;
			
				if($perturbation=='downregulated'){
					$up_regions = array_diff($wt_regions, $mut_regions);
					$down_regions = array_diff($mut_regions, $wt_regions);
				} else {
					$down_regions = array_diff($wt_regions, $mut_regions);
					$up_regions = array_diff($mut_regions, $wt_regions);
				}
			
				$up_regions  = simplify_hierarchy($hierarch,$root,$leaf_lsts,$up_regions);
				$down_regions  = simplify_hierarchy($hierarch,$root,$leaf_lsts,$down_regions);
			
				foreach($up_regions as $up_region){
					print "$aff_gene indirectly upregulates $cluster_id in $up_region : $ish - $cur_wt</br>";
					$khoueiry = "INSERT INTO \"REG_EVIDENCE\" (\"GENE_X\", \"GENE_Y\", \"TYPE\", \"REG_ANAT\", \"DIRECT\", \"EVIDENCE\", \"CONTROL\", \"DEV_STAGE_ID\", \"PERT_TYPE\") VALUES ('$aff_gene', '$cluster_id', 'upregulates', $up_region, 'n', $mut_ish, $wt_ish, $stage,'$perturbation') ";	
					$stmt = pg_query($c,$khoueiry) or die("ERROR: ".pg_last_error($c));
				}
				foreach($down_regions as $down_region){
				
					print "$aff_gene indirectly downregulates $cluster_id in $down_region : $ish - $cur_wt</br>";
					$khoueiry = "INSERT INTO \"REG_EVIDENCE\" (\"GENE_X\", \"GENE_Y\", \"TYPE\", \"REG_ANAT\", \"DIRECT\", \"EVIDENCE\", \"CONTROL\", \"DEV_STAGE_ID\",\"PERT_TYPE\") VALUES ('$aff_gene', '$cluster_id', 'downregulates', $down_region, 'n', $mut_ish, $wt_ish, $stage,'$perturbation') ";
					$stmt = pg_query($c,$khoueiry) or die("ERROR: ".pg_last_error($c));
				}
			}
		}
		
	}
			
}
	

/*
	Auxiliary function to correct LacZ issues in evidences using constructs...
*/	
function back_lineage($stage,$regions,$c){
	$new_regions = $regions;
	while(count($new_regions)>0){		
		$new_stage = $stage;
		$new_regions = (array)null;
		$backable = true;
		
		$khoueiry = "SELECT \"MOTHER_CELL\", \"DEV_STAGE_ID\" FROM \"LINEAGE\", \"ANAT_ENTITY\" WHERE \"MOTHER_CELL\"=\"ANAT_ID\" AND \"DAUGHTER_CELL\" IN (".implode($regions, ",").");";
		$stmt = pg_query($c,$khoueiry);	
		while($row=pg_fetch_array($stmt)){ 
			$new_stage = $row["DEV_STAGE_ID"]; 
			$new_regions[] = $row["MOTHER_CELL"]; 
		}
			
$khoueiry = "SELECT \"DAUGHTER_CELL\" FROM \"LINEAGE\" WHERE \"MOTHER_CELL\" IN (".implode($new_regions, ",").");";				
		$stmt = pg_query($c,$khoueiry);	
		while($row=pg_fetch_array($stmt)){ 
			if(!in_array($row["DAUGHTER_CELL"],$regions)){ $backable = false; break; }				
		}
		if(!$backable) { break; } else { $regions = $new_regions; $stage = $new_stage; }
	}
	$to_return["stage"]=$stage;
	$to_return["regions"]=$regions;
	return $to_return;
}
	
/*
	Auxiliary function 	
	Add evidence related to regulatory regions
*/
function update_reg_evidence($c, $ish, $ishinfo, $construct_id, $regions,
							$hierarch,$root,$leaf_lsts,$parent_lsts) {						
							
	$stage = $ishinfo["DEV_STAGE_ID"];
			
	$khoueiry="SELECT \"PROMOTER_ID\" FROM \"CONSTRUCTION\" WHERE \"CONSTRUCTION_ID\"=$construct_id";	
	$stmt = pg_query($c,$khoueiry);	
	if($row=pg_fetch_array($stmt)){ 
		$promoter_id = $row["PROMOTER_ID"];
		
		//Check to which gene is this region associated to 
		$regulated_genes = (array)null;
		$khoueiry="SELECT \"GENE_CLUSTER_ID\" FROM \"GENE_REGULATION\", \"GENE_CONCEPT\"
			WHERE \"GENE_MODEL_ID\"=\"GENE_ID\" AND \"PROMOTER_ID\"=$promoter_id";	
		$stmt = pg_query($c,$khoueiry);
		while($row=pg_fetch_array($stmt)){
			if(!in_array($row["GENE_CLUSTER_ID"],$regulated_genes)){
				$regulated_genes[]=$row["GENE_CLUSTER_ID"];
			}
		}

		//If there are no genes it's no use to continue
		if(count($regulated_genes)==0) { return; }
		
		/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//Check indirect evidence...
		
		$expr = (array)null;		
		if($ishinfo["WILD_TYPE"]=='y'){
			
			$expr = (array)null;
			$khoueiry="SELECT \"TARGET\".\"IN_SITU_ID\", \"REGION_ID\", \"WILD_TYPE\", \"CHECKED\" FROM 
				\"TARGET\", \"IN_SITU\" WHERE \"DEV_STAGE_ID\"=$stage AND 
				\"TARGET\".\"IN_SITU_ID\" = \"IN_SITU\".\"IN_SITU_ID\" AND 
				\"TARGET\".\"IN_SITU_ID\" IN (SELECT \"IN_SITU_ID\" FROM \"MUTANT\") AND
				\"TARGET\".\"IN_SITU_ID\" NOT IN (SELECT \"IN_SITU_ID\" FROM \"EMBRYO_MANIP\") AND
				\"TARGET_ID\" IN 
				(SELECT \"CONSTRUCTION_ID\" FROM \"CONSTRUCTION\" WHERE \"PROMOTER_ID\"=$promoter_id);";
			$stmt = pg_query($c,$khoueiry);
			while($row=pg_fetch_array($stmt)){ 
				if(($row["CHECKED"]=="y")){
					$arr = (array)null;
					if(isset($expr[$row["IN_SITU_ID"]])){
						$arr = $expr[$row["IN_SITU_ID"]];
					}
					if(isset($leaf_lsts[$row["REGION_ID"]])){
						$arr = array_merge($arr,$leaf_lsts[$row["REGION_ID"]]);
						$arr = array_unique($arr);
					}
					$expr[$row["IN_SITU_ID"]] = $arr; 
				}
			}
			
		} else {
			
			$expr = (array)null;
			$khoueiry="SELECT \"TARGET\".\"IN_SITU_ID\", \"REGION_ID\", \"WILD_TYPE\", \"CHECKED\" FROM 
				\"TARGET\", \"IN_SITU\" WHERE \"DEV_STAGE_ID\"=$stage AND 
				\"TARGET\".\"IN_SITU_ID\" = \"IN_SITU\".\"IN_SITU_ID\" AND 
				\"TARGET_ID\" IN 
				(SELECT \"CONSTRUCTION_ID\" FROM \"CONSTRUCTION\" WHERE \"PROMOTER_ID\"=$promoter_id);";
			$stmt = pg_query($c,$khoueiry);
			while($row=pg_fetch_array($stmt)){ 
				if(($row["CHECKED"]=="y") && ($row["WILD_TYPE"]=="y")){
					$arr = (array)null;
					if(isset($expr[$row["IN_SITU_ID"]])){
						$arr = $expr[$row["IN_SITU_ID"]];
					}
					if(isset($leaf_lsts[$row["REGION_ID"]])){
						$arr = array_merge($arr,$leaf_lsts[$row["REGION_ID"]]);
						$arr = array_unique($arr);
					}
					$expr[$row["IN_SITU_ID"]] = $arr; 
				}
			}
		
		}
		
		foreach ($expr as $exp_ish => $exp_regions) {
	
			//Obtain the genes that are affected: regulators...
			//Obtain perturbed genes,
			$regulating_genes= (array) null;	
			$conflicts = (array) null;
		
			$khoueiry = "SELECT \"NAME\", \"UP_DOWN\" FROM \"MUTANT\" WHERE \"IN_SITU_ID\"=";
			if($ishinfo["WILD_TYPE"]=='n'){	
				$khoueiry = $khoueiry.$ish;
			} else {
				$khoueiry = $khoueiry.$cur_ish;
			}
			$stmt = pg_query($c,$khoueiry);

			
			$count = 0;
			while($row=pg_fetch_array($stmt)){ 
				$regulating_genes[$row["NAME"]] = $row["UP_DOWN"];
				$count++;						
			}					
			if($count !== 1) { continue; }	
			
			//Find the names for the perturbed genes
			$pert_trans = (array) null;	
			foreach ($regulating_genes as $name => $pert){  
				$khoueiry = "SELECT \"GENE_CLUSTER_ID\" FROM \"GENE_CONCEPT\" WHERE \"GENE_MODEL_ID\" IN 
					(SELECT \"GENE_ID\" FROM \"GENE\" WHERE \"NAME\"='$name');";
				$stmt = pg_query($c,$khoueiry);	
				if($row=pg_fetch_array($stmt)){ 
					$pert_trans[$name] = $row["GENE_CLUSTER_ID"]; 
				}
			}
			
			$wt_ish = $ish;
			$mut_ish = $exp_ish;
			$wt_regions = $regions;
			$mut_regions = $exp_regions;
			
			if($ishinfo["WILD_TYPE"]=='n'){
				$wt_ish = $exp_ish;
				$mut_ish = $ish;
				$mut_regions = $regions;
				$wt_regions = $exp_regions;			
			}
			
			foreach($regulated_genes as $regulated_gene){				
				foreach ($regulating_genes as $pert_gene => $perturbation) {
					
					$regulating_gene = $pert_trans[$pert_gene];

					if(!in_array($pert_gene, $conflicts)){
						
						$up_regions = (array)null;
						$down_regions = (array)null;
			
						if($perturbation=='downregulated'){
							$up_regions = array_diff($wt_regions, $mut_regions);
							$down_regions = array_diff($mut_regions, $wt_regions);
						} else {
							$down_regions = array_diff($wt_regions, $mut_regions);
							$up_regions = array_diff($mut_regions, $wt_regions);
						}
			
						$up_regions  = simplify_hierarchy($hierarch,$root,$leaf_lsts,$up_regions);
						$down_regions  = simplify_hierarchy($hierarch,$root,$leaf_lsts,$down_regions);
						
						// search back in lineage...
						$backed = back_lineage($stage,$up_regions,$c);
						$new_stage = $backed["stage"];
						$up_regions = $backed["regions"];
						
						foreach($up_regions as $up_region){
						
							//DEBUG
							print "$regulating_gene indirectly upregulates $regulated_gene in $up_region : $mut_ish - $wt_ish (using reg region analysis)</br>";
				
							$khoueiry = "INSERT INTO \"REG_EVIDENCE\" (\"GENE_X\", \"GENE_Y\", \"TYPE\", \"REG_ANAT\", \"DIRECT\", \"EVIDENCE\", \"CONTROL\", \"DEV_STAGE_ID\", \"PERT_TYPE\") VALUES ('$regulating_gene', '$regulated_gene', 'upregulates', $up_region, 'n', $mut_ish, $wt_ish, $new_stage,'$perturbation') ";	
							$stmt = pg_query($c,$khoueiry) or die("ERROR: ".pg_last_error($c));
						}
						
						// search back in lineage...
						$backed = back_lineage($stage,$down_regions,$c);
						$new_stage = $backed["stage"];
						$down_regions = $backed["regions"];
						
						foreach($down_regions as $down_region){
						
							//DEBUG
							print "$regulating_gene indirectly downregulates $regulated_gene in $down_region : $mut_ish  - $wt_ish (using reg region analysis)</br>";
				
							$khoueiry = "INSERT INTO \"REG_EVIDENCE\" (\"GENE_X\", \"GENE_Y\", \"TYPE\", \"REG_ANAT\", \"DIRECT\", \"EVIDENCE\", \"CONTROL\", \"DEV_STAGE_ID\", \"PERT_TYPE\") VALUES ('$regulating_gene', '$regulated_gene', 'downregulates', $down_region, 'n', $mut_ish, $wt_ish, $new_stage,'$perturbation') ";	
							$stmt = pg_query($c,$khoueiry) or die("ERROR: ".pg_last_error($c));
						}
					}
				}
			}
						
		}
		
		
		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//Check direct evidence
		//Get Children
		
		//REMOVE ME
		print "getting children</br>";
							
		$children = (array)null;
		$proc = array($promoter_id);		
		while(count($proc)>0){ 		
			$current = array_pop($proc);					
			$khoueiry = "SELECT \"PROMOTER_ID\" FROM \"PROMOTER\" WHERE 
				\"BASE_REG_ID\"=$current AND \"PROMOTER_ID\"!=$current";
			$stmt = pg_query($c,$khoueiry);
			while($row=pg_fetch_array($stmt)){
				array_push($proc,$row["PROMOTER_ID"]);
				$children[] = $row["PROMOTER_ID"];				
			}			
		}	
		
		//REMOVE ME
		foreach ($children as $child) { print " child ".$child."</br>"; }
		
		//REMOVE ME
		print "getting parents</br>";
		//Get Parents
		$parents = (array)null;
		$proc = array($promoter_id);		
		while(count($proc)>0){ 		
			$current = array_pop($proc);					
			$khoueiry = "SELECT \"BASE_REG_ID\" FROM \"PROMOTER\" WHERE \"PROMOTER_ID\"=$current";
			$stmt = pg_query($c,$khoueiry);
			if($row=pg_fetch_array($stmt)){
				if($row["BASE_REG_ID"] != $current){
					array_push($proc,$row["BASE_REG_ID"]);
				}
				$parents[] = $row["BASE_REG_ID"];
			}			
		}
		
		//REMOVE ME
		foreach ($parents as $parent) { print " parent ".$parent."</br>"; }
		
		//Get motifs
		$current_motifs = (array)null;
		$khoueiry = "SELECT \"MOTIF_ID\", \"BEGIN\", \"MOTIF_COORD_ID\" FROM \"MOTIF_COORD\" WHERE \"PROMOTER_ID\"=$promoter_id";
		$stmt = pg_query($c,$khoueiry);
		while($row=pg_fetch_array($stmt)){
			$current_motifs[$row["MOTIF_ID"]][$row["BEGIN"]] = $row["MOTIF_COORD_ID"];
		}
		
		//Get children motifs
		$children_motifs = (array)null;
		if(count($children)>0){			
			$khoueiry = "SELECT \"PROMOTER_ID\", \"MOTIF_ID\", \"BEGIN\", \"MOTIF_COORD_ID\" FROM \"MOTIF_COORD\" 
				WHERE \"PROMOTER_ID\" IN (".implode(",",$children).")";
			$stmt = pg_query($c,$khoueiry);
			while($row=pg_fetch_array($stmt)){
				$children_motifs[$row["PROMOTER_ID"]][$row["MOTIF_ID"]][$row["BEGIN"]] = $row["MOTIF_COORD_ID"];
			}
		}
		
		//Get parent motifs
		$parents_motifs = (array)null;
		if(count($parents)>0){
			$khoueiry = "SELECT \"PROMOTER_ID\", \"MOTIF_ID\", \"BEGIN\", \"MOTIF_COORD_ID\" FROM \"MOTIF_COORD\" 
				WHERE \"PROMOTER_ID\" IN (".implode(",",$parents).")";
			$stmt = pg_query($c,$khoueiry);
			while($row=pg_fetch_array($stmt)){
				$parents_motifs[$row["PROMOTER_ID"]][$row["MOTIF_ID"]][$row["BEGIN"]] = $row["MOTIF_COORD_ID"];
			}				
		}

		foreach ($children_motifs as $child_promoter => $child_motifs) {							
		
			$change == 0;
			foreach ($current_motifs as $motif => $coords_list){			
				foreach ($coords_list as $begin => $motif_coord){
					if(!isset($child_motifs[$motif]) || !isset($child_motifs[$motif][$begin])){
						$change++;
						break;
					}
				}
			}
			
			// only allow to have one site affected...
			if($change==1) {
		
			foreach ($children_motifs as $child_promoter => $child_motifs) {
				foreach ($current_motifs as $motif => $coords_list){			
					foreach ($coords_list as $begin => $motif_coord){
				
						//Get genes associated to motif
						$site_genes=(array)null;
						$khoueiry="SELECT \"GENE_CLUSTER_ID\" FROM \"MOTIF_COORD_GENE\", \"GENE_CONCEPT\" WHERE \"GENE_MODEL_ID\"=\"GENE_ID\" AND \"MOTIF_COORD_ID\"=$motif_coord";
						$stmt = pg_query($c,$khoueiry);	
						while($row=pg_fetch_array($stmt)){
							if(!in_array($row["GENE_CLUSTER_ID"],$site_genes)){
								$site_genes[] = $row["GENE_CLUSTER_ID"];
							}
						}
					
						if(!isset($child_motifs[$motif]) || !isset($child_motifs[$motif][$begin])){
					
							//Check all ISH of this child against the current ISH
							$child_regions = (array)null;
							$khoueiry="SELECT \"TARGET\".\"IN_SITU_ID\", \"TARGET_ID\", \"REGION_ID\", 
							\"WILD_TYPE\", \"CHECKED\" FROM \"TARGET\", \"IN_SITU\" WHERE 
							\"DEV_STAGE_ID\"=$stage AND 
							\"TARGET\".\"IN_SITU_ID\" = \"IN_SITU\".\"IN_SITU_ID\" AND \"TARGET_ID\" IN 
						(SELECT \"CONSTRUCTION_ID\" FROM \"CONSTRUCTION\" WHERE \"PROMOTER_ID\"=$child_promoter);";
							$stmt = pg_query($c,$khoueiry);
							while($row=pg_fetch_array($stmt)){ 
								if(($row["CHECKED"]=="y") && ($row["WILD_TYPE"]=="y")){							
									$arr = (array)null;
									if(isset($child_regions[$row["TARGET_ID"]][$row["IN_SITU_ID"]])){
										$arr = $child_regions[$row["TARGET_ID"]][$row["IN_SITU_ID"]];
									}
									if(isset($leaf_lsts[$row["REGION_ID"]])){
										$arr = array_merge($arr,$leaf_lsts[$row["REGION_ID"]]);
										$arr = array_unique($arr);
									}
									$child_regions[$row["TARGET_ID"]][$row["IN_SITU_ID"]] = $arr;
								}
							}	
						
							foreach ($children_regions as $target => $ish_list){
								foreach ($ish_list as $child_ish => $child_regions){								
								
									$up_regions = simplify_hierarchy($hierarch, $root,$leaf_lsts,
																array_diff($regions, $child_regions));
																				
									$down_regions = simplify_hierarchy($hierarch,$root,$leaf_lsts,
																	array_diff($child_regions,$regions));
								
									// search back in lineage...
									$backed = back_lineage($stage,$down_regions,$c);
									$new_stage_down = $backed["stage"];
									$down_regions = $backed["regions"];
								
									// search back in lineage...
									$backed = back_lineage($stage,$up_regions,$c);
									$new_stage_up = $backed["stage"];
									$up_regions = $backed["regions"];
								
									foreach ($regulated_genes as $regulated_gene) {
										foreach ($site_genes as $site_gene) {
											foreach ($up_regions as $up_region) {
												$khoueiry = "INSERT INTO \"REG_EVIDENCE\" (\"GENE_X\", \"GENE_Y\", \"TYPE\", \"REG_ANAT\", \"DIRECT\", \"EVIDENCE\", \"CONTROL\", \"DEV_STAGE_ID\") VALUES ('$site_gene', '$regulated_gene', 'upregulates', $up_region, 'y', $child_ish, $ish, $new_stage_up) ";	
												$stmt = pg_query($c,$khoueiry) or die("ERROR!");	
												print "Gene $site_gene directly upregulates $regulated_gene in $up_region: $child_ish - $ish<br/>";
											}
										
											foreach ($down_regions as $down_region) {
												$khoueiry = "INSERT INTO \"REG_EVIDENCE\" (\"GENE_X\", \"GENE_Y\", \"TYPE\", \"REG_ANAT\", \"DIRECT\", \"EVIDENCE\", \"CONTROL\", \"DEV_STAGE_ID\") VALUES ('$site_gene', '$regulated_gene', 'downregulates', $down_region, 'y', $child_ish, $ish, $new_stage_down) ";	
												$stmt = pg_query($c,$khoueiry) or die("ERROR!");	
												print "Gene $site_gene directly downregulates $regulated_gene in $down_region: $child_ish - $ish<br/>";
											}
										}
									}								
								}
							}
						}	
					}			
				}	
			}
		} //END if			
	}		

					
		foreach ($parents_motifs as $parent_promoter => $parent_motifs) {
			$change == 0;
			foreach ($parent_motifs as $motif => $coords_list){						
				foreach ($coords_list as $begin => $motif_coord){
					if(!isset($current_motifs[$motif]) || !isset($current_motifs[$motif][$begin])){
						$change++;
						break;
					}
				}
			}
			
			if($change==1){
				foreach ($parents_motifs as $parent_promoter => $parent_motifs) {
					foreach ($parent_motifs as $motif => $coords_list){						
						foreach ($coords_list as $begin => $motif_coord){
					
							//Get genes associated to motif
							$site_genes=(array)null;
							$khoueiry="SELECT \"GENE_CLUSTER_ID\" FROM \"MOTIF_COORD_GENE\", \"GENE_CONCEPT\" WHERE \"GENE_MODEL_ID\"=\"GENE_ID\" AND \"MOTIF_COORD_ID\"=$motif_coord";
							$stmt = pg_query($c,$khoueiry);	
							while($row=pg_fetch_array($stmt)){
								if(!in_array($row["GENE_CLUSTER_ID"],$site_genes)){
									$site_genes[] = $row["GENE_CLUSTER_ID"];
								}
							}
				
							if(!isset($current_motifs[$motif]) || !isset($current_motifs[$motif][$begin])){
					
								//Check all ISH of this parent against the current ISH						
								$parent_regions = (array)null;
								$khoueiry="SELECT \"TARGET\".\"IN_SITU_ID\", \"TARGET_ID\", \"REGION_ID\", 
							\"WILD_TYPE\", \"CHECKED\" FROM \"TARGET\", \"IN_SITU\" WHERE 
							\"DEV_STAGE_ID\"=$stage AND 
							\"TARGET\".\"IN_SITU_ID\" = \"IN_SITU\".\"IN_SITU_ID\" AND \"TARGET_ID\" IN 
					(SELECT \"CONSTRUCTION_ID\" FROM \"CONSTRUCTION\" WHERE \"PROMOTER_ID\"=$parent_promoter);";
								$stmt = pg_query($c,$khoueiry);
								while($row=pg_fetch_array($stmt)){ 
									if(($row["CHECKED"]=="y") && ($row["WILD_TYPE"]=="y")){	
										$arr = (array)null;
										if(isset($parent_regions[$row["TARGET_ID"]][$row["IN_SITU_ID"]])){
											$arr = $parent_regions[$row["TARGET_ID"]][$row["IN_SITU_ID"]];
										}
										if(isset($leaf_lsts[$row["REGION_ID"]])){
											$arr = array_merge($arr,$leaf_lsts[$row["REGION_ID"]]);
											$arr = array_unique($arr);
										}
										$parent_regions[$row["TARGET_ID"]][$row["IN_SITU_ID"]] = $arr;	
									}
								}	
						
								foreach ($parent_regions as $target => $ish_list){
									foreach ($ish_list as $parent_ish => $mother_regions){
							
										$up_regions = simplify_hierarchy($hierarch, $root,$leaf_lsts,
																array_diff($mother_regions, $regions));
																				
										$down_regions = simplify_hierarchy($hierarch,$root,$leaf_lsts,
																	array_diff($regions,$mother_regions));
								
										// search back in lineage...
										$backed = back_lineage($stage,$down_regions,$c);
										$new_stage_down = $backed["stage"];
										$down_regions = $backed["regions"];

										// search back in lineage...
										$backed = back_lineage($stage,$up_regions,$c);
										$new_stage_up = $backed["stage"];
										$up_regions = $backed["regions"];			
								
										foreach ($regulated_genes as $regulated_gene) {
											foreach ($site_genes as $site_gene) {
												foreach ($up_regions as $up_region) {
													$khoueiry = "INSERT INTO \"REG_EVIDENCE\" (\"GENE_X\", \"GENE_Y\", \"TYPE\", \"REG_ANAT\", \"DIRECT\", \"EVIDENCE\", \"CONTROL\", \"DEV_STAGE_ID\") VALUES ('$site_gene', '$regulated_gene', 'upregulates', $up_region, 'y', $ish, $parent_ish, $new_stage_up) ";	
													$stmt = pg_query($c,$khoueiry) or die("ERROR!");	
													print "Gene $site_gene directly upregulates $regulated_gene in $up_region: $ish - $parent_ish<br/>";
												}
										
												foreach ($down_regions as $down_region) {
													$khoueiry = "INSERT INTO \"REG_EVIDENCE\" (\"GENE_X\", \"GENE_Y\", \"TYPE\", \"REG_ANAT\", \"DIRECT\", \"EVIDENCE\", \"CONTROL\", \"DEV_STAGE_ID\") VALUES ('$site_gene', '$regulated_gene', 'downregulates', $down_region, 'y', $ish, $parent_ish, $new_stage_down) ";	
													$stmt = pg_query($c,$khoueiry) or die("ERROR!");	
													print "Gene $site_gene directly downregulates $regulated_gene in $down_region: $ish - $parent_ish<br/>";
												}
											}
										}								
								
									}
								}
							
							}					
						}			
					}
				}
			} // END if
						
		}			
		
	}
	
}
	

?>