<?php
ini_set( 'default_charset', 'UTF-8' );
header("Content-Type: text/html;charset=UTF-8");
session_start();

include_once("config.php");

$TRANS_MAP = array();
//$tmap = array();

$xml = new DOMDocument(); 
$xml->load("trans.xml");
$xpathXml = new DOMXpath($xml);
$transTables = $xpathXml->query("/transliterations/transliteration");
if (!is_null($transTables)) {
	foreach ($transTables as $table) {
  		$TRANS_MAP[$table->getAttribute("language")] = array("trans" => array(), "backtrans" => array());  		
  		$entries = $xpathXml->query("char", $table);
  		foreach ($entries as $e) {
  			$TRANS_MAP[$table->getAttribute("language")]["trans"][json_decode('"'. '\\u' . $e->getAttribute("unicode") .'"')] = $e->getAttribute("transliterated");
  			$TRANS_MAP[$table->getAttribute("language")]["backtrans"][$e->getAttribute("transliterated")] = json_decode('"'. '\\u' . $e->getAttribute("unicode") .'"');
  		}
    }
}

function transliterate($str, $lang){
	//echo $str;
	global $TRANS_MAP;
	//print_r($TRANS_MAP);
	$res = "";
	$chrArray = preg_split('//u',$str, -1, PREG_SPLIT_NO_EMPTY);
	//print_r($chrArray);
	for($i=0; $i < count($chrArray); $i++) {
		$val = $TRANS_MAP[$lang]["trans"][$chrArray[$i]];
		if (strlen($val) == 0)
			$res .= $chrArray[$i];
		else
			$res .= $val;
	}
	return json_decode('"'.$res.'"');
}

function backTransliterate($str, $lang){
	//echo $arbStr;
	global $TRANS_MAP;
	$res = "";
	$chrArray = preg_split('//u',$str, -1, PREG_SPLIT_NO_EMPTY);
	//print_r($chrArray);
	for($i=0; $i < count($chrArray); $i++) {
		$val = $TRANS_MAP[$lang]["backtrans"][$chrArray[$i]];
		//echo $val . "<br>";
		if (strlen($val) == 0)
			$res .= $chrArray[$i];
		else
			$res .= $val;
	}
	return $res;
	//return json_decode('"'.$res.'"');
}

?>
