const fs = require("fs");

const file = fs.readFileSync("./art.ans", "utf8");
const lines = file.split("\n");
const final = [];

for (const line of lines) {
  let result = "";
  let currentBg = "";
  const regex = /(\x1b\[[0-9;]*m|.)/g;
  const parts = line.match(regex) || [];

  for (let i = 0; i < parts.length; i++) {
    const part = parts[i];

    if (part.startsWith("\x1b[")) {
      // Background color tracking
      const params = part.slice(2, -1).split(";");
      const isBg = params.some(p => p === "49" || p.startsWith("4"));
      if (isBg) currentBg = part;

      // Don't immediately output it — we'll output it *before* the next space
      continue;
    }

    if (part === " ") {
      // Always output color + space
      if (currentBg) {
        result += currentBg + " ";
      } else {
        result += " ";
      }
    } else {
      result += part;
    }
  }

  final.push(result);
}

fs.writeFileSync("./newart.ans", final.join("\n"), "utf8");
