<?php

$dir = dir('in');

while ($f = $dir->read()) {
    if (preg_match('/([0-9]+)\.mht\.gz$/', $f, $match)) {
        echo "$f ";
        $mhtz = file_get_contents("in/$f");
        $mht = gzdecode($mhtz);
    } else if (preg_match('/([0-9]+)\.mht$/', $f, $match)) {
        echo "$f ";
        $mht = file_get_contents("in/$f");
    } else {
        continue;
    }
    $thread = $match[1];
    if (!preg_match('/boundary="([^"]+)"/', $mht, $match)){
        echo "boundary not found\n";
        continue;
    }
    $files = explode($match[1], $mht);

    $outpath = "out/$thread";
    if (!file_exists($outpath)) {
        mkdir($outpath);
    }

    $html = explode("\r\n\r\n", $files[2]);
    $html = base64_decode(($html[1]));

    file_put_contents("$outpath/index.html", $html);

    for ($i = 3; $i < count($files); $i++) {
        $file = explode("\r\n\r\n", $files[$i]);
        if (!preg_match('/Content-Location: ([^\r]+)/s', $file[0], $match)) {
            continue;
        }
        file_put_contents("$outpath/".basename($match[1]), base64_decode($file[1]));
    }

    echo "ok \n";
}