<?php ini_set('max_execution_time', '0'); ?>
<?php /* FUNC: Print an array */ function ea ($the_array) { echo '<pre class="popper">'; print_r ($the_array); echo '</pre><br>'; } ?>
<?php /* Get content from line number of a text file */ function get_line_number($filename, $linenumber) {
		$file = new SplFileObject($filename, "r");
		$file -> seek((int)$linenumber - 1);
		$linedata = $file->current();
		$linedata = str_replace("\r\n", "", $linedata);
		return $linedata;
} ?>
<?php /* FUNC: Directory and File functions: dir_img(), dir_jscss(), dir_fonts(), file_quranpublic(), file_qurandata(), file_translations() */
	function dir_img() { $dir = "/dist/img/"; return $dir; }
	function dir_jscss() { $dir = "/dist/script_css/"; return $dir; }
	function dir_fonts() { $dir = "/dist/fonts/"; return $dir; }
	?>
<?php include "data/al_kitab.io_data.alk"; ?>
<?php function arrow($where, $how=null) { if (!empty($how)) { return '<div class="arrow-holder '.$where.' '.$how.'"><div class="arrow-'.$how.'"></div></div>';} else { return '<div class="arrow-holder '.$where.' down"><div class="arrow-down"></div></div>'; } } ?>
<?php function minmax($direction, $control) { $dir = ($direction == "up") ? "close" : "open"; return "<a class='arr-$direction arrow' href='#' title='Click/Tap to $dir panel' data-controlID='$control'></a>"; } ?>
<?php /* FUNC: Misc Images */ function images($input=null) {
			if ($input == "hidden") {
				$x = '<img title="Al Kitab" alt="Al Kitab" class="bismillah hide" width="1200" height="630" src = "/dist/img/bismillah-wide.png"/><br><img title="Al Kitab" alt="Al Kitab" class="bismillah hide" width="630" height="630" src = "/dist/img/bismillah-sq.png"/><br>'; return $x; 
			}
			if ($input == "surahend") { $x = "<img alt='surah end symbol' title='surah end symbol' class='surahendsymbol' src='".dir_img()."surahendsymbol.png' />"; }
			return $x;
	} ?>
<?php /* Check if cookie is set for Translation and Other options checkboxes */ function isOptionSelected($option) {
    if (isset($_COOKIE[$option]) && $_COOKIE[$option] == 'checked') { return true; }
    return false;
} ?>
<?php /* FUNC: Get server name */ function server() { return $_SERVER["HTTP_HOST"]; } ?>
<?php /* FUNC: Sanitize the initial input or location to remove trailing characters */ function sanitizeURI($input = null) {
	if ($input == null && !empty($_GET["s"])) { $input = urldecode($_GET["s"]); }
	elseif ( $input == null && empty($_GET["s"]) ) {
		$input = urldecode($_SERVER["REQUEST_URI"]); 
		if (stripos($input, "?q=fullsurah")) { $GLOBALS["fullsurah"] = "true"; $input = str_replace("?q=fullsurah", "",$input);}
		$input = substr($input,1); 
	}
	$input = rtrim($input, "/"); $input = rtrim($input, "-"); $input = rtrim($input, "."); $input = rtrim($input, " ");
	//ea ($input); die;
	return $input;
} ?>
<?php /* FUNC: Make array pattern for s:v pattern */ function properpatternify($input = null) {
		$chars = array(":","-","—","~", " "); 
		$replc = array("/","/","/","/", "");
		$input = str_replace($chars, $replc, $input);
		$x = explode ("/", $input);
		return $x;
	} ?>
<?php /* FUNC: Get Quran Data as Full Array or Targeted InfoString */ function quran_data($surahnumber, $targetedinfo=null) {
		global $quran_data;
		if ($targetedinfo == null) $data = $quran_data[$surahnumber];
		else $data = $quran_data[$surahnumber][$targetedinfo];
		return $data;
	} ?>
