const fs = require("fs");

if (process.argv.length < 4) {
  console.error("Usage: node script.js <inputFile> <outputFile>");
  process.exit(1);
}

const inputFile = process.argv[2];
const outputFile = process.argv[3];

const file = fs.readFileSync(inputFile, "utf8");
const lines = file.split("\n");

const final = [];

for (const line of lines) {
  let str = "";
  const chars = line.split("");

  function testSpace(index) {
    if (chars[index - 2] == " ") {
      return testSpace(index - 1);
    } else if (chars[index - 2] == "m") {
      if (chars.join("").substring(index - 5, index - 1) == "[49m") {
        return true;
      } else {
        return false;
      }
    }
    return false;
  }

  for (let i = 0; i < chars.length; i++) {
    const char = chars[i];
    if (char === " ") {
      if (testSpace(i)) {
        str += "\x1b[49m ";
      } else {
        str += char;
      }
    } else {
      str += char;
    }
  }

  final.push(str);
}

fs.writeFileSync(outputFile, final.join("\n"), "utf8");
console.log(`Processed file saved as: ${outputFile}`);
