#include "testlib.h"
#include <string>
#include <sstream>
#include <vector>
#include <cctype>

static const int maxT = 1 << 23; // 8MB-ish

static std::vector<std::string> splitTokens(const std::string &line) {
    std::vector<std::string> tokens;
    std::istringstream iss(line);
    std::string w;
    while (iss >> w) {
        tokens.push_back(w);
    }
    return tokens;
}

static std::string shorten(const std::string &s) {
    const size_t LIM = 50;
    if (s.size() <= LIM) return s;
    return s.substr(0, LIM - 3) + "...";
}

int main(int argc, char *argv[]) {
    registerTestlibCmd(argc, argv);

    int lineNumber = 0;
    int total = 0;

    while (!ouf.eof() && !ans.eof()) {
        std::string outLine = ouf.readLine();
        std::string ansLine = ans.readLine();

        lineNumber += 1;

        total += int(outLine.size()) + 1;
        if (total > maxT) {
            quitf(_wa,
                  "at least %d > %d bytes in output",
                  total, maxT);
        }

        std::vector<std::string> outTokens = splitTokens(outLine);
        std::vector<std::string> ansTokens = splitTokens(ansLine);

        if ((int)outTokens.size() != (int)ansTokens.size()) {
            quitf(_wa,
                  "line %d: %d tokens instead of %d",
                  lineNumber,
                  (int)outTokens.size(),
                  (int)ansTokens.size());
        }

        for (int i = 0; i < (int)outTokens.size(); i++) {
            if (outTokens[i] != ansTokens[i]) {
                quitf(_wa,
                      "line %d, token %d: '%s' instead of `%s'",
                      lineNumber,
                      i + 1,
                      shorten(outTokens[i]).c_str(),
                      shorten(ansTokens[i]).c_str());
            }
        }
    }

    if (!ouf.eof()) {
        quitf(_wa,
              "extra lines: more than %d",
              lineNumber);
    }

    if (!ans.eof()) {
        quitf(_wa,
              "not enough lines: %d",
              lineNumber);
    }

    ouf.seekEof();
    ans.seekEof();

    quitf(_ok, "%d lines", lineNumber);
}