<?php /* FUNC: VAR: Messages: Error, Loading, Info4Ajax, Hints */
	
	function error($x = null) {
		if ($x == 1) { return "<div class='displayerror'><strong>Error:</strong> Unknown format or range.<br>Kindly use at least three characters of either<br>English, or Arabic, or Numeric values like:<br><div class='highlight'>1/3</div>, or <div class='highlight'>22-10</div><br>format for Surah and Verse, and<br>use range search like:<br><div class='highlight'>1/3/5/4</div>, or <div class='highlight'>22/10-23/3</div>.<br>Also note: The Book has total 114 chapters.</div><!-- .displayerror -->"; }
		elseif ($x == 2) { return "<div class='displayerror'><strong>Search failed:</strong> The word(s) you are looking for cannot be found in our database.</div><!-- .displayerror -->"; }
		else { return "Error"; }
	}
	function info4ajax ($location, $totalverses, $lastdisplayed = null) {
		echo '<input type="hidden" name="surahnumber" id="surahnumber" value="'.$location.'">';
		if ($lastdisplayed !== null) { echo '<input type="hidden" name="lastdisplayedverse" id="lastdisplayedverse" value="'.$lastdisplayed.'">'; }
		else { echo '<input type="hidden" name="lastdisplayedverse" id="lastdisplayedverse" value="10">'; }
		echo '<input type="hidden" name="remainingverses" id="remainingverses" value="'.($totalverses - 10) .'">';
		echo '<input type="hidden" name="totalverses" id="totalverses" value="'.$totalverses.'">';
	}	
	function loadmore_btn_inpt ($mode) {
		$x = '<div id="loaderanim" class="hide"><span class="loaderanim_bar" style="--delay: 0.0s">°</span><span class="loaderanim_bar" style="--delay: 0.1s">°</span><span class="loaderanim_bar" style="--delay: 0.2s">°</span><span class="loaderanim_bar" style="--delay: 0.3s">°</span><span class="loaderanim_bar" style="--delay: 0.4s">°</span><span class="loaderanim_bar" style="--delay: 0.5s">°</span><span class="loaderanim_bar" style="--delay: 0.6s">°</span><span class="loaderanim_bar" style="--delay: 0.7s">°</span><span class="loaderanim_bar" style="--delay: 0.8s">°</span><span class="loaderanim_bar" style="--delay: 0.9s">°</span></div>';
		if ($mode == "search") { $x = $x.'<br><input id="loadmoresearch" type="button" class="btn-loadmore" value="Get more results" />'; }
		if ($mode == "chapter") { $x = $x.'<br><input id="loadmore" type="button" class="btn-loadmore" value="Get next verses" />'; }
		if ($mode == "range") { $x = $x.'<br><input id="loadmore" type="button" class="btn-loadmore" value="Continue reading the Surah" />'; }
		return $x;
	}
	function genhints() { return "<small class='hint'>Hint: 'Tap' or 'Click' on an Arabic word in verses for additional meanings.<br><br>Hint: 'Tap' or 'Click' on ◉ to save as image to clipboard.</small>"; }
?>
<?php /* FUNC: Format the Masthead and Searchbar */ function the_masthead($andmenu=null) {
		include "dist/img/bismillah.svg.php";
		$x = "";
		if (!empty($_GET['s'])) { $x = $_GET['s']; }
		$the_masthead = '
		<table id="masthead" class="scrollshowhide" cellspacing="0" cellpadding="0">
		<tr>
			<td class="gohome"><a class="gohome homesvg" href="/" title="Home Page"></a></td>
			<td class="search" colspan="4"><form class="search" action="/" name="q" accept-charset="utf-8"><input id="keyboardInputInitiator0" class="search keyboardInput" type="search" name="s" placeholder="Search" value="'.$x.'"></form></td>
		</tr>
		</table>
		<div id="ajax_search" class="ajax_search"></div>
		';
		if ($andmenu === "menu") { $the_masthead = $the_masthead.'<div id="mnbtnhldr"><div><label id="readericon" for="readermode">Ξ</label></div><div id="menu">֍</div></div>'; }
		return $the_masthead;
	} ?>
<?php /* FUNC: Build Surah Name buttons */ function surah_names() { 
		$xm = "1";
		$surahnamebuttons = "";
		while ($xm < "115") {
			$surahnamebuttons = $surahnamebuttons."
				<a class='surahname' name='surah' href='/".$xm."'><span class='digit'>".$xm."</span><br>
					<span class='englishfont'>".quran_data($xm, "name_eng")."</span><br><span class='arabicfont'>".quran_data($xm, "name_arb")."</span><br><span class='englishfont translitname'>".quran_data($xm, "translit_name")."</span>
				</a>"; 
			$xm++; 
		} 
		return $surahnamebuttons;
	} ?>
