<?php

define('SDK_ROOT', dirname(dirname(__FILE__)));
function findExamples()
{
    return glob(SDK_ROOT . '/example/*.php');
}
function parseExample($file)
{
    $php = file_get_contents($file);
    preg_match('/\\/\\*(.+?)\\*\\/\\n(.+)/s', $php, $match);
    list(, $markdown, $code) = $match;
    return join("\n", array($markdown, '```php', '<?php', $code, '```'));
}
$examples = array();
$files = findExamples();
foreach ($files as $file) {
    $example = parseExample($file);
    $examples[] = $example;
}
$readmePath = SDK_ROOT . '/README.md';
$readme = file_get_contents($readmePath);
$exampleDocs = join("\n", $examples);
$readme = preg_replace('/(generated by: make docs[^\\n]+\\n).+(\\n<!--)/is', '$1' . $exampleDocs . '$2', $readme);
file_put_contents($readmePath, $readme);
/**
 * Here we need to know if we are running from command line or from web
 * That runs anyway: if (isset($_SERVER['SERVER_NAME'])) {
 * but have some o(l|d)d compatibility problem ...
 */
if (in_array(php_sapi_name(), array('cli', 'cgi'))) {
    $html = false;
    $parser = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : 'BBCode';
    $render = isset($_SERVER['argv'][2]) ? $_SERVER['argv'][2] : 'Xhtml';
    if (!isset($_SERVER['argv'][3]) or !is_readable($sou = $_SERVER['argv'][3])) {
        die("Enter a text file to be processed as 3d argument\n First and second are parser and renderer\n");
    }
    $source = file_get_contents($sou);
} else {
    $html = true;
    $elist = findExamples(dirname(__FILE__));
    if (isset($_REQUEST['example']) && in_array($_REQUEST['exchoice'], $elist)) {
        $_REQUEST['source'] = file_get_contents($_REQUEST['exchoice']);
        if (preg_match('#(\\b' . implode('\\b|\\b', $plist) . '\\b)#', $_REQUEST['source'], $match)) {
            $_REQUEST['parser'] = $match[1];
        }
        $_REQUEST['translate'] = true;
    }
    foreach (array('parser' => $plist[0], 'render' => $rlist[0], 'exchoice' => $elist ? $elist[0] : '', 'source' => '') as $fld => $def) {
        if (!isset($_REQUEST[$fld])) {
            $_REQUEST[$fld] = $def;
        }
        ${$fld} = $_REQUEST[$fld];
    }
    if (!isset($_REQUEST['translate'])) {
        echo bldHtml('', $plist, $rlist, $elist);