// Poly-fill the String trim method.
if(!String.prototype.trim) {
    String.prototype.trim = function() {
        return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
    };
}

// Create the main header and inline files.
var ForReading = 1, ForWriting = 2, ForAppending = 8;
var fso = WScript.CreateObject("Scripting.FileSystemObject");
var directory = WScript.Arguments(0);
var mainHeaderFile = fso.CreateTextFile(directory + "\\main.h");
var mainInlineFile = fso.CreateTextFile(directory + "\\main.inl");

mainHeaderFile.WriteLine("// Auto-generated; do not edit");
mainInlineFile.WriteLine("\t// Auto-generated; do not edit");

// Read standard input, collecting case and test names.
var tests = {};
while(!WScript.StdIn.AtEndOfStream) {
    var line = WScript.StdIn.ReadLine();
    if(line.indexOf("{") >= 0) {
        var i = line.indexOf('(');
        line = line.substr(i + 1);
        i = line.indexOf(',');
        var caseName = line.substr(0, i);
        var testCase = tests[caseName] = tests[caseName] || [];
        line = line.substr(i + 1).trim();
        i = line.indexOf(')');
        var testName = line.substr(0, i);
        testCase.push(testName);
    }
}

// Populate the main header and inline files and create the test case header files.
for(var key in tests) {
    mainHeaderFile.WriteLine('#include "' + key + '.h"');
    var instanceName = key.toLowerCase();
    mainInlineFile.WriteLine("\t" + key + " " + instanceName + ";");
    var fout = fso.CreateTextFile(directory + "\\" + key + ".h");
    fout.WriteLine("// Auto-generated; do not edit");
    fout.WriteLine("class " + key + " {");
    fout.WriteLine("public:");
    var test = tests[key];
    for(var i = 0, n = test.length; i < n; ++i) {
        fout.WriteLine("\tvoid " + test[i] + "();");
        mainInlineFile.WriteLine('\ttestName= "' + key + "." + test[i] + '";');
        mainInlineFile.WriteLine("\t" + instanceName + "." + test[i] + "();");
    }
    fout.WriteLine("};");
    fout.Close();
}
