<?php
//Provides a parser so that facts and rules can be entered into the database
//in a humar readable syntax
//syntax is clause(argument1,....,argumentN); for facts or
//fact1 ^ fact2 ^ .. ^ factN => factN+1; for rules
//the function takes a string with newline separated facts and rules and adds them to a knowledgebase
function parse($input, $kb){
	$lines = str_replace(" ", "", $line);
	$lines = str_replace("\n", "", $line);
	$lines = explode(";", $input);
	foreach($lines as $line){
		//determine if the line is a fact or a rule
		if(!preg_match("/=>/", $line) && $line != ""){
			//we have a candidate for a fact
			$fact = parseFact($line);
			$kb->add_fact($fact);
		}
		elseif($line != ""){
		//we have a candidate for a rule
			$parts = preg_split("/=>/", $line);
			$horns = preg_split("/\\^/", $parts[0]);
			for($i = 0; $i < count($horns); $i++){
				//echo($horns[i]);
				//echo("<br>");
				$horns[$i] = parseFact($horns[$i]);	
			}
			$head = parseFact($parts[1]);
			$rule = new rule($head, $horns);
			$kb->add_rule($rule);
		}
	}
	return $kb;
}

function parseFact($line){
			$parts = preg_split("/\\(/", $line);
			$name = preg_replace('/\s+/', '', $parts[0]); 
			$arguments = preg_split("/,\\s*/", $parts[1]);
			$objArgs = array();
			for($i = 0; $i < count($arguments); $i++){
				$arguments[$i] = str_replace(")", "", $arguments[$i]);
				$arguments[$i] = str_replace(" ", "", $arguments[$i]);
				if(contains("*", $arguments[$i])){
					$objArgs[] = new variable($arguments[$i]);
				}
				else{
					$objArgs[] = new atom($arguments[$i]);
				}
			}
			return new fact($name, $objArgs);	
}

?>