<?php /* FUNC: Language checking functions: is_home(), is_arabic(), is_arabic(), is_english(), is_chapter(), is_svpttrn(), is_rngpttrn(), */
	function is_home() { if (sanitizeURI() == null) return TRUE; else return FALSE; }
	function is_arabic($input=null) { if ($input == null) { $input = sanitizeURI(); }
		preg_match_all ('/[ٱء-ي⇐ ]/iu', $input, $m); preg_match_all ('/[\[A-Z\]]/iu', $input, $m2); preg_match_all ('/\d/', $input, $m3);
		if ( count ($m[0]) > 1 && empty($m2[0][0]) && empty($m3[0]) ) { return true; } else { return false; }
	}
	function is_english($input=null) { if ($input == null) { $input = sanitizeURI(); }
		preg_match_all ('/[\[A-Z \]]/iu', $input, $m); preg_match_all ('/\d/', $input, $m2); preg_match_all ('/[ٱء-ي]/iu', $input, $m3); 
		if ( count ($m[0]) > 1 && empty($m2[0][0]) && empty($m3[0]) ) { return true; } else { return false; }
	}
	function is_chapter($input=null) { if ($input == null) { $input = sanitizeURI(); }
		preg_match_all ('/^\d{1,3}$/', $input, $m1);
		if (!empty($m1[0][0])) { if ($m1[0][0] < "115") { if ( $m1[0][0] > "0") { return true; } else { return false; } } else { return false; } } else { return false; }
	}
	function is_svpttrn($input=null) { if ($input == null) { $input = sanitizeURI(); }
		preg_match ('/^(\d{1,3}[\:\-\/]\d{1,3})$/', $input, $m);
		if (!empty($m[0])) { $x = properpatternify($input); if ( ($x[0] < "115" && $x[0] > "0") && ($x[1] <= quran_data($x[0], "verses")) ) { return true; } else return false; } 
		else { return false; }
	}
	function is_rngpttrn($input=null) { if ($input == null) { $input = sanitizeURI(); }
		preg_match ('/^(\d{1,3}[\:\-\/]\d{1,3}((\ [\-\?\:\—\/]\ )|(to|[\-\?\:\—\/]))\d{1,3}[\:\-\/]\d{1,3})$/', $input, $m);
		if ( !empty($m) ) { 
		 $x = properpatternify($input);
		 if (
			($x[0] < "115" && $x[0] > "0") && ($x[1] <= quran_data($x[0], "verses")) &&
			($x[2] < "115" && $x[2] > "0") && ($x[3] <= quran_data($x[2], "verses")) &&
			($x[0] <= $x[2])
		 ) { return true; }
		 else { return false; }
		}
	}
	function is_search($input=null) { if (is_english() || is_arabic()) return TRUE; }
	//function is_error() { /* Function defined in header.php */ }
?>
<?php /* FOLLOWING FUNCTIONS LOAD WHEN NO ERROR */ ?>
<?php /* FUNC: Properly print Search term or Verse number */ function printsearchterm($mode, $input, $numbers) { 
		if ($mode == "search") { echo '<div id="searchtermcontainer"><div class="searchtitle">Searching:</div><div class="searchterm">'.$input.'</div><div class="totalresults"><strong>'.$numbers.'</strong> results</div></div>'; } 
		if ($mode == "range") { echo '<div id="searchtermcontainer" class="inrange"><div class="searchtitle">Range:</div><div class="rangeterm">'.$numbers[0].':'.$numbers[1].' — '.$numbers[2].':'.$numbers[3].'</div></div>'; }
		echo genhints();
	} ?>
<?php /* FUNC: Properly print Surah name in Arabic and English */ function printsurahnames($surahnumber) { 
		$x1 = quran_data($surahnumber, "name_arb");
		$x2 = quran_data($surahnumber, "name_eng");
		$x3 = '<div class="surahtitle"><div class="arabictitlesurah">'.$x1.'</div><div class="englishtitlesurah">'.$x2.'</div>'.genhints().'</div>';
		echo $x3;
	} ?>
