<?php
/************************************************
 * wrapper script for mathomatic
 * Copy it , Use it , Change it as you want it.
 *
 * 2009, Steffen Pohle <at> gulpe.de
 */

function input_filter ($m) {
	$i = 0;
	$cl = "";
	$out = "";

	for ($i = 0; $i < strlen ($m); $i++) {
		$c = $m[$i];
		if ((strlen ($cl) != 0 || $c != ' ') && $c != ">") $cl = $cl.$c;
		if ($c == "\n" && strlen ($cl) > 1) {
			if ($cl[0] == "!") $cl = "";
			if (strtolower (substr ($cl, 0, 4)) == "save") $cl ="";
			if (strtolower (substr ($cl, 0, 4)) == "read") $cl ="";
			$out = $out.$cl;
			$cl = "";
		}
	}
	return ($out."\n");
};

if ($_REQUEST['source'] == 1) {
	/*******************************************
	 *  display the math.php source
	 */
	system ('highlight -X math.php', $retval);
}

else {
 	/*******************************************
	 *  web-wrapper
	 */
	$math=$_POST['math'];
	if ($math=="") {
		$math="25a-(12a-(8b-(11a+19b-13c)-5c)+2a)+28b\n";
		$math=$math."simplify\nclear\n; do something new\n";
		$math=$math."0=2x^2-3x-20\nsolve x\ncalculate\n";
	}
	$mathfilter = input_filter ($math);

	?>
	  <html>
	  <head>
	    <title>Mathomatic Webclient</title>
	    <meta http-equiv="content-type" content="text/html; charset=utf8">
	    <meta http-equiv="Content-Style-Type" content="text/css">
	    <link rel="stylesheet" type="text/css" href="homepage.css">
	  </head>
	  <body>
	  <h1>Mathomatic - Web-Client</h1>
	  <a href="http://www.mathomatic.com/math/">Mathomatic</a> - the tool which does all the work.<br>
	  <a href="math.php?source=1">Web-Client</a> - sourcecode (PHP)<br>
          <center><form action="math.php" method="POST">
	   <textarea name="math" rows="25" cols="70"><?=$math?></textarea><br><br>
	   <input type="submit" value="mathomatic">
	  </form></center>
	  <p><hr>
	<?php
	$tmpfname = tempnam("/tmp", "FOO");
	$handle = fopen($tmpfname, "w");
	fwrite($handle, $mathfilter);
	fclose($handle);
	system ('mathomatic -x -q '.$tmpfname, $retval);
	unlink($tmpfname);
	echo "</body>\n</html>\n";
}

?>