<?php

function createCSV($testPath, $csvname, $regex) {
    $dir = opendir($testPath);
    $content;
    $maxrow = 0;
    while ($file = readdir($dir)) {
        //if (eregi("[0-9]{2,3}.json_rv1", $file)) {
        if (eregi($regex, $file)) {
            $sourceString = file_get_contents($testPath . $file);
            $source = json_decode($sourceString, true);

            $vector = array();
            foreach ($source as $key => $value) {
                if ($key == 0) {
                    continue;
                }
                array_push($vector, $value);
            }
            $tmpRow = count($vector);
            if ($tmpRow > $maxrow) {
                $maxrow = $tmpRow;
            }
            $content[$file] = $vector;
            #file_put_contents($testPath . $file. ".dat", $content);
            #$script = "set terminal svg;set xrange [1:];set style data lines;set out \"$testPath$file.svg\";plot \"$testPath$file.dat\";";
            #file_put_contents($testPath . $file. ".pl", $script);
            #exec("gnuplot $testPath$file.pl");
        }
    }
//print_r($content);

    $export = "time,";

// Header
    foreach ($content as $key => $value) {
        $export .= $key . ",";
    }

    $export = rtrim($export, ",") . "\n";

    for ($i = 0; $i < $maxrow; $i++) {
        $row = "$i,";
        foreach ($content as $key => $value) {
            if (count($value) > $i) {
                $row.=$value[$i] . ",";
            } else {
                $row.="0,";
            }
        }
        $export .= rtrim($row, ",") . "\n";
    }
    file_put_contents($testPath . $csvname, $export);
    echo $export;
}
createCSV("test/mrdumps/", "all.csv", "[0-9][0-9][0-9].json_rv1");
createCSV("test/mrdumps/", "0xx.csv", "[0][0-9][0-9].json_rv1");
createCSV("test/mrdumps/", "1xx.csv", "[1][0-9][0-9].json_rv1");
createCSV("test/mrdumps/", "2xx.csv", "[2][0-9][0-9].json_rv1");
createCSV("test/mrdumps/", "x0x.csv", "[0-9][0][0-9].json_rv1");
createCSV("test/mrdumps/", "x1x.csv", "[0-9][01][0-9].json_rv1");
createCSV("test/mrdumps/", "x2x.csv", "[0-9][02][0-9].json_rv1");
createCSV("test/mrdumps/", "xx0.csv", "[0-9][0-9][0].json_rv1");
createCSV("test/mrdumps/", "xx1.csv", "[0-9][0-9][1].json_rv1");
createCSV("test/mrdumps/", "xx2.csv", "[0-9][0-9][2].json_rv1");
createCSV("test/mrdumps/", "xx3.csv", "[0-9][0-9][3].json_rv1");
createCSV("test/mrdumps/", "xx4.csv", "[0-9][0-9][4].json_rv1");
createCSV("test/mrdumps/", "xx5.csv", "[0-9][0-9][5].json_rv1");
createCSV("test/mrdumps/", "xx7.csv", "[0-9][0-9][7].json_rv1");
createCSV("test/mrdumps/", "20x.csv", "[2][0][0-9].json_rv1");

?>

