<?php

if (empty($argv[1])) {
	die("Usage: make.php SOURCE_MARKDOWN > DESTINATION_HTML\n");
}

$lines = file($argv[1]);
$out = '';
$in_list = $in_section = false;
$section_class = null;

function escape($str) {
	$str = htmlspecialchars($str);
	$str = str_replace('&lt;!--', '<sup>', $str);
	$str = str_replace('--&gt;', '</sup>', $str);

	$str = preg_replace_callback('/`(.*?)`/', function ($match) {
		return '<code>' . $match[1] . '</code>';
	}, $str);

	$str = preg_replace_callback('/\[(.*?)\]\((.*?)\)/', function ($match) {
		return sprintf('<a href="%s">%s</a>', $match[2], $match[1]);
	}, $str);

	return $str;
}

foreach ($lines as $line)
{
	if (preg_match('/^---+(?:\s*=(\w+))?$/', $line, $match)) {
		if ($in_section) {
			if ($in_list) {
				$out .= '    </ul>' . PHP_EOL;
				$in_list = false;
			}

			$out .= '</section>' . PHP_EOL . PHP_EOL;
			$in_section = false;
		}

		$section_class = !empty($match[1]) ? $match[1] : null;

		continue;
	}

	if ('' === trim($line)) {
		continue;
	}

	if (!$in_section) {
		$out .= sprintf('<section class="%s">', $section_class) . PHP_EOL;
		$in_section = true;
	}

	if (preg_match('/^(#+)\s+/', $line, $match)) {
		$size = strlen($match[1]);
		$title = trim(substr($line, strlen($match[0])));
		$out .= sprintf('    <h%d>%s</h%d>', $size, escape($title), $size) . PHP_EOL;
	}
	elseif (preg_match('/^\*\s+/', $line)) {
		if (!$in_list) {
			$out .= '    <ul>' . PHP_EOL;
			$in_list = true;
		}

		$out .= sprintf('        <li>%s</li>', escape(trim(substr($line, 2)))) . PHP_EOL;
	}
	else {
		$out .= '        ' . trim($line) . PHP_EOL;
	}
}

if ($in_section) {
	if ($in_list) {
		$out .= '    </ul>' . PHP_EOL;
		$in_list = false;
	}

	$out .= '</section>' . PHP_EOL . PHP_EOL;
	$in_section = false;
}

?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>Slides</title>
	<link rel="stylesheet" type="text/css" href="style.css" media="screen,presentation" />
	<link rel="stylesheet" type="text/css" href="print.css" media="print" />
	<script type="text/javascript" src="slides.js"></script>
</head>

<body>

<?=$out?>

</body>
</html>