<?
	$EnforceSession = false;
	$SiteRoot = "../";
	include $SiteRoot."includes/includes.php";
	include "functions.php";
		
	// Get the name
	$name = request("name");
	$pagetitle = "The Holy Bible - " . $name;

	// Run the header
	include $SiteRoot."includes/header.php";
	
	// Begin Template
	$tp = new PhpTemplate;
	for($tp->StartFromFile("book.template"); $tp->NextAndEchoOutput();)
	{
		if($tp->IsEscape("NAME")) echo $name;
		else if($tp->IsEscape("CHAPTERS")) 
		{
			// Open it
			$dbx = fopen("bible.dbx", "rb");
			
			// Load the index location
			$index_loc = ReadInt($dbx);
			
			// Seek
			fseek($dbx, $index_loc, SEEK_SET);
			
			// Load the number of books
			$book_count = ReadInt($dbx);
			
			// Loop each book
			for($Bi = 0; $Bi < $book_count; $Bi++)
			{
				// Load the name
				$candidate_name = strtolower(trim(fread($dbx, 64)));
				
				// Load the chapter count
				$chapter_count = ReadInt($dbx);
				
				// Seek past
				fseek($dbx, $chapter_count * 4, SEEK_CUR);
				
				// If this is not our book
				if(strtolower($name) != $candidate_name) continue;

				// Loop each chapter
				for($Ci = 1; $Ci <= $chapter_count; $Ci++)
				{	
					// Run the name
					ExChapterTemplate($tp->GetEscapeArgument(), $name, $Ci, $chapter_count);
				}
				
				// Done
				break;
			}
			
			// Close it
			fclose($dbx);
		}
	}

	// Footer
	include $SiteRoot."includes/footer.php";

	function ExChapterTemplate($template, $name, $chapter_number, $chapter_count)
	{
		// Begin Template
		$tp = new PhpTemplate;
		for($tp->Start($template); $tp->NextAndEchoOutput();)
		{
			if($tp->IsEscape("NAME")) echo $name;
			else if($tp->IsEscape("NAME-URI")) echo rawurlencode($name);
			else if($tp->IsEscape("CHAPTER")) echo $chapter_number;
			else if($tp->IsEscape("IF-NOT-LAST") && $chapter_number < $chapter_count) $tp->PushArgumentToStream();
		}
	}
	
?>