foreach ($found as $value) {
    if (preg_match("#</?[a-z]+>#im", $value)) {
        throw new Exception("i18n key '" . $value . "' uses HTML, which is not allowed");
    }
}
// find all PHP files that could be included
echo "Found " . count($found) . " potential translation keys\n";
// sort
ksort($found);
// print out to a JSON file
$fp = fopen($root . "/" . $json['template'], "w");
if (!$fp) {
    throw new Exception("Could not open destination file '" . $json['template'] . "' for writing");
}
// we write this out manually so we can format it
write_out_formatted_json($fp, $found);
fclose($fp);
echo "Wrote template file '" . $json['template'] . "'\n";
// print out to a text file, optionally
if ($json['template_text']) {
    $fp = fopen($root . "/" . $json['template_text'], "w");
    if (!$fp) {
        throw new Exception("Could not open destination file '" . $json['template_text'] . "' for writing");
    }
    foreach ($found as $key) {
        // we need to replace :placeholder with <placeholder>
        $key = preg_replace("/:([a-z0-9_]+)/i", "<\\1>", $key);
        fwrite($fp, $key . "\n");
    }
    fclose($fp);
    echo "Wrote template file '" . $json['template_text'] . "'\n";
foreach ($translations as $code => $includes) {
    echo "Processing " . count($includes) . " '{$code}' includes...\n";
    $result = array();
    foreach ($includes as $include) {
        $result = array_merge($result, json_decode(file_get_contents($include), true));
    }
    // sort it
    ksort($result);
    // write it out
    $out = $json['translations'][$code];
    $fp = fopen($out, "w");
    if (!$fp) {
        throw new Exception("Could not open destination file '" . $out . "' for writing");
    }
    // we write this out manually so we can format it
    write_out_formatted_json($fp, $result);
    fclose($fp);
    echo "Wrote " . count($result) . " {$code} strings to '{$out}'\n";
    if ($json['generate_php']) {
        $php = str_replace(".json", ".php", $out);
        $fp = fopen($php, "w");
        if (!$fp) {
            throw new Exception("Could not open destination file '" . $php . "' for writing");
        }
        // we write this out manually so we can format it
        $first = true;
        fwrite($fp, "<?php\n\n/**\n * {$code} template file\n * Generated by translation-discovery at " . date('r') . "\n */\n\n");
        fwrite($fp, '$' . "result = array(\n");
        foreach ($result as $key => $value) {
            fwrite($fp, "\t\"" . phpescapestring($key) . "\" => \"" . phpescapestring($value) . "\",\n");
        }