<?php /* FUNC: English to Arabic numerals */  function arabicnumber ($number) {
		$arabicno =  str_replace( array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"), array("١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩", "٠"), $number); return $arabicno; 
	} ?>
<?php /* FUNC: Format Verse Translations ONLY */ function translationsformatednonecho($translations) {
	global $translations_data;
	$x = 2; $full = "";
	while ($x < count($translations)) {
		$lang = $translations_data[$x]["language"];
		$full = $full.'
			<div class="translationtext trans_'.$translations_data[$x]["sname"].'" lang="'.$lang.'"><div class="bullet">⦿</div>'.$translations[$x].'<div class="translationname"> - '.$translations_data[$x]["fname"].'</div></div>';
		$x++;
	}
	preg_match_all ('/\(([^)]+)\)/iu', $full, $m);
	if (!empty($m[0])) { $m = $m[0][0];
		$b = "<span class='regularbraces'>$m</span>";
		$full = str_replace($m, $b, $full);
	}	
	$fulls = '<div class="translations"><hr size="1" color="#343434">'.$full.'</div>';
	return $fulls;
}	?>
<?php /* FUNC: Properly print Single English/Arabic word fullinfo Div/Span */ function singlewordmarkup ($entry, $lang, $spandiv, $searchitem=null) {	
		if ($searchitem == null) { $searchitem = "some_words_nowhere_in_entire_databse"; }
		$ar_word = $entry[3];
		$en_word = $entry[4];
		$othrmng = $entry[5];
		$root = $entry[6];
		$translit = $entry[7];
		$diatless = $entry[8];
		$topic = $entry[9];
		$isinquote = $entry[10];
		//var_dump($root);
		if (preg_match('/ ⇐ /', $root)) { $roothtml = preg_replace('/ ⇐ /', '__', $root);}
		else { $roothtml = $root; }
		if (
			stripos($ar_word, preg_quote($searchitem, '/')) !== false ||
			stripos($en_word, preg_quote($searchitem, '/')) !== false ||
			stripos($othrmng, preg_quote($searchitem, '/')) !== false ||
			stripos($othrmng, $searchitem) !== false ||
			stripos($root, preg_quote($searchitem, '/')) !== false ||
			stripos($translit, $searchitem) !== false ||
			//stripos($topic, $searchitem) !== false ||
			stripos($translit, preg_quote($searchitem, '/')) !== false ) { $highlight = "highlight "; }
		elseif (stripos($topic, $searchitem) !== false) { $highlight = "topicsearch "; }
		else { $highlight = ""; }
		if (!empty($othrmng)) { 
			$sep = "<strong class='crimsonf'> | </strong>";
			$pattern = '/,(?![^\[\]()]*(\)|\]))/';
			$othrmng2 = preg_replace($pattern, $sep, $othrmng);
			preg_match_all ('/\(([^)]+)\)/iu', $othrmng2, $m);
			if (!empty($m[0])) { $m = $m[0][0];
				$b = "<span class='regularbraces'>$m</span>";
				$othrmng2 = str_replace($m, $b, $othrmng2);
			}
		}
		//if ($lang == "English") { if ($isinquote === "@") { $isinquote = "quote "; } $class = "englishfont $highlight $isinquote"; 
		if ($lang == "English") { 
			if (strpos($isinquote, "@") !== false) { $isinquote = "quote ";  }
			$class = "englishfont $highlight $isinquote"; 
			if ($en_word !== "°") { $word = $en_word; }
			else { $word = ""; }
			preg_match_all ('/\(([^)]+)\)/iu', $word, $m);
			if (!empty($m[0])) { $m = $m[0][0];
				$b = "<span class='regularbraces'>$m</span>";
				$word = str_replace($m, $b, $word);
			}
			if ($en_word == "") { $word = "{eng}"; }
			if ($en_word == "") { $class = $class. " inceng"; }
			$lang = "English";
		}
		elseif ($lang == "Arabic") {
			if (
				$ar_word === "ۖ" || // ssalay - [mark - continuing is preferred]
				$ar_word === "ۗ" || // qalay - [mark - pausing is preferred]
				$ar_word === "ۘ" || // meme - [mark - necessary pause]
				$ar_word === "ۙ" || // laa - [mark - do not pause]
				$ar_word === "ۚ" || // jeme - [mark - can pause]
				$ar_word === "ۛ" || // 3dots - [mark - interchangeable]
				$ar_word === "ۜ" || // sene - [mark]
				$ar_word === "۩" || // sajda - [mark]
				$ar_word === "⌂" // [mark]
			) 
			{ $class = "arabicfont $highlight diatric "; }
			else { $class = "arabicfont $highlight"; }
			 if (strpos($isinquote, "@") !== false) { $isinquote = "quote"; $class = $class. $isinquote; }
			if ( $ar_word === "ۜ" ) { $class = $class." dia_exp1"; } // The mark "sene" is singled out here because in Arabic font, sene has uneven margins on left and right. So additional padding is provided by adding a class for l/r margins only.
			if ( $ar_word === "ۖ" ) { $class = $class." dia_exp2"; } // The mark "salay" is singled out here because in Arabic font, salay has uneven margins on left and right. So additional padding is provided by adding a class for l/r margins only.
			
			$word = $ar_word; 
			$lang = "Arabic";
		}
		//$title = $root.' | '.$othrmng.' | '.$translit. ' | '. $diatless;
		$title = "";
		//$markup = '<'.$spandiv.' datacls="" class="'.$class.'" title="'.$title.'" dataroot="'.$root.'" dataarbic="'.$ar_word.'" dataom="'.$othrmng2.'" lang="'. $lang.'">'.$word.'</'.$spandiv.'> ';
		$markup = '<'.$spandiv.' data-cls="" class="'.$class.'" data-root="'.$roothtml.'" data-arabic="'.$ar_word.'" lang="'. $lang.'">'.$word.'</'.$spandiv.'> ';
		
		return $markup;
	} ?>
<?php /* FUNC: Build Single_Verse array */ function getoneayatarray($surah, $verse) {
		global $file;
		$now = $start = quran_data($surah, "first_word"); $start = $start - 1;
		$end = quran_data($surah, "last_word"); $end = $end - 1;
		$handle = fopen($file["alkitab_full"], "r") or die("Couldn't get handle");
		if ($handle) { $x = 0; $z = 0; $versearray = array(); 
			while (!feof($handle)) {
				$buffer = fgets($handle, 4096);
				if ($x < $start) { }
				elseif ($x >= $start && $x <= $end) {
					if (preg_match('/\t{3}/', $buffer)) { $buffer = preg_replace('/\t{2}/', '	[untranslated]	[untranslated]	', $buffer); }
					elseif (preg_match('/\t{2}/', $buffer)) { $buffer = preg_replace('/\t{2}/', '	[untranslated]	', $buffer); }
					$rowarray = preg_split("/\t+/", $buffer);
					if ($rowarray[0] == ($surah.":".$verse)) { $versearray[$z] = $rowarray; $z++; }
				}
				elseif ($x > $end) { goto endloop; }
				$x++;
			}
			endloop:
			fclose($handle);
			return $versearray; 
		}
	} ?>
<?php /* FUNC: Get Single Verse Translations */ function versetransarray ($chapter, $verse) {
		global $file;
		$surah_first_line = (int) quran_data($chapter, "first_line");
		$verseno = $surah_first_line + (int) $verse - 1;
		$linedata = get_line_number($file["translations"], $verseno);
		$linedata = explode("|", $linedata); 
		return $linedata; 
	} ?>
<?php /* FUNC: Format ranges for Link on Verse Title ONLY  */ function setLINKrange ($verse, $maxverses) {
		if ($verse - 5 >= 1) { $range["from"] = $verse - 5;} else { $range["from"] = 1;}
		if ($range["from"] == 1 && $range["from"] +9 <= $maxverses) { $range["till"] = $verse + 9; }
		elseif ($verse + 5 <= $maxverses) { $range["till"] = $verse + 5; }
		else { $range["till"] = $maxverses; }
		return $range;
	} ?>
<?php /* FUNC: Properly print Single_Verse */ function printoneayat($surah, $verse, $searchhighlight=null) {
		$surahinfo = quran_data($surah);
		if ($searchhighlight == null) { $searchhighlight = ""; }
		$translations = versetransarray ($surah, $verse);
		$arabicnumber = "<a class='surahvrsno' href='/$surah/$verse'><div class='srhno'>".arabicnumber ($surah)."</div><div class='vrsno'>".arabicnumber ($verse)."</div></a>";
		$verseinfo = $surahinfo["name_eng"].'<strong> [ '.$surah.':'.$verse.' ] </strong><span class="arabic">'.$surahinfo["name_arb"]."</span>";
		$versearray = array();
		$versearray = getoneayatarray($surah, $verse);
		$maxverses = $surahinfo["verses"];
		$range = setLINKrange ($verse, $maxverses);
		$versedivID = $surahinfo["sht_name"].'-'.$surah.'-'.$verse;
		$f_1 = $f_2 = $f_3 = $f_4 = $f_5 = $f_6 = $engtmp = $engread = $startQuote = $collection = $shownroots = "";
		$verseslink = '/' . $surah .'/'. $range["from"] . '/' . $surah . '/' . $range["till"] . '#'. $versedivID;

		$f_1 = '<div id="'.$versedivID.'" class="vrscntnr"><div class="vrshdr"><div class="capture" title="Click to save verse as image in clipboard">◉</div><a class="vrsnmbar" href='.$verseslink.' title="Click to go to ayats">'.$verseinfo.'</a></div><div class="wrdcntnr">';
		
		foreach ($versearray as $entry) { 
			$f_tmp = $f_2.'<div class="wrds">';
			$f_tmp = $f_tmp."".singlewordmarkup($entry, "Arabic", "div", $searchhighlight)."".singlewordmarkup($entry, "English", "div", $searchhighlight);
			$f_tmp = $f_tmp."</div><!-- .wrds -->";
			$f_2 = $f_tmp;
		}
		$f_2 = $f_2.'</div><!-- .wrdcntnr --><div class="arbline">'.$arabicnumber;
		
		foreach ($versearray as $entry) { 
			$f_tmp = $f_3."".singlewordmarkup($entry, "Arabic", "span", $searchhighlight); 
			$f_3 = $f_tmp; 
		}
		$f_3 = $f_3.'</div><div class="engline sp_'.$versedivID.'"><button data-target="sp_'.$versedivID.'" class="playthis" id="play_'.$versedivID.'"></button>';
		
		foreach ($versearray as $entry) { 
			$f_tmp = $f_4."".singlewordmarkup($entry, "English", "span", $searchhighlight);
			$f_4 = $f_tmp; 
		}
		
		foreach ($versearray as $entry) {
			if ($entry[4] !== "°" && $entry[4] !== null && $entry[4] !== "") {
				if (strpos($entry[10], "@") !== false) { 
					if ($startQuote == "1") {  }
					else { $entry[4] = "<span class='quote'>$entry[4]"; $startQuote = "1"; }
				}
				if (strpos($entry[10], "__") !==false && $startQuote == "1") { $entry[4] = "</span>" . $entry[4]; $startQuote = "end"; }
				$engtmp = $engread .' '. $entry[4];
				$engread = $engtmp;
			}
		}
		$engread = $engread . " <span class='rmsrhvrno'>[ $surah : $verse ] </span>";

		foreach ($versearray as $entry) {
			if (!empty($entry[5]) && !empty($entry[6]) && (strpos($entry[6], "—") !== 1 ) ) {
				if (strpos($shownroots, "'".$entry[6]."'") < 1) {
					$sep = "<i class='sptr'> | </i>";
					$pattern = '/,(?![^\[\]()]*(\)|\]))/';
					$othrmng2 = preg_replace($pattern, $sep, $entry[5]);
					preg_match_all ('/\(([^)]+)\)/iu', $othrmng2, $m);
					if (!empty($m[0])) { $m = $m[0][0];
						$b = "<span class='regularbraces'>$m</span>";
						$othrmng2 = str_replace($m, $b, $othrmng2);
					}
					if (preg_match('/ ⇐ /', $entry[6])) { $roothtml = preg_replace('/ ⇐ /', '__', $entry[6]);}
					else { $roothtml = $entry[6]; }
					$shownroots = "<div id='root_$roothtml' class='rootmeaning' data-root='$roothtml' style='display: '><strong>$entry[6]</strong> $sep $othrmng2</div>".$shownroots; 
				}
			}
		}
		$collection = "<div class='all_roots'>$shownroots</div>";

		$f_4 = $f_4.'</div><div class="qurancomlink"><span>🔗</span><a href="https://quran.com/'.$surah.'/?startingVerse='.$verse.'" target="_quran.com">Read verse on Quran.com</a><strong>⤻</strong></div>';
		$f_5 = translationsformatednonecho($translations);
		$f_6 = '</div><!-- .vrscntnr --><article data-index="'.$surah . $verse.'" class="reader" style="display:none">'.$engread.'</article>'.$collection;
		$final = $f_1."".$f_2."".$f_3."".$f_4."".$f_5."".$f_6;
		echo $final;
	} ?>
<?php /* FUNC: Properly print Single_Surah */ function printfullsurah($surah) {
		$surahinfo = quran_data($surah);
		$maxverses = $surahinfo["verses"];
		$x = 1;
		while ($x < ($maxverses + 1)) { printoneayat($surah, $x); $x++; }
	} ?>
<?php /* FUNC: Build Search array. Result: array[x]["surah"], array[x]["verse"]*/ function buildsearcharray($searchitem) {
		if (!empty($searchitem)) {
			if ($searchitem == "_translated" || $searchitem == "_topics") { return false; }
			global $file;
			$filecontents = file_get_contents($file["alkitab_full"]);
			$pattern = "/.*(".preg_quote($searchitem, '/').").*\$/mi"; // finalise the regular expression, matching the whole line
			if (preg_match_all($pattern, $filecontents, $matches)) { $resultsraw1 = $matches[0];$matches = ""; } // search, and store all matching occurrences in $matches
			$x = 0;
			if (empty($resultsraw1)) { $finalresult = "empty"; goto finalresult; }
			else {
				//foreach ($resultsraw1 as $aresult1) { $resultsfine1[$x] = substr( $aresult1, strrpos($aresult1, ',') + 1 ); $x++; }
				foreach ($resultsraw1 as $aresult1) { $resultsfine1[$x] = explode ("\t", $aresult1); $resultsfine1[$x] = $resultsfine1[$x][0]; $x++; }
				$f = $resultsfine1 = array_values(array_unique($resultsfine1));
				$x = 0;
				foreach ($resultsfine1 as $aresult) {
					$res = explode (":", $aresult);
					if (stripos($res[1], "\r")) { $res[1] = str_replace("\r", "", $res[1]); }
					$finalresult[$x]["surah"] = $res[0];
					$finalresult[$x]["verse"] = $res[1];
					$x++; 
				}
			}
			finalresult: $filecontents = "";
			return $finalresult;
		}
	} ?>
<?php /* FUNC: Print Search results */ function printsearchresult($searcharray, $searchitem) {
		$x = 0;
		foreach ($searcharray as $key) {
			if ($key !== $searchitem) {
				echo '<div class="resultnumber">'.($x + 1).'</div>'; printoneayat($key["surah"], $key["verse"], $searchitem);
				$x++;
			}
		}
	} ?>
<?php /* FUNC: to check if a substring is part of a string inside brackets */  function isInsideBrackets($string, $substring) {
		$pattern = "/\[(.*?)\]/"; // Regular expression pattern to match the substring inside brackets
		if (preg_match_all($pattern, $string, $matches)) { // Use preg_match_all to find all substrings inside brackets in the input string
				foreach ($matches[1] as $match) { // Loop through the matches and check if the substring is found in any of them
					if (strpos($match, $substring) !== false) { return true; } // Substring found inside brackets
				}
		}
		return false; // Substring not found inside brackets
	}
	/* EXECUTE SPECIAL FOR MY SENTENCES FILE 
	if (isInsideBrackets($inputString, $substringToCheck)) { echo "The substring '$substringToCheck' is part of a string inside brackets.\n"; } 
	else { echo "The substring '$substringToCheck' is not found inside brackets.\n"; }
	/* */
?>
<?php /* Create Map of Translated Verses */ function mapverses() {
		global $file;
		$searchitem = "	";
		$filecontents = file_get_contents($file["alkitab_full"]);
		$pattern = "/.*(".preg_quote($searchitem, '/').").*\$/mi"; // finalise the regular expression, matching the whole line
		if (!preg_match_all($pattern, $filecontents, $matches)) { $x1 = $matches[0]; } // search, and store all matching occurrences in $matches
		$x = count($matches[0]); $y = 0;
		while ($y < $x) { 
			$x1 = explode("	",$matches[0][$y]);
			if ($x1[4] !== "") { $v[$y] = $x1[0]; }
			$y++; 
		}
		$v = array_unique($v); $v = array_values($v);
		$howmanytranslated = count($v);
		$fr = formatRanges($v);
		$x = count($fr); $y = 0;
		$html = $shtml = $vrs = $vrstmp = "";
		while ($y < $x) {
			//$t = explode(":",$v[$y]);
			//$html = "<a class='vrsmp' href='/".$t[0]."/".$t[1]."'>[ ".$t[0]." / ".$t[1]." ]</a> ";
			$a = explode(":",$fr[$y]);
			$vrs = $a[0];
			$t = str_replace(':', '/', $fr[$y]);
			if (stripos($fr[$y], "-")) { $i = str_replace('-', ' — ', $fr[$y]); } 
			else { $i = $fr[$y]; }
			if ($vrs == $vrstmp) { $html = "<a class='vrsmp' href='/".$t."'>".$i."</a> ";}
			else { $html = "<div class='mappedheadvrs'>$vrs</div><a class='vrsmp' href='/".$t."'>".$i."</a> "; $vrstmp = $vrs;  }
			$shtml = $shtml . $html;
			$y++;
		}
		$completemap = "<div class='howmany' style='font-family: Arial;color:white'>Translated: $howmanytranslated / 6235</div><br>" . $shtml;
		return $completemap;
	} 
	/* Format Translated Verses Ranges for mapverses() */ function formatRanges($inputArray) {
		$outputArray = [];
		$currentRange = null;

		foreach ($inputArray as $value) {
			list($group, $number) = explode(':', $value);

			if ($currentRange === null) { $currentRange = [$group, $number, $number]; } // Start a new range
			else { // Check if the current number is consecutive to the previous one
				if ($group == $currentRange[0] && $number == $currentRange[2] + 1) { $currentRange[2] = $number; } // Extend the current range
				else { $outputArray[] = formatRange($currentRange); $currentRange = [$group, $number, $number]; } // Add the current range to the output and start a new one
			}
		}
		if ($currentRange !== null) { $outputArray[] = formatRange($currentRange); } // Add the last range to the output
		return $outputArray;
	}
	/* Format Translated Verses Ranges for mapverses() */ function formatRange($range) {
		if ($range[1] == $range[2]) { return "{$range[0]}:{$range[1]}"; }
		else { return "{$range[0]}:{$range[1]}-{$range[0]}:{$range[2]}"; }
	} ?>
<?php /* Create Map of Topics and Display */ function topics() { echo "Working on it.";
/*		global $file;
		$filecontents = file_get_contents($file["topics"]);
		$lines = explode("\n", $filecontents); // Split file contents into lines
		$data = []; // Initialize empty array to store the data
		foreach ($lines as $line) {
			$columns = explode("\t", $line); // Split line into columns by tab delimiter
			$key = array_shift($columns); // Extract the first column as key
			if (!empty($columns)) { $data[$key] = $columns; }// Store rest of the columns as values for the key
			else { unset($data[$key]); }
		}
		ea ($data);
	*/ } ?>
<?php /* ========================= DISABLED — FOR SPECIAL USAGE ONLY ========================================== */ ?>
<?php /* THE FOLLOWING PROGRAM PARSES MY TRANSLATION FILE FROM EXCEL CVS FORMAT TO SENTENCE FORMAT. COPY AND PASTE THE RESULT BACK IN FILE.?>
 function formatData($filename) { // Function to organize data by numbers and format it as requested 
    $groupedData = []; // Initialize an empty array to store grouped data
    $file = fopen($filename, 'r');
		if ($file) {
			while (($line = fgets($file)) !== false) {
				$parts = explode("\t", $line); // Split the line into parts using tabs as the delimiter
				
				if (count($parts) === 3 || count($parts) === 2) {  // Extract the number, text, and phrase within brackets
					$number = trim($parts[0]);
					$text = trim($parts[1]);
					if (!empty($parts[2])) { $phrase = trim($parts[2]); }
					if (!isset($groupedData[$number])) { // Append the data to the corresponding group 
						if (!empty($parts[2])) { $groupedData[$number] = ['text' => [], 'phrases' => []]; }
						else { $groupedData[$number] = ['text'];  }
					}
					$groupedData[$number]['text'][] = $text;
					if (!empty($parts[2])) { $groupedData[$number]['phrases'][] = $phrase; }
				}
			}
			
			fclose($file); // Close the file
			
			foreach ($groupedData as $number => $data) {  // Output the formatted data
				$combinedText = implode(' ', $data['text']); // Combine text without removing duplicates
				//var_dump($combinedText);
				if (!empty($data['phrases'])) { $combinedPhrases = implode('	', array_unique($data['phrases'])); } // Combine phrases within brackets and move to the end 
				if (!empty(($data['phrases']))) { echo "<pre>$number	$combinedText	$combinedPhrases</pre>"; }
				else {
					if (preg_match('/	 /', $number.'	'.$combinedText) || preg_match('/	$/', $number.'	'.$combinedText)) {  }
					else { echo "<pre>$number	$combinedText</pre>"; }
				}
			}
    } else { echo "Failed to open the file."; }
}
$filename =$file["my_sentences"]; // Specify the file name
formatData($filename); die; // Call the function to format and organize data
/* */
?>
<?php /* FUNC: Strip Diatrics from Arabic Quran words. Turned off. Used only when in need. /* 
	$x = 0;
	$e = 81805;
	$file = new SplFileObject($file["unique_entries"], "r");
	$diatrics = [
							"~[\x{0600}-\x{0620}]~u",
							"~[\x{063B}-\x{0640}]~u",
							"~[\x{064B}-\x{0660}]~u",
							"~[\x{066A}-\x{06FF}]~u",
					];
	while ($x < $e) {
		$file -> seek($x);
		$linedata = $file->current();
		$linedata = preg_replace("/ٱ|آ|أ|إ/i", "ا", $linedata);
		$linedata = preg_replace("/ؤ/i", "و", $linedata);
		$string = preg_replace($diatrics, "", $linedata);
		ea ($string);
		$x++;
	} */ ?>
<?php /* FUNC: Unicode String Reverse *—/— function utf8_strrev($str) { preg_match_all('/./us', $str, $ar); return join('', array_reverse($ar[0])); } */ ?>