import { readdirSync, readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";
import assert from "node:assert/strict";

import {
  createLinuxCncInterpSdk,
  planIniFileContextStaging,
} from "../../../runtime/sdk/src/index.js";
import {
  INTERP_BASELINE_INI_FIXTURE,
  INTERP_COORDINATE_OFFSETS_FILE_FIXTURE,
  INTERP_ERROR_FIXTURES,
  INTERP_FILE_FIXTURES,
  INTERP_INI_FIXTURE,
  INTERP_MDI_FIXTURES,
  INTERP_POSITION_PARAMS_FILE_FIXTURE,
  INTERP_SPINDLE_ORIENT_OFFSET_FIXTURE,
} from "../../fixtures/interp-fixture-matrix.mjs";

function verifyExpectedOutput(fixtureName, output, expectedText) {
  const expectedLines = expectedText.split("\n").filter(Boolean);

  for (const expectedLine of expectedLines) {
    if (expectedLine.startsWith("absent=")) {
      const forbidden = expectedLine.slice("absent=".length);
      assert.equal(
        output.includes(forbidden),
        false,
        `${fixtureName}: unexpected ${forbidden}`,
      );
      continue;
    }

    assert.equal(
      output.includes(expectedLine),
      true,
      `${fixtureName}: ${expectedLine}`,
    );
  }
}

function verifyExpectedFileError(fixtureName, output, expectedText) {
  assert.equal(
    output.includes("file_open=0"),
    true,
    `${fixtureName}: file open`,
  );

  const expectedLines = expectedText.split("\n").filter(Boolean);
  for (const expectedLine of expectedLines) {
    if (expectedLine.startsWith("absent=")) {
      const forbidden = expectedLine.slice("absent=".length);
      assert.equal(
        output.includes(forbidden),
        false,
        `${fixtureName}: unexpected ${forbidden}`,
      );
      continue;
    }

    if (expectedLine.startsWith("error_text=")) {
      const message = expectedLine.slice("error_text=".length);
      assert.equal(
        output.includes(`file_error_text=${message}`),
        true,
        `${fixtureName}: ${message}`,
      );
      continue;
    }

    if (expectedLine.startsWith("canon_event=")) {
      assert.equal(
        output.includes(expectedLine),
        true,
        `${fixtureName}: ${expectedLine}`,
      );
    }
  }
}

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = resolve(__dirname, "../../..");
const wasmPath = resolve(rootDir, "build/wasm/core/linuxcnc_interp.wasm");
const manifestText = readFileSync(resolve(rootDir, "tools/source-manifest.txt"), "utf8");
const interpPrints = [];

const interp = await createLinuxCncInterpSdk({
  wasmBinary: readFileSync(wasmPath),
  print(message) {
    interpPrints.push(message);
  },
  printErr(message) {
    console.error(message);
  },
});

function runWithCapturedPrints(operation) {
  interpPrints.length = 0;
  const output = operation();
  return { output, prints: interpPrints.join("\n") };
}

function writeVendorTextFile(sourcePath, wasmPath, targetInterp = interp) {
  targetInterp.writeTextFile(wasmPath, readFileSync(sourcePath, "utf8"));
}

function writeLocalIniFixture(filename, wasmPath, expectedWasmPath, targetInterp = interp) {
  assert.equal(wasmPath, expectedWasmPath, `${filename} local ini staging path drift`);
  targetInterp.writeTextFile(
    wasmPath,
    readFileSync(resolve(rootDir, `tests/fixtures/ini/${filename}`), "utf8"),
  );
  return wasmPath;
}

function writeLocalGcodeFixture(fixtureName, wasmPath, expectedWasmPath, targetInterp = interp) {
  assert.equal(wasmPath, expectedWasmPath, `${fixtureName} local gcode staging path drift`);
  targetInterp.writeTextFile(
    wasmPath,
    readFileSync(resolve(rootDir, `tests/fixtures/gcode/${fixtureName}.ngc`), "utf8"),
  );
  return wasmPath;
}

function writeLocalErrorGcodeFixture(fixtureName, wasmPath, expectedWasmPath, targetInterp = interp) {
  assert.equal(wasmPath, expectedWasmPath, `${fixtureName} local error gcode staging path drift`);
  targetInterp.writeTextFile(
    wasmPath,
    readFileSync(resolve(rootDir, `tests/fixtures/gcode_errors/${fixtureName}.ngc`), "utf8"),
  );
  return wasmPath;
}

function writeIniToolTableFixtureStaging(wasmDir, expectedWasmDir, targetInterp = interp) {
  assert.equal(wasmDir, expectedWasmDir, "ini_tool_table staging root drift");
  const files = ["ini_tool_table.ini", "ini_tool_table.tbl", "ini_tool_table.ngc"];
  assert.equal(new Set(files).size, files.length, "ini_tool_table staging manifest duplicate");
  for (const file of files) {
    assert.equal(`${wasmDir}/${file}`, `${expectedWasmDir}/${file}`, `ini_tool_table ${file} staging path drift`);
  }

  writeLocalIniFixture("ini_tool_table.ini", `${wasmDir}/ini_tool_table.ini`, `${expectedWasmDir}/ini_tool_table.ini`, targetInterp);
  writeLocalIniFixture("ini_tool_table.tbl", `${wasmDir}/ini_tool_table.tbl`, `${expectedWasmDir}/ini_tool_table.tbl`, targetInterp);
  writeLocalGcodeFixture("ini_tool_table", `${wasmDir}/ini_tool_table.ngc`, `${expectedWasmDir}/ini_tool_table.ngc`, targetInterp);

  return {
    iniPath: `${wasmDir}/ini_tool_table.ini`,
    programPath: `${wasmDir}/ini_tool_table.ngc`,
  };
}

function writeG92PersistenceStaging(wasmDir, expectedWasmDir, targetInterp = interp) {
  assert.equal(wasmDir, expectedWasmDir, "g92 persistence staging root drift");
  const files = ["test.ngc", "startup.var", "persist.ini", "disabled.ini"];
  assert.equal(new Set(files).size, files.length, "g92 persistence staging manifest duplicate");
  for (const file of files) {
    assert.equal(`${wasmDir}/${file}`, `${expectedWasmDir}/${file}`, `g92 persistence ${file} staging path drift`);
  }

  const programPath = `${wasmDir}/test.ngc`;
  const parameterPath = `${wasmDir}/startup.var`;
  const iniPath = `${wasmDir}/persist.ini`;
  const disabledIniPath = `${wasmDir}/disabled.ini`;

  targetInterp.writeTextFile(
    programPath,
    [
      "(PRINT,Startup G92 params: #5210 #5211 #5212 #5213)",
      "M30",
      "",
    ].join("\n"),
  );
  targetInterp.writeTextFile(
    parameterPath,
    [
      "5210 1",
      "5211 1.25",
      "5212 2.5",
      "5213 3.75",
      "5220 1",
      "",
    ].join("\n"),
  );
  targetInterp.writeTextFile(
    iniPath,
    [
      "[RS274NGC]",
      "PARAMETER_FILE = startup.var",
      "[TRAJ]",
      "COORDINATES = X Y Z",
      "",
    ].join("\n"),
  );
  targetInterp.writeTextFile(
    disabledIniPath,
    [
      "[RS274NGC]",
      "PARAMETER_FILE = startup.var",
      "DISABLE_G92_PERSISTENCE = 1",
      "[TRAJ]",
      "COORDINATES = X Y Z",
      "",
    ].join("\n"),
  );

  return { disabledIniPath, iniPath, parameterPath, programPath };
}

function generatedParameterPath(wasmPath, expectedWasmPath) {
  assert.equal(wasmPath, expectedWasmPath, `parameter fixture ${expectedWasmPath} staging path drift`);
  return wasmPath;
}

function writeGeneratedParameterFixture(wasmPath, expectedWasmPath, text, targetInterp = interp) {
  const checkedPath = generatedParameterPath(wasmPath, expectedWasmPath);
  targetInterp.writeTextFile(checkedPath, text);
  return checkedPath;
}

function generatedToolTablePath(wasmPath, expectedWasmPath) {
  assert.equal(wasmPath, expectedWasmPath, `tool table fixture ${expectedWasmPath} staging path drift`);
  return wasmPath;
}

function writeGeneratedToolTableFixture(wasmPath, expectedWasmPath, text, targetInterp = interp) {
  const checkedPath = generatedToolTablePath(wasmPath, expectedWasmPath);
  targetInterp.writeTextFile(checkedPath, text);
  return checkedPath;
}

function stageInterpIniContext(name, programFile = "test.ngc") {
  const sourceRootRel = `tests/interp/${name}`;
  const iniText = readFileSync(
    resolve(rootDir, "vendor/linuxcnc", sourceRootRel, "test.ini"),
    "utf8",
  );
  const plan = planIniFileContextStaging({
    manifestText,
    sourceRootRel,
    iniFile: "test.ini",
    iniText,
    programFile,
    wasmDir: `/work/interp/${name}`,
  });

  for (const file of plan.files) {
    writeVendorTextFile(resolve(rootDir, "vendor/linuxcnc", file.sourceRel), file.wasmPath);
    if (file.executable) {
      interp.module.FS.chmod(file.wasmPath, 0o755);
    }
  }

  return plan;
}

function assertFiveAxisMachineNgcCoverage(name, sourceDir, subdir, files) {
  const expectedFiles = files
    .filter((file) => file.startsWith(`${subdir}/`) && file.endsWith(".ngc"))
    .map((file) => file.slice(subdir.length + 1))
    .sort();
  assert.deepEqual(
    readdirSync(resolve(sourceDir, subdir))
      .filter((filename) => filename.endsWith(".ngc"))
      .sort(),
    expectedFiles,
    `fiveaxis ${name}/${subdir} fixture coverage drift`,
  );
}

function assertFiveAxisMachineFilesStaging(name, files, wasmDir, expectedWasmDir) {
  assert.equal(wasmDir, expectedWasmDir, `fiveaxis ${name} staging root drift`);
  assert.equal(new Set(files).size, files.length, `fiveaxis ${name} staging manifest duplicate`);
  for (const file of files) {
    assert.equal(
      `${wasmDir}/${file}`,
      `${expectedWasmDir}/${file}`,
      `fiveaxis ${name}/${file} staging manifest drift`,
    );
  }
}

function writeFiveAxisMachineFiles(name, sourceDir, wasmDir, expectedWasmDir, files) {
  assertFiveAxisMachineFilesStaging(name, files, wasmDir, expectedWasmDir);
  for (const file of files) {
    writeVendorTextFile(resolve(sourceDir, file), `${wasmDir}/${file}`);
  }
  return wasmDir;
}

function writeFiveAxisTrtMachineFiles() {
  const sourceDir = resolve(
    rootDir,
    "vendor/linuxcnc/configs/sim/axis/vismach/5axis/table-rotary-tilting",
  );
  const wasmDir = "/work/fiveaxis/table-rotary-tilting";
  const files = [
    "xyzac-trt.ini",
    "xyzbc-trt.ini",
    "xyzac-trt.tbl",
    "xyzbc-trt.tbl",
    "remap_subs/428remap.ngc",
    "remap_subs/429remap.ngc",
    "remap_subs/430remap.ngc",
    "remap_subs/centering.ngc",
    "remap_subs/helix_ac.ngc",
    "remap_subs/helix_bc.ngc",
    "remap_subs/xyzac_switchkins_sub.ngc",
    "remap_subs/xyzbc_switchkins_sub.ngc",
    "demos/xyzac_switchkins.ngc",
    "demos/xyzbc_switchkins.ngc",
    "demos/xyzac_switchkins_test_1.ngc",
    "demos/xyzac_switchkins_test_2.ngc",
    "demos/xyzac_switchkins_test_3.ngc",
    "demos/boat-xyzac.ngc",
    "demos/boat-xyzbc.ngc",
    "demos/impeller-7bl-xyzac.ngc",
  ];

  assertFiveAxisMachineNgcCoverage("table-rotary-tilting", sourceDir, "remap_subs", files);
  assertFiveAxisMachineNgcCoverage("table-rotary-tilting", sourceDir, "demos", files);
  return writeFiveAxisMachineFiles(
    "table-rotary-tilting",
    sourceDir,
    wasmDir,
    "/work/fiveaxis/table-rotary-tilting",
    files,
  );
}

function writeFiveAxisTdrMachineFiles() {
  const sourceDir = resolve(
    rootDir,
    "vendor/linuxcnc/configs/sim/axis/vismach/5axis/table-dual-rotary",
  );
  const wasmDir = "/work/fiveaxis/table-dual-rotary";
  const files = [
    "xyzab-tdr.ini",
    "xyzab-tdr.tbl",
    "remap_subs/428remap.ngc",
    "remap_subs/429remap.ngc",
    "demos/xyzab-tdr-demo.ngc",
  ];

  assertFiveAxisMachineNgcCoverage("table-dual-rotary", sourceDir, "remap_subs", files);
  assertFiveAxisMachineNgcCoverage("table-dual-rotary", sourceDir, "demos", files);
  return writeFiveAxisMachineFiles(
    "table-dual-rotary",
    sourceDir,
    wasmDir,
    "/work/fiveaxis/table-dual-rotary",
    files,
  );
}

function writeFiveAxisBridgeMillMachineFiles() {
  const sourceDir = resolve(
    rootDir,
    "vendor/linuxcnc/configs/sim/axis/vismach/5axis/bridgemill",
  );
  const wasmDir = "/work/fiveaxis/bridgemill";
  const files = [
    "5axis.ini",
    "5axis.tbl",
    "remap_subs/428remap.ngc",
    "remap_subs/429remap.ngc",
    "remap_subs/430remap.ngc",
    "5axisgui.ngc",
  ];

  assertFiveAxisMachineNgcCoverage("bridgemill", sourceDir, "remap_subs", files);
  return writeFiveAxisMachineFiles(
    "bridgemill",
    sourceDir,
    wasmDir,
    "/work/fiveaxis/bridgemill",
    files,
  );
}

function writeRemapRegressionFiles(name, files) {
  const sourceDir = resolve(rootDir, "vendor/linuxcnc/tests/remap", name);
  const wasmDir = `/work/remap/${name}`;

  for (const filename of files) {
    writeVendorTextFile(resolve(sourceDir, filename), `${wasmDir}/${filename}`);
  }

  return wasmDir;
}

function assertRemapRegressionCoverage(name, files, expectedUnstagedFiles = []) {
  const sourceDir = resolve(rootDir, "vendor/linuxcnc/tests/remap", name);
  assert.deepEqual(
    readdirSync(sourceDir)
      .filter((filename) => filename.endsWith(".ini") || filename.endsWith(".ngc"))
      .sort(),
    [...files, ...expectedUnstagedFiles].sort(),
    `remap ${name} fixture coverage drift`,
  );
  assert.deepEqual(
    files.filter((file) => expectedUnstagedFiles.includes(file)),
    [],
    `remap ${name} unstaged fixture overlap drift`,
  );
}

function assertRemapRegressionFilesStaging(name, files, wasmDir) {
  for (const file of files) {
    assert.equal(
      `${wasmDir}/${file}`,
      `/work/remap/${name}/${file}`,
      `remap ${name}/${file} staging manifest drift`,
    );
  }
}

function assertRemapRegressionGeneratedFileStaging(name, filename, wasmPath) {
  assert.equal(
    wasmPath,
    `/work/remap/${name}/${filename}`,
    `remap ${name}/${filename} generated staging path drift`,
  );
}

function writeInterpRegressionFile(name, filename) {
  const sourceDir = resolve(rootDir, "vendor/linuxcnc/tests/interp", name);
  const wasmDir = `/work/interp/${name}`;

  writeVendorTextFile(resolve(sourceDir, filename), `${wasmDir}/${filename}`);

  return `${wasmDir}/${filename}`;
}

function assertInterpRegressionFileStaging(name, filename, wasmPath) {
  assert.equal(
    wasmPath,
    `/work/interp/${name}/${filename}`,
    `interp ${name}/${filename} staging manifest drift`,
  );
}

function stripInterpIniContextStagingPrefix(name, wasmPath) {
  const prefix = `/work/interp/${name}/`;
  assert.equal(
    wasmPath.startsWith(prefix),
    true,
    `interp ${name} staging prefix drift: ${wasmPath}`,
  );
  return wasmPath.slice(prefix.length);
}

function assertInterpIniContextNgcStaging(name, files, plan) {
  assert.deepEqual(
    plan.files
      .filter((file) => file.sourceRel.endsWith(".ngc"))
      .map((file) => stripInterpIniContextStagingPrefix(name, file.wasmPath))
      .sort(),
    files,
    `interp ${name} staging manifest drift`,
  );
}

function writeInterpRegressionFiles(name, files) {
  const sourceDir = resolve(rootDir, "vendor/linuxcnc/tests/interp", name);
  const wasmDir = `/work/interp/${name}`;

  for (const filename of files) {
    writeVendorTextFile(resolve(sourceDir, filename), `${wasmDir}/${filename}`);
  }

  return wasmDir;
}

function assertInterpRegressionFilesCoverage(name, files) {
  const sourceDir = resolve(rootDir, "vendor/linuxcnc/tests/interp", name);
  assert.deepEqual(
    readdirSync(sourceDir)
      .filter((filename) => filename.endsWith(".ini") || filename.endsWith(".ngc") || filename.endsWith(".tbl"))
      .sort(),
    [...files].sort(),
    `interp ${name} fixture coverage drift`,
  );
}

function assertInterpRegressionFilesStaging(name, files, wasmDir) {
  for (const file of files) {
    assertInterpRegressionFileStaging(name, file, `${wasmDir}/${file}`);
  }
}

function interpRegressionNgcFiles(name) {
  const sourceDir = resolve(rootDir, "vendor/linuxcnc/tests/interp", name);
  return readdirSync(sourceDir)
    .filter((filename) => filename.endsWith(".ngc"))
    .sort();
}

function interpRegressionNgcFilesRecursive(name) {
  const sourceDir = resolve(rootDir, "vendor/linuxcnc/tests/interp", name);
  const files = [];

  function walk(relativeDir) {
    const directory = resolve(sourceDir, relativeDir);
    for (const entry of readdirSync(directory, { withFileTypes: true })) {
      const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;
      if (entry.isDirectory()) {
        walk(relativePath);
        continue;
      }
      if (entry.isFile() && entry.name.endsWith(".ngc")) {
        files.push(relativePath);
      }
    }
  }

  walk("");
  return files.sort();
}

function writeCcompRegressionFiles(name) {
  const sourceDir = resolve(rootDir, "vendor/linuxcnc/tests/ccomp", name);
  const wasmDir = `/work/ccomp/${name}`;

  writeVendorTextFile(resolve(sourceDir, "test.ngc"), `${wasmDir}/test.ngc`);
  writeVendorTextFile(resolve(sourceDir, "test.tbl"), `${wasmDir}/test.tbl`);
  interp.writeTextFile(
    `${wasmDir}/test.ini`,
    [
      "[EMCIO]",
      "TOOL_TABLE = test.tbl",
      "[TRAJ]",
      "COORDINATES = X Y Z A B C U V W",
      "",
    ].join("\n"),
  );

  return wasmDir;
}

const ccompRegressionFiles = [
  "test.ngc",
  "test.tbl",
];

function assertCcompRegressionCoverage(name) {
  const sourceDir = resolve(rootDir, "vendor/linuxcnc/tests/ccomp", name);
  assert.deepEqual(
    readdirSync(sourceDir)
      .filter((filename) => filename.endsWith(".ngc") || filename.endsWith(".tbl"))
      .sort(),
    ccompRegressionFiles,
    `interp ccomp ${name} fixture coverage drift`,
  );
}

function assertCcompRegressionFilesStaging(name, wasmDir) {
  for (const file of ccompRegressionFiles) {
    assert.equal(
      `${wasmDir}/${file}`,
      `/work/ccomp/${name}/${file}`,
      `interp ccomp ${name}/${file} staging manifest drift`,
    );
  }
}

function writeG10RegressionFiles(name, files) {
  const sourceDir = resolve(rootDir, "vendor/linuxcnc/tests/interp/g10", name);
  const wasmDir = `/work/interp/g10/${name}`;

  for (const filename of files) {
    writeVendorTextFile(resolve(sourceDir, filename), `${wasmDir}/${filename}`);
  }

  if (files.includes("test.tbl")) {
    interp.writeTextFile(
      `${wasmDir}/test.ini`,
      [
        "[EMCIO]",
        "TOOL_TABLE = test.tbl",
        "[TRAJ]",
        "COORDINATES = X Y Z A B C U V W",
        "",
      ].join("\n"),
    );
  }

  return wasmDir;
}

function assertG10RegressionCoverage(name, files) {
  const sourceDir = resolve(rootDir, "vendor/linuxcnc/tests/interp/g10", name);
  assert.deepEqual(
    readdirSync(sourceDir)
      .filter((filename) => filename.endsWith(".ngc") || filename.endsWith(".tbl"))
      .sort(),
    [...files].sort(),
    `interp g10 ${name} fixture coverage drift`,
  );
}

function assertG10RegressionFilesStaging(name, files, wasmDir) {
  for (const file of files) {
    assert.equal(
      `${wasmDir}/${file}`,
      `/work/interp/g10/${name}/${file}`,
      `interp g10 ${name}/${file} staging manifest drift`,
    );
  }
}

function assertUserMCodeFixtureStaging(name, code, wasmDir) {
  const expectedWasmDir = `/work/user-m/${name}`;
  const files = ["test.ini", "test.ngc", code];
  assert.equal(wasmDir, expectedWasmDir, `user-m ${name} staging root drift`);
  assert.equal(new Set(files).size, files.length, `user-m ${name} staging manifest duplicate`);
  for (const file of files) {
    assert.equal(
      `${wasmDir}/${file}`,
      `${expectedWasmDir}/${file}`,
      `user-m ${name}/${file} staging path drift`,
    );
  }
}

function writeUserMCodeFixture(name, code) {
  const wasmDir = `/work/user-m/${name}`;
  assertUserMCodeFixtureStaging(name, code, wasmDir);
  const iniPath = `${wasmDir}/test.ini`;
  const programPath = `${wasmDir}/test.ngc`;
  const mcodePath = `${wasmDir}/${code}`;

  interp.writeTextFile(
    iniPath,
    [
      "[DISPLAY]",
      "PROGRAM_PREFIX = .",
      "",
      "[RS274NGC]",
      "USER_M_PATH = .",
      "",
      "[TRAJ]",
      "COORDINATES = XYZ",
    ].join("\n"),
  );
  interp.writeTextFile(programPath, `${code}\nM2\n`);
  interp.writeTextFile(mcodePath, "#!/bin/sh\nexit 0\n");
  interp.module.FS.chmod(mcodePath, 0o755);

  return { iniPath, programPath };
}

const namedParamIniPath = "/work/namedparams.ini";
interp.writeTextFile(
  namedParamIniPath,
  readFileSync(resolve(rootDir, "tests/fixtures/ini/namedparams.ini"), "utf8"),
);

verifyExpectedOutput(
  "probe_init_and_synch",
  interp.probeInitAndSynch(),
  [
    "init=0",
    "setup.length_units=2",
    "setup.origin_index=1",
    "setup.distance_mode=0",
    "setup.feed_mode=0",
    "setup.motion_mode=800",
    "canon_event=INIT_CANON",
    "canon_event=USE_LENGTH_UNITS units=2",
    "canon_event=SET_G5X_OFFSET index=1",
    "canon_event=SET_G92_OFFSET x=0 y=0 z=0",
    "canon_event=SET_XY_ROTATION rotation=0",
    "canon_event=SET_FEED_REFERENCE reference=2",
    "inch_init=0",
    "inch_setup.length_units=1",
    "inch_external_length_units=0.0393701",
    "inch_canon_event=USE_LENGTH_UNITS units=1",
    "synch=0",
    "synch.current_pocket=2",
    "synch.selected_pocket=2",
    "synch.tool_0=2",
    "synch.tool_2=2",
  ].join("\n"),
);

verifyExpectedOutput(
  "probe_indexer",
  interp.probeIndexer(),
  [
    "execute=0",
    "post_a=90",
    "canon_event=SET_MOTION_CONTROL_MODE mode=2 tolerance=0",
    "canon_event=UNLOCK_ROTARY line=1 joint=0",
    "canon_event=STRAIGHT_TRAVERSE line=1 x=0 y=0 z=0 a=90 b=0 c=0 u=0 v=0 w=0",
    "canon_event=LOCK_ROTARY line=1 joint=0",
    "canon_event=SET_MOTION_CONTROL_MODE mode=1 tolerance=0",
    "canon_event=SET_NAIVECAM_TOLERANCE tolerance=0",
    "canon_event=UPDATE_TAG line=1",
  ].join("\n"),
);

verifyExpectedOutput(
  "probe_named_parameters",
  interp.probeNamedParameters(namedParamIniPath),
  [
    "init_named_parameters=0",
    "global_named_count=57",
    "_metric_machine: rc=0 found=1 value=1",
    "_motion_mode: rc=0 found=1 value=10",
    "_metric: rc=0 found=1 value=1",
    "_feed: rc=0 found=1 value=123.45",
    "_rpm: rc=0 found=1 value=678.9",
    "_x: rc=0 found=1 value=1.25",
    "_current_tool: rc=0 found=1 value=12",
    "_ini[traj]max_linear_velocity: rc=0 found=1 value=35",
    "_hal[standalone.pin-bit]: rc=0 found=1 value=1",
    "_hal[standalone.signal-float]: rc=0 found=1 value=98.25",
    "_hal[standalone.param-s32]: rc=0 found=1 value=-17",
    "_hal[standalone.pin-u32]: rc=0 found=1 value=1.23457e+08",
    "_hal[standalone.signal-s64]: rc=0 found=1 value=-9e+09",
    "_hal[standalone.param-u64]: rc=0 found=1 value=9e+09",
    "_hal[standalone.disconnected-float]: rc=0 found=1 value=12.5",
    "_hal[standalone.missing]: rc=0 found=0 value=0",
  ].join("\n"),
);

for (const fixtureName of INTERP_MDI_FIXTURES) {
  const programText = readFileSync(
    resolve(rootDir, `tests/fixtures/gcode/${fixtureName}.ngc`),
    "utf8",
  );
  const expectedEvents = readFileSync(
    resolve(rootDir, `tests/fixtures/canon/${fixtureName}.events`),
    "utf8",
  ).trimEnd();

  verifyExpectedOutput(fixtureName, interp.runProgram(programText), expectedEvents);
}

const namedParamProgramText = readFileSync(
  resolve(rootDir, `tests/fixtures/gcode/${INTERP_INI_FIXTURE}.ngc`),
  "utf8",
);
const namedParamExpected = readFileSync(
  resolve(rootDir, `tests/fixtures/canon/${INTERP_INI_FIXTURE}.events`),
  "utf8",
).trimEnd();
verifyExpectedOutput(
  INTERP_INI_FIXTURE,
  interp.runProgramWithIni(namedParamProgramText, namedParamIniPath),
  namedParamExpected,
);

const baselineIniProgramText = readFileSync(
  resolve(rootDir, `tests/fixtures/gcode/${INTERP_BASELINE_INI_FIXTURE}.ngc`),
  "utf8",
);
const baselineIniExpected = readFileSync(
  resolve(rootDir, `tests/fixtures/canon/${INTERP_BASELINE_INI_FIXTURE}.events`),
  "utf8",
).trimEnd();
verifyExpectedOutput(
  INTERP_BASELINE_INI_FIXTURE,
  interp.runProgramWithIni(baselineIniProgramText, namedParamIniPath),
  baselineIniExpected,
);

const spindleOrientOffsetProgramText = readFileSync(
  resolve(rootDir, `tests/fixtures/gcode/${INTERP_SPINDLE_ORIENT_OFFSET_FIXTURE}.ngc`),
  "utf8",
);
const spindleOrientOffsetExpected = readFileSync(
  resolve(rootDir, `tests/fixtures/canon/${INTERP_SPINDLE_ORIENT_OFFSET_FIXTURE}.events`),
  "utf8",
).trimEnd();
const spindleOrientOffsetIniPath = writeLocalIniFixture(
  "spindle_orient_offset.ini",
  "/work/spindle-orient-offset.ini",
  "/work/spindle-orient-offset.ini",
);
const disableFanucStyleSubIniPath = writeLocalIniFixture(
  "disable_fanuc_style_sub.ini",
  "/work/disable-fanuc-style-sub.ini",
  "/work/disable-fanuc-style-sub.ini",
);
verifyExpectedOutput(
  INTERP_SPINDLE_ORIENT_OFFSET_FIXTURE,
  interp.runProgramWithIni(spindleOrientOffsetProgramText, spindleOrientOffsetIniPath),
  spindleOrientOffsetExpected,
);

for (const fixtureName of INTERP_ERROR_FIXTURES) {
  const programText = readFileSync(
    resolve(rootDir, `tests/fixtures/gcode_errors/${fixtureName}.ngc`),
    "utf8",
  );
  const expectedOutput = readFileSync(
    resolve(rootDir, `tests/fixtures/canon_errors/${fixtureName}.expected`),
    "utf8",
  ).trimEnd();

  verifyExpectedOutput(fixtureName, interp.runProgram(programText), expectedOutput);
}

for (const fixtureName of INTERP_ERROR_FIXTURES) {
  const programPath = writeLocalErrorGcodeFixture(
    fixtureName,
    `/work/${fixtureName}-error.ngc`,
    `/work/${fixtureName}-error.ngc`,
  );
  const expectedOutput = readFileSync(
    resolve(rootDir, `tests/fixtures/canon_errors/${fixtureName}.expected`),
    "utf8",
  ).trimEnd();

  verifyExpectedFileError(fixtureName, interp.runFile(programPath), expectedOutput);
}

for (const fixtureName of INTERP_FILE_FIXTURES) {
  const programPath = writeLocalGcodeFixture(
    fixtureName,
    `/work/${fixtureName}.ngc`,
    `/work/${fixtureName}.ngc`,
  );
  const expectedEvents = readFileSync(
    resolve(rootDir, `tests/fixtures/canon/${fixtureName}.events`),
    "utf8",
  ).trimEnd();

  verifyExpectedOutput(fixtureName, interp.runFile(programPath), expectedEvents);
}

const minimalLinearRunStepsPath = writeLocalGcodeFixture(
  "minimal_linear",
  "/work/minimal_linear.ngc",
  "/work/minimal_linear.ngc",
);
verifyExpectedOutput(
  "minimal_linear_run_steps",
  interp.runFile(minimalLinearRunStepsPath),
  [
    "run_step phase=read step=1 rc=0 line=1",
    "run_step phase=execute step=1 rc=0 line=1 x=1 y=2 z=0",
    "statement_uri=G0%20X1.0%20Y2.0%20%28Comment%29",
    "run_step phase=execute step=2 rc=0 line=2 x=3 y=4 z=0",
    "statement_uri=G1%20X3.0%20Y4.0%20F120.0",
  ].join("\n"),
);

const namedParamFilePath = writeLocalGcodeFixture(
  INTERP_INI_FIXTURE,
  `/work/${INTERP_INI_FIXTURE}.ngc`,
  `/work/${INTERP_INI_FIXTURE}.ngc`,
);
verifyExpectedOutput(
  "namedparam_semantics_file",
  interp.runFileWithIni(namedParamFilePath, namedParamIniPath),
  namedParamExpected,
);

const iniToolTableDir = "/work/ini-tool-table";
const iniToolTable = writeIniToolTableFixtureStaging(
  iniToolTableDir,
  "/work/ini-tool-table",
);
verifyExpectedOutput(
  "ini_tool_table_file",
  interp.runFileWithIni(iniToolTable.programPath, iniToolTable.iniPath),
  readFileSync(resolve(rootDir, "tests/fixtures/canon/ini_tool_table.events"), "utf8").trimEnd(),
);

const baselineIniFilePath = writeLocalGcodeFixture(
  INTERP_BASELINE_INI_FIXTURE,
  `/work/${INTERP_BASELINE_INI_FIXTURE}.ngc`,
  `/work/${INTERP_BASELINE_INI_FIXTURE}.ngc`,
);
verifyExpectedOutput(
  `${INTERP_BASELINE_INI_FIXTURE}_file`,
  interp.runFileWithIni(baselineIniFilePath, namedParamIniPath),
  baselineIniExpected,
);

const spindleOrientOffsetFilePath = writeLocalGcodeFixture(
  INTERP_SPINDLE_ORIENT_OFFSET_FIXTURE,
  `/work/${INTERP_SPINDLE_ORIENT_OFFSET_FIXTURE}.ngc`,
  `/work/${INTERP_SPINDLE_ORIENT_OFFSET_FIXTURE}.ngc`,
);
verifyExpectedOutput(
  `${INTERP_SPINDLE_ORIENT_OFFSET_FIXTURE}_file`,
  interp.runFileWithIni(spindleOrientOffsetFilePath, spindleOrientOffsetIniPath),
  spindleOrientOffsetExpected,
);

const disableFanucStyleSubFilePath = writeLocalGcodeFixture(
  "disable_fanuc_style_sub_m98",
  "/work/disable_fanuc_style_sub_m98.ngc",
  "/work/disable_fanuc_style_sub_m98.ngc",
);
verifyExpectedOutput(
  "disable_fanuc_style_sub_m98_file_wasm",
  interp.runFileWithIni(disableFanucStyleSubFilePath, disableFanucStyleSubIniPath),
  [
    "file_open=0",
    "file_saw_error=1",
    "file_error_text=DISABLE_FANUC_STYLE_SUB set in INI file, but found m98",
  ].join("\n"),
);

const coordinateOffsetsFilePath = writeLocalGcodeFixture(
  INTERP_COORDINATE_OFFSETS_FILE_FIXTURE,
  `/work/${INTERP_COORDINATE_OFFSETS_FILE_FIXTURE}.ngc`,
  `/work/${INTERP_COORDINATE_OFFSETS_FILE_FIXTURE}.ngc`,
);
verifyExpectedOutput(
  `${INTERP_COORDINATE_OFFSETS_FILE_FIXTURE}_file`,
  interp.runFile(coordinateOffsetsFilePath),
  readFileSync(
    resolve(
      rootDir,
      `tests/fixtures/canon_file/${INTERP_COORDINATE_OFFSETS_FILE_FIXTURE}.events`,
    ),
    "utf8",
  ).trimEnd(),
);

const positionParamsFilePath = writeLocalGcodeFixture(
  INTERP_POSITION_PARAMS_FILE_FIXTURE,
  `/work/${INTERP_POSITION_PARAMS_FILE_FIXTURE}.ngc`,
  `/work/${INTERP_POSITION_PARAMS_FILE_FIXTURE}.ngc`,
);
verifyExpectedOutput(
  `${INTERP_POSITION_PARAMS_FILE_FIXTURE}_file`,
  interp.runFile(positionParamsFilePath),
  readFileSync(
    resolve(
      rootDir,
      `tests/fixtures/canon_file/${INTERP_POSITION_PARAMS_FILE_FIXTURE}.events`,
    ),
    "utf8",
  ).trimEnd(),
);

const fiveAxisTrtDir = writeFiveAxisTrtMachineFiles();
verifyExpectedOutput(
  "fiveaxis_xyzac_switchkins_wasm",
  interp.runFiveAxisRemapFile(
    `${fiveAxisTrtDir}/demos/xyzac_switchkins.ngc`,
    `${fiveAxisTrtDir}/xyzac-trt.ini`,
  ),
  [
    "fiveaxis_ini_open=1",
    "fiveaxis_tool_table_load=0",
    "fiveaxis_parse_remap_1=0",
    "fiveaxis_parse_remap_2=0",
    "fiveaxis_parse_remap_3=0",
    "fiveaxis_parsed_remap_count=3",
    "fiveaxis_remaps_ready=1",
    "fiveaxis_file_open=0",
    "fiveaxis_file_read_count=620",
    "fiveaxis_file_execute_count=620",
    "fiveaxis_file_finish_count=21",
    "fiveaxis_file_final_rc=1",
    "fiveaxis_file_reached_exit=1",
    "fiveaxis_hal_switchkins: rc=0 found=1 value=0",
    "fiveaxis_linuxcnc_remap_file_execute=1",
  ].join("\n"),
);
verifyExpectedOutput(
  "fiveaxis_xyzbc_switchkins_wasm",
  interp.runFiveAxisRemapFile(
    `${fiveAxisTrtDir}/demos/xyzbc_switchkins.ngc`,
    `${fiveAxisTrtDir}/xyzbc-trt.ini`,
  ),
  [
    "fiveaxis_ini_open=1",
    "fiveaxis_tool_table_load=0",
    "fiveaxis_parse_remap_1=0",
    "fiveaxis_parse_remap_2=0",
    "fiveaxis_parse_remap_3=0",
    "fiveaxis_parsed_remap_count=3",
    "fiveaxis_remaps_ready=1",
    "fiveaxis_file_open=0",
    "fiveaxis_file_read_count=620",
    "fiveaxis_file_execute_count=620",
    "fiveaxis_file_finish_count=21",
    "fiveaxis_file_final_rc=1",
    "fiveaxis_file_reached_exit=1",
    "fiveaxis_hal_switchkins: rc=0 found=1 value=0",
    "fiveaxis_linuxcnc_remap_file_execute=1",
  ].join("\n"),
);
verifyExpectedOutput(
  "fiveaxis_xyzac_switchkins_test_1_wasm",
  interp.runFiveAxisRemapFile(
    `${fiveAxisTrtDir}/demos/xyzac_switchkins_test_1.ngc`,
    `${fiveAxisTrtDir}/xyzac-trt.ini`,
  ),
  [
    "fiveaxis_ini_open=1",
    "fiveaxis_tool_table_load=0",
    "fiveaxis_parse_remap_1=0",
    "fiveaxis_parse_remap_2=0",
    "fiveaxis_parse_remap_3=0",
    "fiveaxis_parsed_remap_count=3",
    "fiveaxis_remaps_ready=1",
    "fiveaxis_file_open=0",
    "fiveaxis_file_read_count=248",
    "fiveaxis_file_execute_count=248",
    "fiveaxis_file_finish_count=9",
    "fiveaxis_file_final_rc=1",
    "fiveaxis_file_reached_exit=1",
    "fiveaxis_hal_switchkins: rc=0 found=1 value=0",
    "fiveaxis_linuxcnc_remap_file_execute=1",
  ].join("\n"),
);
verifyExpectedOutput(
  "fiveaxis_xyzac_switchkins_test_2_wasm",
  interp.runFiveAxisRemapFile(
    `${fiveAxisTrtDir}/demos/xyzac_switchkins_test_2.ngc`,
    `${fiveAxisTrtDir}/xyzac-trt.ini`,
  ),
  [
    "fiveaxis_ini_open=1",
    "fiveaxis_tool_table_load=0",
    "fiveaxis_parse_remap_1=0",
    "fiveaxis_parse_remap_2=0",
    "fiveaxis_parse_remap_3=0",
    "fiveaxis_parsed_remap_count=3",
    "fiveaxis_remaps_ready=1",
    "fiveaxis_file_open=0",
    "fiveaxis_file_read_count=120",
    "fiveaxis_file_execute_count=120",
    "fiveaxis_file_finish_count=3",
    "fiveaxis_file_final_rc=1",
    "fiveaxis_file_reached_exit=1",
    "fiveaxis_hal_switchkins: rc=0 found=1 value=0",
    "fiveaxis_linuxcnc_remap_file_execute=1",
  ].join("\n"),
);
verifyExpectedOutput(
  "fiveaxis_xyzac_switchkins_test_3_wasm",
  interp.runFiveAxisRemapFile(
    `${fiveAxisTrtDir}/demos/xyzac_switchkins_test_3.ngc`,
    `${fiveAxisTrtDir}/xyzac-trt.ini`,
  ),
  [
    "fiveaxis_ini_open=1",
    "fiveaxis_tool_table_load=0",
    "fiveaxis_parse_remap_1=0",
    "fiveaxis_parse_remap_2=0",
    "fiveaxis_parse_remap_3=0",
    "fiveaxis_parsed_remap_count=3",
    "fiveaxis_remaps_ready=1",
    "fiveaxis_file_open=0",
    "fiveaxis_file_read_count=86",
    "fiveaxis_file_execute_count=86",
    "fiveaxis_file_finish_count=3",
    "fiveaxis_file_final_rc=1",
    "fiveaxis_file_reached_exit=1",
    "fiveaxis_hal_switchkins: rc=0 found=1 value=0",
    "fiveaxis_linuxcnc_remap_file_execute=1",
  ].join("\n"),
);

verifyExpectedOutput(
  "fiveaxis_boat_xyzac_wasm",
  interp.runFiveAxisRemapFile(
    `${fiveAxisTrtDir}/demos/boat-xyzac.ngc`,
    `${fiveAxisTrtDir}/xyzac-trt.ini`,
  ),
  [
    "fiveaxis_ini_open=1",
    "fiveaxis_tool_table_load=0",
    "fiveaxis_parse_remap_1=0",
    "fiveaxis_parse_remap_2=0",
    "fiveaxis_parse_remap_3=0",
    "fiveaxis_file_open=0",
    "fiveaxis_file_read_count=1927",
    "fiveaxis_file_execute_count=1927",
    "fiveaxis_file_finish_count=3",
    "fiveaxis_file_final_rc=1",
    "fiveaxis_file_reached_exit=1",
    "fiveaxis_hal_switchkins: rc=0 found=1 value=0",
    "fiveaxis_linuxcnc_remap_file_execute=1",
  ].join("\n"),
);
verifyExpectedOutput(
  "fiveaxis_boat_xyzbc_wasm",
  interp.runFiveAxisRemapFile(
    `${fiveAxisTrtDir}/demos/boat-xyzbc.ngc`,
    `${fiveAxisTrtDir}/xyzbc-trt.ini`,
  ),
  [
    "fiveaxis_ini_open=1",
    "fiveaxis_tool_table_load=0",
    "fiveaxis_parse_remap_1=0",
    "fiveaxis_parse_remap_2=0",
    "fiveaxis_parse_remap_3=0",
    "fiveaxis_file_open=0",
    "fiveaxis_file_read_count=1913",
    "fiveaxis_file_execute_count=1913",
    "fiveaxis_file_finish_count=3",
    "fiveaxis_file_final_rc=1",
    "fiveaxis_file_reached_exit=1",
    "fiveaxis_hal_switchkins: rc=0 found=1 value=0",
    "fiveaxis_linuxcnc_remap_file_execute=1",
  ].join("\n"),
);
verifyExpectedOutput(
  "fiveaxis_impeller_7bl_xyzac_wasm",
  interp.runFiveAxisRemapFile(
    `${fiveAxisTrtDir}/demos/impeller-7bl-xyzac.ngc`,
    `${fiveAxisTrtDir}/xyzac-trt.ini`,
  ),
  [
    "fiveaxis_ini_open=1",
    "fiveaxis_tool_table_load=0",
    "fiveaxis_parse_remap_1=0",
    "fiveaxis_parse_remap_2=0",
    "fiveaxis_parse_remap_3=0",
    "fiveaxis_file_open=0",
    "fiveaxis_file_read_count=4558",
    "fiveaxis_file_execute_count=4558",
    "fiveaxis_file_finish_count=2",
    "fiveaxis_file_final_rc=1",
    "fiveaxis_file_reached_exit=1",
    "fiveaxis_hal_switchkins: rc=0 found=1 value=0",
    "fiveaxis_linuxcnc_remap_file_execute=1",
  ].join("\n"),
);

const fiveAxisTdrDir = writeFiveAxisTdrMachineFiles();
verifyExpectedOutput(
  "fiveaxis_xyzab_tdr_demo_wasm",
  interp.runFiveAxisRemapFile(
    `${fiveAxisTdrDir}/demos/xyzab-tdr-demo.ngc`,
    `${fiveAxisTdrDir}/xyzab-tdr.ini`,
  ),
  [
    "fiveaxis_ini_open=1",
    "fiveaxis_tool_table_load=0",
    "fiveaxis_parse_remap_1=0",
    "fiveaxis_parse_remap_2=0",
    "fiveaxis_parsed_remap_count=2",
    "fiveaxis_remaps_ready=1",
    "fiveaxis_file_open=0",
    "fiveaxis_file_read_count=97",
    "fiveaxis_file_execute_count=97",
    "fiveaxis_file_finish_count=3",
    "fiveaxis_file_final_rc=1",
    "fiveaxis_file_reached_exit=1",
    "fiveaxis_hal_switchkins: rc=0 found=1 value=1",
    "fiveaxis_linuxcnc_remap_file_execute=1",
  ].join("\n"),
);

const fiveAxisBridgeMillDir = writeFiveAxisBridgeMillMachineFiles();
verifyExpectedOutput(
  "fiveaxis_bridgemill_5axisgui_wasm",
  interp.runFiveAxisRemapFile(
    `${fiveAxisBridgeMillDir}/5axisgui.ngc`,
    `${fiveAxisBridgeMillDir}/5axis.ini`,
  ),
  [
    "fiveaxis_ini_open=1",
    "fiveaxis_tool_table_load=0",
    "fiveaxis_parse_remap_1=0",
    "fiveaxis_parse_remap_2=0",
    "fiveaxis_parse_remap_3=0",
    "fiveaxis_parsed_remap_count=3",
    "fiveaxis_remaps_ready=1",
    "fiveaxis_file_open=0",
    "fiveaxis_file_read_count=2197",
    "fiveaxis_file_execute_count=2197",
    "fiveaxis_file_finish_count=137",
    "fiveaxis_file_final_rc=1",
    "fiveaxis_file_reached_exit=1",
    "fiveaxis_hal_switchkins: rc=0 found=1 value=0",
    "fiveaxis_linuxcnc_remap_file_execute=1",
  ].join("\n"),
);

const duplicateOwordFiles = [
  "test.ini",
  "test.ngc",
  "rm207.ngc",
  "rm208.ngc",
];
const duplicateOwordDir = writeRemapRegressionFiles("duplicate-o-word", duplicateOwordFiles);
assertRemapRegressionCoverage("duplicate-o-word", duplicateOwordFiles);
assertRemapRegressionFilesStaging("duplicate-o-word", duplicateOwordFiles, duplicateOwordDir);
verifyExpectedOutput(
  "duplicate_oword_remap_wasm",
  interp.runRemapFile(
    `${duplicateOwordDir}/test.ngc`,
    `${duplicateOwordDir}/test.ini`,
  ),
  [
    "remap_ini_open=1",
    "remap_subroutine_path_count=1",
    "remap_parse_remap_1=0",
    "remap_parse_remap_2=0",
    "remap_parsed_remap_count=2",
    "remap_remaps_ready=1",
    "remap_file_open=0",
    "remap_file_read_count=31",
    "remap_file_execute_count=31",
    "remap_file_finish_count=0",
    "remap_file_final_rc=3",
    "remap_file_reached_endfile=1",
    "remap_canon_event=MESSAGE:  executing m207:  run remapped m208 before o<problem>",
    "remap_canon_event=MESSAGE:  rm207 running remapped m208",
    "remap_canon_event=MESSAGE:  rm208 starting and done",
    "remap_canon_event=FINISH",
    "remap_linuxcnc_file_execute=1",
  ].join("\n"),
);

const failArgs0Files = [
  "test.ini",
  "test.ngc",
  "rm400.ngc",
];
const failArgs0Dir = writeRemapRegressionFiles("fail/args.0", failArgs0Files);
assertRemapRegressionCoverage("fail/args.0", failArgs0Files);
assertRemapRegressionFilesStaging("fail/args.0", failArgs0Files, failArgs0Dir);
verifyExpectedOutput(
  "fail_args_0_remap_wasm",
  interp.runRemapFile(
    `${failArgs0Dir}/test.ngc`,
    `${failArgs0Dir}/test.ini`,
  ),
  [
    "remap_ini_open=1",
    "remap_subroutine_path_count=1",
    "remap_parse_remap_1=0",
    "remap_parsed_remap_count=1",
    "remap_remaps_ready=1",
    "remap_file_open=0",
    "remap_file_saw_error=0",
    "remap_canon_event=MESSAGE:  M400 call_level= 1.000000 remap_level=1.000000",
    "remap_canon_event=MESSAGE:  P word set: 47.110000",
    "remap_canon_event=MESSAGE:  Q word set: 8.150000",
    "remap_canon_event=PROGRAM_END",
    "remap_linuxcnc_file_execute=1",
  ].join("\n"),
);

const failArgs1Files = [
  "test.ini",
  "test.ngc",
  "rm400.ngc",
];
const failArgs1Dir = writeRemapRegressionFiles("fail/args.1", failArgs1Files);
assertRemapRegressionCoverage("fail/args.1", failArgs1Files);
assertRemapRegressionFilesStaging("fail/args.1", failArgs1Files, failArgs1Dir);
verifyExpectedOutput(
  "fail_args_1_remap_wasm",
  interp.runRemapFileContinueOnError(
    `${failArgs1Dir}/test.ngc`,
    `${failArgs1Dir}/test.ini`,
  ),
  [
    "remap_ini_open=1",
    "remap_subroutine_path_count=1",
    "remap_parse_remap_1=0",
    "remap_file_execute_1=5",
    "remap_file_error_text=user-defined M400: missing: Q",
    "remap_file_saw_error=1",
    "remap_canon_event=PROGRAM_END",
    "remap_linuxcnc_file_execute=1",
  ].join("\n"),
);

const failArgs2Files = [
  "test.ini",
  "test.ngc",
  "rm400.ngc",
];
const failArgs2Dir = writeRemapRegressionFiles("fail/args.2", failArgs2Files);
assertRemapRegressionCoverage("fail/args.2", failArgs2Files);
assertRemapRegressionFilesStaging("fail/args.2", failArgs2Files, failArgs2Dir);
verifyExpectedOutput(
  "fail_args_2_remap_wasm",
  interp.runRemapFileContinueOnError(
    `${failArgs2Dir}/test.ngc`,
    `${failArgs2Dir}/test.ini`,
  ),
  [
    "remap_ini_open=1",
    "remap_subroutine_path_count=1",
    "remap_parse_remap_1=0",
    "remap_file_execute_1=5",
    "remap_file_error_text=user-defined M400: missing: P,Q",
    "remap_file_saw_error=1",
    "remap_canon_event=PROGRAM_END",
    "remap_linuxcnc_file_execute=1",
  ].join("\n"),
);

const failBodyNgcFiles = [
  "test.ini",
  "test.ngc",
  "rm400.ngc",
];
const failBodyNgcDir = writeRemapRegressionFiles("fail/body-ngc", failBodyNgcFiles);
assertRemapRegressionCoverage("fail/body-ngc", failBodyNgcFiles);
assertRemapRegressionFilesStaging("fail/body-ngc", failBodyNgcFiles, failBodyNgcDir);
verifyExpectedOutput(
  "fail_body_ngc_remap_wasm",
  interp.runRemapFileContinueOnError(
    `${failBodyNgcDir}/test.ngc`,
    `${failBodyNgcDir}/test.ini`,
  ),
  [
    "remap_ini_open=1",
    "remap_subroutine_path_count=1",
    "remap_parse_remap_1=0",
    "remap_file_read_5=5",
    "remap_file_error_text=Attempt to divide by zero",
    "remap_file_saw_error=1",
    "remap_canon_event=MESSAGE:  before M400: call_level= 0.000000 remap_level=0.000000",
    "remap_canon_event=MESSAGE:  in rm400: call_level= 1.000000 remap_level=1.000000",
    "remap_canon_event=MESSAGE:  after failed M400: call_level= 0.000000 remap_level=0.000000",
    "remap_canon_event=PROGRAM_END",
    "remap_linuxcnc_file_execute=1",
  ].join("\n"),
);

const m30InteractionFiles = [
  "test.ini",
  "test.ngc",
  "rm400.ngc",
];
const m30InteractionDir = writeRemapRegressionFiles("m30-interaction", m30InteractionFiles);
assertRemapRegressionCoverage("m30-interaction", m30InteractionFiles);
assertRemapRegressionFilesStaging("m30-interaction", m30InteractionFiles, m30InteractionDir);
verifyExpectedOutput(
  "m30_interaction_remap_wasm",
  interp.runRemapFile(
    `${m30InteractionDir}/test.ngc`,
    `${m30InteractionDir}/test.ini`,
  ),
  [
    "remap_ini_open=1",
    "remap_subroutine_path_count=1",
    "remap_parse_remap_1=0",
    "remap_parsed_remap_count=1",
    "remap_remaps_ready=1",
    "remap_file_open=0",
    "remap_file_read_count=4",
    "remap_file_execute_count=4",
    "remap_file_finish_count=0",
    "remap_file_final_rc=1",
    "remap_file_reached_exit=1",
    "remap_canon_event=MESSAGE: m400 call_level=1.000000 remap_level=1.000000 line=2.000000",
    "remap_canon_event=PROGRAM_END",
    "remap_linuxcnc_file_execute=1",
  ].join("\n"),
);

const nestedRemapsOwordFiles = [
  "test.ini",
  "test.ngc",
  "rm400.ngc",
  "rm401.ngc",
  "rm402.ngc",
  "rm403.ngc",
];
const nestedRemapsOwordUnstagedFiles = [
  "testsub.ngc",
];
const nestedRemapsOwordDir = writeRemapRegressionFiles(
  "nested-remaps-oword",
  nestedRemapsOwordFiles,
);
assertRemapRegressionCoverage(
  "nested-remaps-oword",
  nestedRemapsOwordFiles,
  nestedRemapsOwordUnstagedFiles,
);
assertRemapRegressionFilesStaging(
  "nested-remaps-oword",
  nestedRemapsOwordFiles,
  nestedRemapsOwordDir,
);
verifyExpectedOutput(
  "nested_remaps_oword_remap_wasm",
  interp.runRemapFile(
    `${nestedRemapsOwordDir}/test.ngc`,
    `${nestedRemapsOwordDir}/test.ini`,
  ),
  [
    "remap_ini_open=1",
    "remap_subroutine_path_count=1",
    "remap_parse_remap_1=0",
    "remap_parse_remap_2=0",
    "remap_parse_remap_3=0",
    "remap_parse_remap_4=0",
    "remap_parsed_remap_count=4",
    "remap_remaps_ready=1",
    "remap_file_open=0",
    "remap_file_read_count=21",
    "remap_file_execute_count=21",
    "remap_file_finish_count=0",
    "remap_file_final_rc=3",
    "remap_file_reached_endfile=1",
    "remap_canon_event=MESSAGE: main call_level=0.000000 remap_level=0.000000 line=2.000000",
    "remap_canon_event=MESSAGE: m400 handler pre call_level=1.000000 remap_level=1.000000 line=2.000000",
    "remap_canon_event=MESSAGE: m401 handler pre call_level=2.000000 remap_level=2.000000 line=2.000000",
    "remap_canon_event=MESSAGE: m402 handler pre call_level=3.000000 remap_level=3.000000 line=2.000000",
    "remap_canon_event=MESSAGE: m403 handler pre call_level=4.000000 remap_level=4.000000 line=2.000000",
    "remap_canon_event=MESSAGE: m400 handler post call_level=1.000000 remap_level=1.000000 line=4.000000",
    "remap_canon_event=FINISH",
    "remap_linuxcnc_file_execute=1",
  ].join("\n"),
);

const posargs0Files = [
  "test.ini",
  "test.ngc",
  "rg881.ngc",
];
const posargs0Dir = writeRemapRegressionFiles("posargs.0", posargs0Files);
assertRemapRegressionCoverage("posargs.0", posargs0Files);
assertRemapRegressionFilesStaging("posargs.0", posargs0Files, posargs0Dir);
verifyExpectedOutput(
  "posargs_0_remap_wasm",
  interp.runRemapFile(
    `${posargs0Dir}/test.ngc`,
    `${posargs0Dir}/test.ini`,
  ),
  [
    "remap_ini_open=1",
    "remap_subroutine_path_count=1",
    "remap_parse_remap_1=0",
    "remap_parsed_remap_count=1",
    "remap_remaps_ready=1",
    "remap_file_open=0",
    "remap_file_read_count=19",
    "remap_file_execute_count=19",
    "remap_file_finish_count=0",
    "remap_file_final_rc=1",
    "remap_file_reached_exit=1",
    "remap_canon_event=MESSAGE:  in rg881: n_args=3.000000 [1.000000] [2.000000] [3.000000] [0.000000] [0.000000]",
    "remap_canon_event=MESSAGE:  in rg881: n_args=4.000000 [1.000000] [2.000000] [3.000000] [4.000000] [0.000000]",
    "remap_canon_event=MESSAGE:  in rg881: n_args=4.000000 [1.000000] [2.000000] [3.000000] [5.000000] [0.000000]",
    "remap_canon_event=MESSAGE:  in rg881: n_args=5.000000 [1.000000] [2.000000] [3.000000] [4.000000] [5.000000]",
    "remap_canon_event=PROGRAM_END",
    "remap_linuxcnc_file_execute=1",
  ].join("\n"),
);

const sequencingFiles = [
  "test.ini",
  "test.ngc",
  "rg881.ngc",
  "rm405.ngc",
  "rm406.ngc",
  "rm407.ngc",
  "rm408.ngc",
  "rm409.ngc",
  "rm410.ngc",
];
const sequencingDir = writeRemapRegressionFiles("sequencing", sequencingFiles);
assertRemapRegressionCoverage("sequencing", sequencingFiles);
assertRemapRegressionFilesStaging("sequencing", sequencingFiles, sequencingDir);
verifyExpectedOutput(
  "sequencing_remap_wasm",
  interp.runRemapFile(
    `${sequencingDir}/test.ngc`,
    `${sequencingDir}/test.ini`,
  ),
  [
    "remap_ini_open=1",
    "remap_subroutine_path_count=1",
    "remap_parse_remap_1=0",
    "remap_parse_remap_2=0",
    "remap_parse_remap_3=0",
    "remap_parse_remap_4=0",
    "remap_parse_remap_5=0",
    "remap_parse_remap_6=0",
    "remap_parse_remap_7=0",
    "remap_parsed_remap_count=7",
    "remap_remaps_ready=1",
    "remap_file_open=0",
    "remap_file_read_count=10084",
    "remap_file_execute_count=10084",
    "remap_file_final_rc=1",
    "remap_file_reached_exit=1",
    "remap_canon_event=MESSAGE:  seq=1.000000",
    "remap_canon_event=MESSAGE:  seq=5.000000",
    "remap_canon_event=MESSAGE:  seq=6.000000",
    "remap_canon_event=MESSAGE:  seq=7.000000",
    "remap_canon_event=MESSAGE:  seq=8.000000 - reset to 1",
    "remap_canon_event=MESSAGE:  seq=8.000000",
    "remap_canon_event=MESSAGE:  seq=9.000000",
    "remap_canon_event=MESSAGE:  seq=10.000000 - reset to 1",
    "remap_canon_event=PROGRAM_END",
    "remap_linuxcnc_file_execute=1",
  ].join("\n"),
);

const remapIoFiles = [
  "test-ngc.ini",
  "io_input_m66.ngc",
  "io_output_m62.ngc",
  "io_output_m63.ngc",
  "io_output_m64.ngc",
  "io_output_m65.ngc",
  "io_output_m67.ngc",
  "io_output_m68.ngc",
];
const remapIoDir = writeRemapRegressionFiles("remap-io", remapIoFiles);
assertRemapRegressionCoverage("remap-io", remapIoFiles);
assertRemapRegressionFilesStaging("remap-io", remapIoFiles, remapIoDir);
const remapIoGeneratedToolTablePath = `${remapIoDir}/simpockets.tbl`;
assertRemapRegressionGeneratedFileStaging("remap-io", "simpockets.tbl", remapIoGeneratedToolTablePath);
interp.writeTextFile(remapIoGeneratedToolTablePath, "T2 P2 Z0 ;remap-io tool\n");
verifyExpectedOutput(
  "remap_io_ngc_mdi_wasm",
  interp.runRemapIoMdiSequence(`${remapIoDir}/test-ngc.ini`),
  [
    "remap_ini_open=1",
    "remap_subroutine_path_count=1",
    "remap_parse_remap_1=0",
    "remap_parse_remap_7=0",
    "remap_parsed_remap_count=7",
    "remap_remaps_ready=1",
    "remap_mdi_M62 P1_execute_0=0",
    "remap_mdi_M66 P1_execute_0=2",
    "remap_mdi_M66 P1_execute_1=0",
    "remap_mdi_M66 E1 L0_execute_0=2",
    "remap_mdi_M66 E1 L0_execute_1=0",
    "remap_mdi_parameter_5399=42.13",
    "remap_mdi_parameter_5399=-13.42",
    "remap_mdi_canon_event=SET_MOTION_OUTPUT_BIT index=0",
    "remap_mdi_canon_event=CLEAR_MOTION_OUTPUT_BIT index=0",
    "remap_mdi_canon_event=SET_AUX_OUTPUT_BIT index=0",
    "remap_mdi_canon_event=CLEAR_AUX_OUTPUT_BIT index=0",
    "remap_mdi_canon_event=WAIT index=0 input_type=1 wait_type=0 timeout=0",
    "remap_mdi_canon_event=WAIT index=0 input_type=0 wait_type=0 timeout=0",
    "remap_mdi_canon_event=SET_MOTION_OUTPUT_VALUE index=0 value=42.13",
    "remap_mdi_canon_event=SET_AUX_OUTPUT_VALUE index=0 value=-13.42",
    "remap_io_ngc_linuxcnc_mdi_sequence=1",
  ].join("\n"),
);

const doWhileBreakNgcFiles = [
  "bug.ngc",
  "test.ngc",
];
const doWhileBreakDir = writeInterpRegressionFiles("do-while-break", doWhileBreakNgcFiles);
assertInterpRegressionFilesCoverage("do-while-break", doWhileBreakNgcFiles);
assertInterpRegressionFilesStaging("do-while-break", doWhileBreakNgcFiles, doWhileBreakDir);
const doWhileBreakPath = `${doWhileBreakDir}/test.ngc`;
verifyExpectedOutput(
  "interp_do_while_break_wasm",
  interp.runFile(doWhileBreakPath),
  [
    "file_open=0",
    "file_read_count=30",
    "file_execute_count=30",
    "canon_event=MESSAGE: must-execute-outer",
    "canon_event=MESSAGE: must-execute-nested",
    "canon_event=MESSAGE: must-execute-inner",
    "canon_event=MESSAGE: post-inner-while",
    "canon_event=MESSAGE: post-nested-while",
    "canon_event=MESSAGE: post-outer-while",
    "canon_event=PROGRAM_END",
    "absent=canon_event=MESSAGE: do-not-execute",
  ].join("\n"),
);

const doWhileBreakBugPath = `${doWhileBreakDir}/bug.ngc`;
verifyExpectedOutput(
  "interp_do_while_break_bug_wasm",
  interp.runFile(doWhileBreakBugPath),
  [
    "file_open=0",
    "file_read_count=7",
    "file_execute_count=7",
    "file_saw_error=0",
    "canon_event=PROGRAM_END",
    "absent=@end of do-while-loop",
    "absent=file_saw_error=1",
  ].join("\n"),
);

const owordBug315Path = writeInterpRegressionFile("oword-bug315", "test.ngc");
const owordBug315NgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  owordBug315NgcFiles,
  interpRegressionNgcFilesRecursive("oword-bug315"),
  "interp oword-bug315 fixture coverage drift",
);
assertInterpRegressionFileStaging("oword-bug315", "test.ngc", owordBug315Path);
verifyExpectedOutput(
  "interp_oword_bug315_wasm",
  interp.runFile(owordBug315Path),
  [
    "file_open=0",
    "file_read_count=23",
    "file_execute_count=23",
    "canon_event=MESSAGE: running sub",
    "canon_event=MESSAGE: breaking out of sub",
    "canon_event=MESSAGE: done",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const owordBug315P2Path = writeInterpRegressionFile("oword-bug315-p2", "test.ngc");
const owordBug315P2NgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  owordBug315P2NgcFiles,
  interpRegressionNgcFilesRecursive("oword-bug315-p2"),
  "interp oword-bug315-p2 fixture coverage drift",
);
assertInterpRegressionFileStaging("oword-bug315-p2", "test.ngc", owordBug315P2Path);
verifyExpectedOutput(
  "interp_oword_bug315_p2_wasm",
  interp.runFile(owordBug315P2Path),
  [
    "file_open=0",
    "file_read_count=26",
    "file_execute_count=26",
    "canon_event=STRAIGHT_TRAVERSE line=7 x=2 y=2 z=2",
    "canon_event=MESSAGE: executing this one",
    "canon_event=PROGRAM_END",
    "absent=canon_event=MESSAGE: not executing this one",
  ].join("\n"),
);

const existsPath = writeInterpRegressionFile("exists", "test.ngc");
const existsNgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  existsNgcFiles,
  interpRegressionNgcFilesRecursive("exists"),
  "interp exists fixture coverage drift",
);
assertInterpRegressionFileStaging("exists", "test.ngc", existsPath);
verifyExpectedOutput(
  "interp_exists_wasm",
  interp.runFile(existsPath),
  [
    "file_open=0",
    "file_read_count=7",
    "file_execute_count=7",
    "canon_event=STRAIGHT_TRAVERSE line=2 x=1 y=0 z=1",
    "canon_event=COMMENT: comment",
    "canon_event=STRAIGHT_TRAVERSE line=6 x=1 y=0 z=0",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const returnValuePath = writeInterpRegressionFile("return-value", "test.ngc");
const returnValueNgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  returnValueNgcFiles,
  interpRegressionNgcFilesRecursive("return-value"),
  "interp return-value fixture coverage drift",
);
assertInterpRegressionFileStaging("return-value", "test.ngc", returnValuePath);
verifyExpectedOutput(
  "interp_return_value_wasm",
  interp.runFile(returnValuePath),
  [
    "file_open=0",
    "file_read_count=75",
    "file_execute_count=75",
    "canon_event=MESSAGE: line 6.000000: _value: - expected 0.000000, got 0.000000",
    "canon_event=MESSAGE: line 28.000000: call with arg1=2.000000 expect 246.000000, got 246.000000",
    "canon_event=MESSAGE: line 37.000000: call with arg1=-1.000000 expect 0.000000, got 0.000000",
    "canon_event=MESSAGE: line 47.000000: call with arg1=0.000000 expect 4712.000000, got 4712.000000",
    "canon_event=MESSAGE: line 53.000000: _value=4712.000000 - expected 4712.000000",
    "canon_event=PROGRAM_END",
    "absent=fail:",
  ].join("\n"),
);

const subsFollowMainPath = writeInterpRegressionFile("subs-follow-main", "test.ngc");
const subsFollowMainNgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  subsFollowMainNgcFiles,
  interpRegressionNgcFilesRecursive("subs-follow-main"),
  "interp subs-follow-main fixture coverage drift",
);
assertInterpRegressionFileStaging("subs-follow-main", "test.ngc", subsFollowMainPath);
verifyExpectedOutput(
  "interp_subs_follow_main_wasm",
  interp.runFile(subsFollowMainPath),
  [
    "file_open=0",
    "file_read_count=9",
    "file_execute_count=9",
    "canon_event=COMMENT: Subs may follow main program ",
    "canon_event=PALLET_SHUTTLE",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const fractionalLinenumbersPath = writeInterpRegressionFile(
  "fractional-linenumbers",
  "test.ngc",
);
const fractionalLinenumbersNgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  fractionalLinenumbersNgcFiles,
  interpRegressionNgcFilesRecursive("fractional-linenumbers"),
  "interp fractional-linenumbers fixture coverage drift",
);
assertInterpRegressionFileStaging("fractional-linenumbers", "test.ngc", fractionalLinenumbersPath);
verifyExpectedOutput(
  "interp_fractional_linenumbers_wasm",
  interp.runFile(fractionalLinenumbersPath),
  [
    "file_open=0",
    "file_read_count=4",
    "file_execute_count=4",
    "canon_event=SET_SPINDLE_SPEED spindle=0 speed=300",
    "canon_event=SET_SPINDLE_SPEED spindle=0 speed=600",
    "canon_event=SET_SPINDLE_SPEED spindle=0 speed=1200",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const crazyPathsPath = writeInterpRegressionFile("crazy-paths", "test.ngc");
const crazyPathsNgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  crazyPathsNgcFiles,
  interpRegressionNgcFilesRecursive("crazy-paths"),
  "interp crazy-paths fixture coverage drift",
);
assertInterpRegressionFileStaging("crazy-paths", "test.ngc", crazyPathsPath);
verifyExpectedOutput(
  "interp_crazy_paths_wasm",
  interp.runFile(crazyPathsPath),
  [
    "file_open=0",
    "file_read_count=1526",
    "file_execute_count=1526",
    "file_saw_error=0",
    "canon_event=COMMENT: interpreter: cutter radius compensation on right",
    "canon_event=COMMENT: interpreter: cutter radius compensation on left",
    "canon_event=ARC_FEED line=8 first_end=-99.2047 second_end=-102.892 first_axis=-98.9043 second_axis=-102.097 rotation=-1 axis_end_point=0",
    "canon_event=ARC_FEED line=103 first_end=-40.3437 second_end=-103.278 first_axis=-45.0196 second_axis=-102.442 rotation=-1 axis_end_point=0",
    "canon_event=STRAIGHT_FEED line=260 x=3.58919 y=30.3694 z=0",
    "canon_event=ARC_FEED line=445 first_end=101.539 second_end=44.5843 first_axis=100.896 second_axis=46.212 rotation=1 axis_end_point=0",
    "canon_event=STRAIGHT_FEED line=469 x=98.8154 y=102.176 z=0",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const camNisleyFiles = [
  "cam.ngc",
  "test.tbl",
];
const camNisleyDir = writeInterpRegressionFiles("cam-nisley", camNisleyFiles);
assertInterpRegressionFilesCoverage("cam-nisley", camNisleyFiles);
assertInterpRegressionFilesStaging("cam-nisley", camNisleyFiles, camNisleyDir);
interp.writeTextFile(
  `${camNisleyDir}/test.ini`,
  [
    "[EMCIO]",
    "TOOL_TABLE = test.tbl",
    "[TRAJ]",
    "COORDINATES = X Y Z A B C U V W",
    "",
  ].join("\n"),
);
verifyExpectedOutput(
  "interp_cam_nisley_wasm",
  interp.runFileWithIni(`${camNisleyDir}/cam.ngc`, `${camNisleyDir}/test.ini`),
  [
    "file_open=0",
    "file_read_count=1584",
    "file_execute_count=1584",
    "file_saw_error=0",
    "canon_event=COMMENT: Ed Nisley - Nov 2006 - Mar 2007",
    "canon_event=SELECT_TOOL tool=1",
    "canon_event=CHANGE_TOOL",
    "canon_event=START_SPINDLE_CLOCKWISE spindle=0",
    "canon_event=COMMENT: interpreter: cutter radius compensation on right",
    "canon_event=ARC_FEED line=223 first_end=1.91351e-18 second_end=-15.1438",
    "canon_event=STRAIGHT_TRAVERSE line=241 x=75 y=0 z=75",
    "canon_event=MESSAGE: Done!",
    "canon_event=PROGRAM_END",
    "absent=file_error_text=Requested tool 1 not found in the tool table",
  ].join("\n"),
);

const camNisleyBareInterp = await createLinuxCncInterpSdk({
  wasmBinary: readFileSync(wasmPath),
  printErr(message) {
    console.error(message);
  },
});
const camNisleyBarePath = "/work/interp/cam-nisley-bare/cam.ngc";
assertInterpRegressionFileStaging("cam-nisley-bare", "cam.ngc", camNisleyBarePath);
writeVendorTextFile(
  resolve(rootDir, "vendor/linuxcnc/tests/interp/cam-nisley/cam.ngc"),
  camNisleyBarePath,
  camNisleyBareInterp,
);
verifyExpectedOutput(
  "interp_cam_nisley_bare_wasm",
  camNisleyBareInterp.runFile(camNisleyBarePath),
  [
    "file_open=0",
    "file_read_count=57",
    "file_execute_count=57",
    "file_saw_error=1",
    "file_error_text=Requested tool 1 not found in the tool table",
  ].join("\n"),
);

const namedparamBug424Path = writeInterpRegressionFile("namedparam-bug424", "test.ngc");
const namedparamBug424NgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  namedparamBug424NgcFiles,
  interpRegressionNgcFilesRecursive("namedparam-bug424"),
  "interp namedparam-bug424 fixture coverage drift",
);
assertInterpRegressionFileStaging("namedparam-bug424", "test.ngc", namedparamBug424Path);
verifyExpectedOutput(
  "interp_namedparam_bug424_wasm",
  interp.runFile(namedparamBug424Path),
  [
    "file_open=0",
    "file_read_count=6",
    "file_execute_count=6",
    "setup.current_x=2",
    "setup.current_y=3",
    "setup.current_z=4",
    "canon_event=USE_LENGTH_UNITS units=1",
    "canon_event=STRAIGHT_TRAVERSE line=5 x=2 y=3 z=4",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const flowsnakePath = writeInterpRegressionFile("flowsnake", "flowsnake.ngc");
const flowsnakeNgcFiles = [
  "flowsnake.ngc",
];
assert.deepEqual(
  flowsnakeNgcFiles,
  interpRegressionNgcFilesRecursive("flowsnake"),
  "interp flowsnake fixture coverage drift",
);
assertInterpRegressionFileStaging("flowsnake", "flowsnake.ngc", flowsnakePath);
verifyExpectedOutput(
  "interp_flowsnake_wasm",
  interp.runFile(flowsnakePath),
  [
    "file_open=0",
    "file_read_count=6414",
    "file_execute_count=6414",
    "file_saw_error=0",
    "canon_event=COMMENT: Program to mill a flowsnake",
    "canon_event=START_SPINDLE_CLOCKWISE spindle=0",
    "canon_event=STRAIGHT_TRAVERSE line=33 x=0.25 y=1 z=1",
    "canon_event=STRAIGHT_FEED line=13 x=3.75 y=1 z=0",
    "canon_event=STRAIGHT_FEED line=13 x=2 y=3.95 z=0",
    "canon_event=STRAIGHT_FEED line=13 x=0.25 y=1 z=0",
    "canon_event=STOP_SPINDLE_TURNING spindle=0",
    "setup.current_x=0.25",
    "setup.current_y=1",
    "setup.current_z=1",
  ].join("\n"),
);

const insideCornersPath = writeInterpRegressionFile("inside-corners", "test.ngc");
const insideCornersNgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  insideCornersNgcFiles,
  interpRegressionNgcFilesRecursive("inside-corners"),
  "interp inside-corners fixture coverage drift",
);
assertInterpRegressionFileStaging("inside-corners", "test.ngc", insideCornersPath);
verifyExpectedOutput(
  "interp_inside_corners_wasm",
  interp.runFile(insideCornersPath),
  [
    "file_open=0",
    "file_read_count=397",
    "file_execute_count=397",
    "file_saw_error=0",
    "canon_event=PROGRAM_STOP",
    "canon_event=DWELL seconds=3",
    "canon_event=SELECT_PLANE plane=1",
    "canon_event=SELECT_PLANE plane=3",
    "canon_event=COMMENT: interpreter: cutter radius compensation on left",
    "canon_event=COMMENT: interpreter: cutter radius compensation on right",
    "canon_event=ARC_FEED line=16 first_end=1.2281 second_end=1.3456 first_axis=0.628 second_axis=1.0458 rotation=1 axis_end_point=-0.1",
    "canon_event=STRAIGHT_FEED line=14 x=0.701154 y=0.162499 z=-0.1",
    "canon_event=ARC_FEED line=74 first_end=0.298564 second_end=1.82077 first_axis=0.3459 second_axis=1.7626 rotation=1 axis_end_point=0",
    "canon_event=STRAIGHT_FEED line=107 x=0 y=0 z=1",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const inverseTimeWithCompPath = writeInterpRegressionFile(
  "inverse-time-with-comp",
  "inverse.ngc",
);
const inverseTimeWithCompNgcFiles = [
  "inverse.ngc",
];
assert.deepEqual(
  inverseTimeWithCompNgcFiles,
  interpRegressionNgcFilesRecursive("inverse-time-with-comp"),
  "interp inverse-time-with-comp fixture coverage drift",
);
assertInterpRegressionFileStaging("inverse-time-with-comp", "inverse.ngc", inverseTimeWithCompPath);
verifyExpectedOutput(
  "interp_inverse_time_with_comp_wasm",
  interp.runFile(inverseTimeWithCompPath),
  [
    "file_open=0",
    "file_read_count=68",
    "file_execute_count=68",
    "file_saw_error=0",
    "canon_event=COMMENT: interpreter: cutter radius compensation on right",
    "canon_event=COMMENT: interpreter: cutter radius compensation on left",
    "canon_event=COMMENT: interpreter: feed mode set to inverse time",
    "canon_event=COMMENT: interpreter: feed mode set to units per minute",
    "canon_event=SET_FEED_RATE rate=30",
    "canon_event=SET_FEED_RATE rate=20",
    "canon_event=SET_FEED_RATE rate=40",
    "canon_event=SET_FEED_RATE rate=33",
    "canon_event=SET_FEED_RATE rate=10",
    "canon_event=SET_FEED_RATE rate=25",
    "canon_event=STRAIGHT_FEED line=5 x=1 y=0 z=0",
    "canon_event=ARC_FEED line=6 first_end=1.2 second_end=0",
    "canon_event=STRAIGHT_FEED line=13 x=0.2 y=3.82918 z=0",
    "canon_event=ARC_FEED line=14 first_end=1.22465e-17 second_end=5.2",
    "canon_event=ARC_FEED line=14 first_end=1.22465e-17 second_end=4.2",
    "canon_event=ARC_FEED line=14 first_end=1.22465e-17 second_end=4.8",
    "canon_event=COMMENT: interpreter: cutter radius compensation off",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const ccompLatheCompDir = writeCcompRegressionFiles("lathe-comp");
assertCcompRegressionCoverage("lathe-comp");
assertCcompRegressionFilesStaging("lathe-comp", ccompLatheCompDir);
verifyExpectedOutput(
  "interp_ccomp_lathe_comp_wasm",
  interp.runFileWithIni(`${ccompLatheCompDir}/test.ngc`, `${ccompLatheCompDir}/test.ini`),
  [
    "file_open=0",
    "file_read_count=49",
    "file_execute_count=49",
    "file_saw_error=0",
    "canon_event=SELECT_PLANE plane=3",
    "canon_event=SELECT_TOOL tool=2",
    "canon_event=COMMENT: interpreter: cutter radius compensation on left",
    "canon_event=SELECT_TOOL tool=7",
    "canon_event=COMMENT: interpreter: cutter radius compensation on right",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const ccompMillG90G91G92Dir = writeCcompRegressionFiles("mill-g90g91g92");
assertCcompRegressionCoverage("mill-g90g91g92");
assertCcompRegressionFilesStaging("mill-g90g91g92", ccompMillG90G91G92Dir);
verifyExpectedOutput(
  "interp_ccomp_mill_g90g91g92_wasm",
  interp.runFileWithIni(
    `${ccompMillG90G91G92Dir}/test.ngc`,
    `${ccompMillG90G91G92Dir}/test.ini`,
  ),
  [
    "file_open=0",
    "file_read_count=28",
    "file_execute_count=28",
    "file_saw_error=0",
    "canon_event=SELECT_TOOL tool=3",
    "canon_event=SET_G92_OFFSET x=0 y=0 z=0.5",
    "canon_event=COMMENT: interpreter: cutter radius compensation on left",
    "canon_event=COMMENT: interpreter: cutter radius compensation off",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const ccompMillLineArcEntryDir = writeCcompRegressionFiles("mill-line-arc-entry");
assertCcompRegressionCoverage("mill-line-arc-entry");
assertCcompRegressionFilesStaging("mill-line-arc-entry", ccompMillLineArcEntryDir);
verifyExpectedOutput(
  "interp_ccomp_mill_line_arc_entry_wasm",
  interp.runFileWithIni(
    `${ccompMillLineArcEntryDir}/test.ngc`,
    `${ccompMillLineArcEntryDir}/test.ini`,
  ),
  [
    "file_open=0",
    "file_read_count=33",
    "file_execute_count=33",
    "file_saw_error=0",
    "canon_event=SELECT_TOOL tool=4",
    "canon_event=COMMENT: interpreter: cutter radius compensation on left",
    "canon_event=ARC_FEED line=23 first_end=2 second_end=3.01969",
    "canon_event=COMMENT: interpreter: cutter radius compensation off",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const ccompMillZchangesDir = writeCcompRegressionFiles("mill-zchanges");
assertCcompRegressionCoverage("mill-zchanges");
assertCcompRegressionFilesStaging("mill-zchanges", ccompMillZchangesDir);
verifyExpectedOutput(
  "interp_ccomp_mill_zchanges_wasm",
  interp.runFileWithIni(`${ccompMillZchangesDir}/test.ngc`, `${ccompMillZchangesDir}/test.ini`),
  [
    "file_open=0",
    "file_read_count=81",
    "file_execute_count=81",
    "file_saw_error=0",
    "canon_event=COMMENT: interpreter: cutter radius compensation on left",
    "canon_event=ARC_FEED line=15 first_end=0.5 second_end=0.752461",
    "canon_event=STRAIGHT_FEED line=54 x=0.49826 y=-0.24826 z=0",
    "canon_event=COMMENT: interpreter: cutter radius compensation off",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const badInterpFixtures = [
  {
    name: "a_in_canned_cycle",
    file: "a-in-canned-cycle.ngc",
    readCount: 3,
    executeCount: 2,
    errorText: "Cannot put an a in canned cycle",
  },
  {
    name: "a_in_canned_cycle2",
    file: "a-in-canned-cycle2.ngc",
    readCount: 2,
    executeCount: 1,
    errorText: "Cannot put an a in canned cycle",
  },
  {
    name: "bad_arc_big_imperial_center_format",
    file: "bad-arc.big.imperial.center-format.ngc",
    readCount: 6,
    executeCount: 6,
    errorText: "Radius to end of arc differs from radius to start: start=(X0.0000,Y0.0000) center=(X300.1428,Y0.0000) end=(X600.0000,Y0.0000) r1=300.1428 r2=299.8572 abs_err=0.2857 rel_err=0.0952%",
  },
  {
    name: "bad_arc_big_metric_center_format",
    file: "bad-arc.big.metric.center-format.ngc",
    readCount: 6,
    executeCount: 6,
    errorText: "Radius to end of arc differs from radius to start: start=(X0.0000,Y0.0000) center=(X3001.4284,Y0.0000) end=(X6000.0000,Y0.0000) r1=3001.4284 r2=2998.5716 abs_err=2.857 rel_err=0.0952%",
  },
  {
    name: "bad_arc_medium_imperial_center_format",
    file: "bad-arc.medium.imperial.center-format.ngc",
    readCount: 6,
    executeCount: 6,
    errorText: "Radius to end of arc differs from radius to start: start=(X0.0000,Y0.0000) center=(X99.8500,Y0.0000) end=(X200.0000,Y0.0000) r1=99.8500 r2=100.1500 abs_err=0.3 rel_err=0.2996%",
  },
  {
    name: "bad_arc_medium_metric_center_format",
    file: "bad-arc.medium.metric.center-format.ngc",
    readCount: 6,
    executeCount: 6,
    errorText: "Radius to end of arc differs from radius to start: start=(X0.0000,Y0.0000) center=(X998.5000,Y0.0000) end=(X2000.0000,Y0.0000) r1=998.5000 r2=1001.5000 abs_err=3 rel_err=0.2996%",
  },
  {
    name: "bad_arc_small_imperial_center_format",
    file: "bad-arc.small.imperial.center-format.ngc",
    readCount: 6,
    executeCount: 6,
    errorText: "Radius to end of arc differs from radius to start: start=(X0.0000,Y0.0000) center=(X2.4986,Y0.0000) end=(X5.0000,Y0.0000) r1=2.4986 r2=2.5014 abs_err=0.002857 rel_err=0.1142%",
  },
  {
    name: "bad_arc_small_metric_center_format",
    file: "bad-arc.small.metric.center-format.ngc",
    readCount: 6,
    executeCount: 6,
    errorText: "Radius to end of arc differs from radius to start: start=(X0.0000,Y0.0000) center=(X24.9857,Y0.0000) end=(X50.0000,Y0.0000) r1=24.9857 r2=25.0143 abs_err=0.02857 rel_err=0.1142%",
  },
  {
    name: "ccomp_arcexit",
    file: "ccomp-arcexit.ngc",
    readCount: 7,
    executeCount: 7,
    errorText: "The move just after exiting cutter compensation mode must be straight, not an arc",
  },
  {
    name: "ccomp_gouging",
    file: "ccomp-gouging.ngc",
    readCount: 7,
    executeCount: 7,
    errorText: "Straight feed in concave corner cannot be reached by the tool without gouging",
  },
  {
    name: "exists_1",
    file: "exists-1.ngc",
    readCount: 2,
    executeCount: 1,
    errorText: "Expected # reading parameter",
  },
  {
    name: "exists_2",
    file: "exists-2.ngc",
    readCount: 2,
    executeCount: 1,
    errorText: "Expected ] reading bracketed parameter",
  },
  {
    name: "exists_3",
    file: "exists-3.ngc",
    readCount: 3,
    executeCount: 2,
    errorText: "Parameter number out of range",
  },
  {
    name: "exists_4",
    file: "exists-4.ngc",
    readCount: 2,
    executeCount: 1,
    errorText: "Unknown word starting with f",
  },
  {
    name: "exists_5",
    file: "exists-5.ngc",
    readCount: 2,
    executeCount: 1,
    errorText: "Named parameter not terminated",
  },
  {
    name: "exists_6",
    file: "exists-6.ngc",
    readCount: 2,
    executeCount: 1,
    errorText: "bad number format (conversion failed) parsing ''",
  },
  {
    name: "exists_7",
    file: "exists-7.ngc",
    readCount: 2,
    executeCount: 1,
    errorText: "Expected ] reading bracketed parameter",
  },
  {
    name: "nested",
    file: "nested.ngc",
    readCount: 6,
    executeCount: 5,
    errorText: "Nested subroutine definition",
  },
  {
    name: "no_feed_rate",
    file: "no-feed-rate.ngc",
    readCount: 2,
    executeCount: 2,
    errorText: "Cannot do g1 with zero feed rate",
  },
  {
    name: "no_ijr",
    file: "no-ijr.ngc",
    readCount: 2,
    executeCount: 2,
    errorText: "R i j k words all missing for arc",
  },
  {
    name: "probe_no_axes",
    file: "probe-no-axes.ngc",
    readCount: 2,
    executeCount: 1,
    errorText: "All axes missing with motion code",
  },
];
assert.deepEqual(
  badInterpFixtures.map((fixture) => fixture.file).sort(),
  interpRegressionNgcFiles("bad"),
  "interp bad fixture coverage drift",
);
for (const badFixture of badInterpFixtures) {
  const badPath = writeInterpRegressionFile("bad", badFixture.file);
  assertInterpRegressionFileStaging("bad", badFixture.file, badPath);
  verifyExpectedOutput(
    `interp_bad_${badFixture.name}_wasm`,
    interp.runFile(badPath),
    [
      "file_open=0",
      `file_read_count=${badFixture.readCount}`,
      `file_execute_count=${badFixture.executeCount}`,
      "file_saw_error=1",
      `file_error_text=${badFixture.errorText}`,
      "canon_event=ON_RESET",
    ].join("\n"),
  );
}

const g33_1Path = writeInterpRegressionFile("g33.1", "g33.1.ngc");
const g33_1NgcFiles = [
  "g33.1.ngc",
];
assert.deepEqual(
  g33_1NgcFiles,
  interpRegressionNgcFilesRecursive("g33.1"),
  "interp g33.1 fixture coverage drift",
);
assertInterpRegressionFileStaging("g33.1", "g33.1.ngc", g33_1Path);
verifyExpectedOutput(
  "interp_g33_1_wasm",
  interp.runFile(g33_1Path),
  [
    "file_open=0",
    "file_read_count=5",
    "file_execute_count=5",
    "file_saw_error=0",
    "run_step phase=execute step=4 rc=0 line=4",
    "statement_uri=g33.1%20z-1.2%20k0.1",
    "canon_event=START_SPINDLE_CLOCKWISE spindle=0",
    "canon_event=START_SPEED_FEED_SYNCH spindle=0 feed_per_revolution=0.1 velocity_mode=0",
    "canon_event=RIGID_TAP line=4 x=0 y=0 z=-1.2 scale=1",
    "canon_event=STOP_SPEED_FEED_SYNCH",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const goodArcFixtures = [
  {
    name: "big_imperial_center_format",
    file: "good-arc.big.imperial.center-format.ngc",
    x: 600,
    firstEnd: 600,
    firstAxis: 300.14,
  },
  {
    name: "big_metric_center_format",
    file: "good-arc.big.metric.center-format.ngc",
    x: 6000,
    firstEnd: 6000,
    firstAxis: 3001.4,
  },
  {
    name: "medium_imperial_center_format",
    file: "good-arc.medium.imperial.center-format.ngc",
    x: 200,
    firstEnd: 200,
    firstAxis: 99.95,
  },
  {
    name: "medium_metric_center_format",
    file: "good-arc.medium.metric.center-format.ngc",
    x: 2000,
    firstEnd: 2000,
    firstAxis: 999.5,
  },
  {
    name: "small_imperial_center_format",
    file: "good-arc.small.imperial.center-format.ngc",
    x: 5,
    firstEnd: 5,
    firstAxis: 2.4986,
  },
  {
    name: "small_metric_center_format",
    file: "good-arc.small.metric.center-format.ngc",
    x: 50,
    firstEnd: 50,
    firstAxis: 24.986,
  },
];
assert.deepEqual(
  goodArcFixtures.map((fixture) => fixture.file).sort(),
  interpRegressionNgcFiles("good"),
  "interp good fixture coverage drift",
);
for (const goodArcFixture of goodArcFixtures) {
  const goodArcPath = writeInterpRegressionFile("good", goodArcFixture.file);
  assertInterpRegressionFileStaging("good", goodArcFixture.file, goodArcPath);
  verifyExpectedOutput(
    `interp_good_arc_${goodArcFixture.name}_wasm`,
    interp.runFile(goodArcPath),
    [
      "file_open=0",
      "file_read_count=5",
      "file_execute_count=5",
      "file_saw_error=0",
      `run_step phase=execute step=4 rc=0 line=4 x=${goodArcFixture.x} y=0`,
      `canon_event=ARC_FEED line=4 first_end=${goodArcFixture.firstEnd} second_end=0 first_axis=${goodArcFixture.firstAxis} second_axis=0 rotation=-1 axis_end_point=0`,
      "canon_event=PROGRAM_END",
      "absent=Radius to end of arc differs from radius to start",
    ].join("\n"),
  );
}

const g6164Path = writeInterpRegressionFile("g6164", "test.ngc");
const g6164NgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  g6164NgcFiles,
  interpRegressionNgcFilesRecursive("g6164"),
  "interp g6164 fixture coverage drift",
);
assertInterpRegressionFileStaging("g6164", "test.ngc", g6164Path);
verifyExpectedOutput(
  "interp_g6164_wasm",
  interp.runFile(g6164Path),
  [
    "file_open=0",
    "file_read_count=6",
    "file_execute_count=6",
    "canon_event=SET_MOTION_CONTROL_MODE mode=3 tolerance=0",
    "canon_event=SET_NAIVECAM_TOLERANCE tolerance=0",
    "canon_event=SET_MOTION_CONTROL_MODE mode=3 tolerance=1",
    "canon_event=SET_NAIVECAM_TOLERANCE tolerance=1",
    "canon_event=SET_NAIVECAM_TOLERANCE tolerance=2",
    "canon_event=SET_MOTION_CONTROL_MODE mode=2 tolerance=0",
    "canon_event=SET_MOTION_CONTROL_MODE mode=1 tolerance=0",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const g72Fixtures = [
  {
    name: "facing",
    dir: "g72-facing",
    file: "g72-iterations-present.ngc",
    finalZ: "-39.999",
  },
  {
    name: "missing_iteration",
    dir: "g72-missing-iteration",
    file: "g72-iterations-missing.ngc",
    finalZ: "-40",
  },
];
for (const g72Fixture of g72Fixtures) {
  assert.deepEqual(
    [g72Fixture.file],
    interpRegressionNgcFilesRecursive(g72Fixture.dir),
    `interp ${g72Fixture.dir} fixture coverage drift`,
  );
  const g72Path = writeInterpRegressionFile(g72Fixture.dir, g72Fixture.file);
  assertInterpRegressionFileStaging(g72Fixture.dir, g72Fixture.file, g72Path);
  verifyExpectedOutput(
    `interp_g72_${g72Fixture.name}_wasm`,
    interp.runFile(g72Path),
    [
      "file_open=0",
      "file_read_count=10",
      "file_execute_count=10",
      "file_saw_error=0",
      "run_step phase=execute step=8 rc=0 line=8 x=100 y=0 z=0",
      "canon_event=STRAIGHT_TRAVERSE line=8 x=50 y=0 z=0",
      "canon_event=STRAIGHT_FEED line=-1 x=100 y=0 z=-39",
      `canon_event=STRAIGHT_FEED line=-1 x=100 y=0 z=${g72Fixture.finalZ}`,
      "canon_event=PROGRAM_END",
      "absent=program seem to be stuck",
    ].join("\n"),
  );
}

const g71Fixtures = [
  {
    name: "endless_loop",
    dir: "g71-endless-loop",
    file: "g71-endless-loop.ngc",
    readCount: 19,
    executeCount: 19,
    keyEvents: [
      "canon_event=STRAIGHT_TRAVERSE line=17 x=15 y=0 z=0",
      "canon_event=ARC_FEED line=-1 first_end=-14.04 second_end=10",
      "canon_event=STRAIGHT_FEED line=-1 x=15 y=0 z=-21.96",
    ],
  },
  {
    name: "endless_loop2",
    dir: "g71-endless-loop2",
    file: "g71-endless-loop2.ngc",
    readCount: 12,
    executeCount: 12,
    keyEvents: [
      "canon_event=START_SPINDLE_CLOCKWISE spindle=0",
      "canon_event=STRAIGHT_TRAVERSE line=9 x=168 y=0 z=0",
      "canon_event=STRAIGHT_FEED line=-1 x=170 y=0 z=-415",
      "canon_event=STRAIGHT_TRAVERSE line=11 x=300 y=0 z=10",
    ],
  },
  {
    name: "endless_loop_2",
    dir: "g71-endless-loop_2",
    file: "g71-endless-loop_2.ngc",
    readCount: 40,
    executeCount: 40,
    keyEvents: [
      "canon_event=COMMENT: interpreter: Lathe diameter mode changed to diameter",
      "canon_event=STRAIGHT_TRAVERSE line=31 x=10 y=0 z=2.8",
      "canon_event=ARC_FEED line=-1 first_end=-27 second_end=10.113",
      "canon_event=COMMENT: interpreter: cutter radius compensation off",
      "canon_event=STRAIGHT_TRAVERSE line=38 x=12.5 y=0 z=-25",
    ],
  },
  {
    name: "with_g70",
    dir: "g71-with-g70",
    file: "g71-with-g70.ngc",
    readCount: 32,
    executeCount: 32,
    keyEvents: [
      "canon_event=ARC_FEED line=-1 first_end=1.62661 second_end=1.78761",
      "canon_event=ARC_FEED line=-1 first_end=-36.1 second_end=13",
      "canon_event=STRAIGHT_FEED line=-1 x=15 y=0 z=-38.1",
    ],
  },
];
for (const g71Fixture of g71Fixtures) {
  assert.deepEqual(
    [g71Fixture.file],
    interpRegressionNgcFilesRecursive(g71Fixture.dir),
    `interp ${g71Fixture.dir} fixture coverage drift`,
  );
  const g71Path = writeInterpRegressionFile(g71Fixture.dir, g71Fixture.file);
  assertInterpRegressionFileStaging(g71Fixture.dir, g71Fixture.file, g71Path);
  verifyExpectedOutput(
    `interp_g71_${g71Fixture.name}_wasm`,
    interp.runFile(g71Path),
    [
      "file_open=0",
      `file_read_count=${g71Fixture.readCount}`,
      `file_execute_count=${g71Fixture.executeCount}`,
      "file_saw_error=0",
      ...g71Fixture.keyEvents,
      "canon_event=PROGRAM_END",
      "absent=program seem to be stuck",
      "absent=killing",
    ].join("\n"),
  );
}

const g76Files = [
  "g76only.ngc",
  "test.tbl",
];
const g76Dir = writeInterpRegressionFiles("g76", g76Files);
assertInterpRegressionFilesCoverage("g76", g76Files);
assertInterpRegressionFilesStaging("g76", g76Files, g76Dir);
interp.writeTextFile(
  `${g76Dir}/test.ini`,
  [
    "[EMCIO]",
    "TOOL_TABLE = test.tbl",
    "[TRAJ]",
    "COORDINATES = X Y Z A B C U V W",
    "",
  ].join("\n"),
);
verifyExpectedOutput(
  "interp_g76_wasm",
  interp.runFileWithIni(`${g76Dir}/g76only.ngc`, `${g76Dir}/test.ini`),
  [
    "file_open=0",
    "file_read_count=30",
    "file_execute_count=30",
    "file_saw_error=0",
    "run_step phase=execute step=6 rc=2 line=6",
    "statement_uri=t4%20m6",
    "run_step phase=execute step=25 rc=0 line=25 x=0.2 y=0 z=-0.5",
    "canon_event=SELECT_TOOL tool=4",
    "canon_event=CHANGE_TOOL",
    "canon_event=START_SPINDLE_CLOCKWISE spindle=0",
    "canon_event=START_SPEED_FEED_SYNCH spindle=0 feed_per_revolution=0.05 velocity_mode=0",
    "canon_event=START_SPEED_FEED_SYNCH spindle=0 feed_per_revolution=0.0672681 velocity_mode=0",
    "canon_event=STOP_SPEED_FEED_SYNCH",
    "canon_event=STRAIGHT_TRAVERSE line=25 x=0.237 y=0 z=0.195474",
    "canon_event=STRAIGHT_TRAVERSE line=26 x=0.5 y=0 z=-0.5",
    "canon_event=PROGRAM_END",
    "absent=Requested tool 4 not found",
  ].join("\n"),
);

const rotationAbsPtsPath = writeInterpRegressionFile("rotation/abs-pts", "test.ngc");
assertInterpRegressionFileStaging("rotation/abs-pts", "test.ngc", rotationAbsPtsPath);
const rotationRegressionFiles = [
  "abs-pts/test.ngc",
  "g28/g28.ngc",
  "g53/g53.ngc",
];
assert.deepEqual(
  rotationRegressionFiles,
  interpRegressionNgcFilesRecursive("rotation"),
  "interp_rotation_fixture_coverage: upstream .ngc manifest",
);
const rotationAbsPtsOutput = interp.runFile(rotationAbsPtsPath);
verifyExpectedOutput(
  "interp_rotation_abs_pts_wasm",
  rotationAbsPtsOutput,
  [
    "file_open=0",
    "file_read_count=192",
    "file_execute_count=192",
    "file_saw_error=0",
    "canon_event=MESSAGE: 0.000000 0.000000 0.000000",
    "canon_event=MESSAGE: 1.000000 2.000000 3.000000",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);
assert.equal(
  rotationAbsPtsOutput.match(/canon_event=MESSAGE: 0\.000000 0\.000000 0\.000000/g)?.length,
  14,
  "interp_rotation_abs_pts_wasm: zero absolute-position message count",
);
assert.equal(
  rotationAbsPtsOutput.match(/canon_event=MESSAGE: 1\.000000 2\.000000 3\.000000/g)?.length,
  14,
  "interp_rotation_abs_pts_wasm: target absolute-position message count",
);

const rotationG28Path = writeInterpRegressionFile("rotation/g28", "g28.ngc");
assertInterpRegressionFileStaging("rotation/g28", "g28.ngc", rotationG28Path);
const rotationG28Output = interp.runFile(rotationG28Path);
verifyExpectedOutput(
  "interp_rotation_g28_wasm",
  rotationG28Output,
  [
    "file_open=0",
    "file_read_count=13",
    "file_execute_count=13",
    "file_saw_error=0",
    "canon_event=SET_XY_ROTATION rotation=45",
    "canon_event=COMMENT: G55 G28",
    "canon_event=STRAIGHT_TRAVERSE line=9 x=10 y=10 z=0",
    "canon_event=COMMENT: G56 G28",
    "canon_event=STRAIGHT_TRAVERSE line=14 x=0 y=14.1421 z=0 a=1",
    "canon_event=FINISH",
  ].join("\n"),
);
assert.match(
  rotationG28Output,
  /canon_event=STRAIGHT_TRAVERSE line=14 x=(0|[0-9.e-]+) y=14\.1421 z=0 a=0/,
  "interp_rotation_g28_wasm: G56 G28 final machine point",
);

const rotationG53Path = writeInterpRegressionFile("rotation/g53", "g53.ngc");
assertInterpRegressionFileStaging("rotation/g53", "g53.ngc", rotationG53Path);
const rotationG53Output = interp.runFile(rotationG53Path);
verifyExpectedOutput(
  "interp_rotation_g53_wasm",
  rotationG53Output,
  [
    "file_open=0",
    "file_read_count=17",
    "file_execute_count=17",
    "file_saw_error=0",
    "canon_event=SET_XY_ROTATION rotation=45",
    "canon_event=COMMENT: g53 + g55 to 1,1",
    "canon_event=COMMENT: g53 + g55 + g92 to 1,1",
    "canon_event=STRAIGHT_TRAVERSE line=13 x=0 y=0 z=0",
    "canon_event=COMMENT: g53 + g56 + g92 to 1,1",
    "canon_event=STRAIGHT_TRAVERSE line=18 x=-0.414214 y=1 z=0 a=1",
    "canon_event=FINISH",
  ].join("\n"),
);
assert.match(
  rotationG53Output,
  /canon_event=STRAIGHT_TRAVERSE line=8 x=1\.41421 y=([0-9.e-]+) z=0/,
  "interp_rotation_g53_wasm: rotated G53 endpoint",
);

const iniparamPlan = stageInterpIniContext("iniparam");
const iniparamNgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  iniparamNgcFiles,
  interpRegressionNgcFilesRecursive("iniparam"),
  "interp iniparam fixture coverage drift",
);
assertInterpIniContextNgcStaging("iniparam", iniparamNgcFiles, iniparamPlan);
verifyExpectedOutput(
  "interp_iniparam_wasm",
  interp.runFileWithIniContinueOnError(
    iniparamPlan.programPath,
    iniparamPlan.iniPath,
  ),
  [
    "file_open=0",
    "file_read_count=9",
    "file_execute_count=8",
    "file_saw_error=1",
    "file_error_text=Named parameter #<_ini[nosuchsection]nosuchname> not defined",
    "setup.current_x=10",
    "setup.current_y=20",
    "setup.current_z=30",
    "canon_event=STRAIGHT_TRAVERSE line=1 x=10 y=20 z=30",
    "canon_event=MESSAGE:  position now: 10.000000 20.000000 30.000000",
    "canon_event=MESSAGE:  not in INI: ######",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const iniparamFailassignPlan = stageInterpIniContext("iniparam-failassign");
const iniparamFailassignNgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  iniparamFailassignNgcFiles,
  interpRegressionNgcFilesRecursive("iniparam-failassign"),
  "interp iniparam-failassign fixture coverage drift",
);
assertInterpIniContextNgcStaging(
  "iniparam-failassign",
  iniparamFailassignNgcFiles,
  iniparamFailassignPlan,
);
verifyExpectedOutput(
  "interp_iniparam_failassign_wasm",
  interp.runFileWithIni(
    iniparamFailassignPlan.programPath,
    iniparamFailassignPlan.iniPath,
  ),
  [
    "file_open=0",
    "file_execute_1=5",
    "file_read_count=1",
    "file_execute_count=1",
    "file_saw_error=1",
    "file_error_text=Cannot assign to read-only parameter #<_ini[vars]toolchange_x>",
    "absent=canon_event=MESSAGE:  notreached",
  ].join("\n"),
);

const subCallFromSubPlan = stageInterpIniContext("sub-call-from-sub");
const subCallFromSubNgcFiles = [
  "subs/caller.ngc",
  "subs/helper.ngc",
  "test.ngc",
];
assert.deepEqual(
  subCallFromSubNgcFiles,
  interpRegressionNgcFilesRecursive("sub-call-from-sub"),
  "interp sub-call-from-sub fixture coverage drift",
);
assertInterpIniContextNgcStaging(
  "sub-call-from-sub",
  subCallFromSubNgcFiles,
  subCallFromSubPlan,
);
verifyExpectedOutput(
  "interp_sub_call_from_sub_wasm",
  interp.runFileWithIni(
    subCallFromSubPlan.programPath,
    subCallFromSubPlan.iniPath,
  ),
  [
    "file_open=0",
    "file_read_count=10",
    "file_execute_count=10",
    "canon_event=COMMENT: Test: calling a sub from within another sub is valid",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const sequenceNumberPlan = stageInterpIniContext("sequence-number");
const sequenceNumberNgcFiles = [
  "rm400.ngc",
  "test.ngc",
];
assert.deepEqual(
  sequenceNumberNgcFiles,
  interpRegressionNgcFilesRecursive("sequence-number"),
  "interp sequence-number fixture coverage drift",
);
assertInterpIniContextNgcStaging(
  "sequence-number",
  sequenceNumberNgcFiles,
  sequenceNumberPlan,
);
verifyExpectedOutput(
  "interp_sequence_number_wasm",
  interp.runFileWithIni(
    sequenceNumberPlan.programPath,
    sequenceNumberPlan.iniPath,
  ),
  [
    "file_open=0",
    "file_read_count=13",
    "file_execute_count=13",
    "canon_event=MESSAGE: main: line=7.000000 - expect 7",
    "canon_event=MESSAGE:  in rm400.ngc line=2.000000 - expect 2",
    "canon_event=MESSAGE: main: line=9.000000 - expect 9",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const nestedSubErrorPlan = stageInterpIniContext("nested-sub-error");
const nestedSubErrorNgcFiles = [
  "subs/nested.ngc",
  "test.ngc",
];
assert.deepEqual(
  nestedSubErrorNgcFiles,
  interpRegressionNgcFilesRecursive("nested-sub-error"),
  "interp nested-sub-error fixture coverage drift",
);
assertInterpIniContextNgcStaging(
  "nested-sub-error",
  nestedSubErrorNgcFiles,
  nestedSubErrorPlan,
);
verifyExpectedOutput(
  "interp_nested_sub_error_wasm",
  interp.runFileWithIni(
    nestedSubErrorPlan.programPath,
    nestedSubErrorPlan.iniPath,
  ),
  [
    "file_open=0",
    "file_read_4=5",
    "file_error_text=Nested subroutine definition: 'O100 sub' found inside called subroutine 'Onested'",
    "file_read_count=4",
    "file_execute_count=3",
    "canon_event=COMMENT: Test: nested sub definition inside named sub should error",
    "absent=canon_event=PROGRAM_END",
  ].join("\n"),
);

const nestedSubInFileErrorPlan = stageInterpIniContext("nested-sub-in-file-error");
const nestedSubInFileErrorNgcFiles = [
  "subs/sequential.ngc",
  "test.ngc",
];
assert.deepEqual(
  nestedSubInFileErrorNgcFiles,
  interpRegressionNgcFilesRecursive("nested-sub-in-file-error"),
  "interp nested-sub-in-file-error fixture coverage drift",
);
assertInterpIniContextNgcStaging(
  "nested-sub-in-file-error",
  nestedSubInFileErrorNgcFiles,
  nestedSubInFileErrorPlan,
);
verifyExpectedOutput(
  "interp_nested_sub_in_file_error_wasm",
  interp.runFileWithIni(
    nestedSubInFileErrorPlan.programPath,
    nestedSubInFileErrorPlan.iniPath,
  ),
  [
    "file_open=0",
    "file_execute_5=5",
    "file_error_text=Subroutine 'O200' not found -- not in offset table and no file '",
    "file_read_count=5",
    "file_execute_count=5",
    "canon_event=COMMENT: Test: numbered sub after named endsub in same file should error",
    "canon_event=MESSAGE:  sequential main: 7.000000 8.000000 9.000000",
    "absent=canon_event=PROGRAM_END",
  ].join("\n"),
);

const owordUnwindPlan = stageInterpIniContext("oword-unwind");
const owordUnwindNgcFiles = [
  "fail.ngc",
  "test.ngc",
];
assert.deepEqual(
  owordUnwindNgcFiles,
  interpRegressionNgcFilesRecursive("oword-unwind"),
  "interp oword-unwind fixture coverage drift",
);
assertInterpIniContextNgcStaging(
  "oword-unwind",
  owordUnwindNgcFiles,
  owordUnwindPlan,
);
verifyExpectedOutput(
  "interp_oword_unwind_wasm",
  interp.runFileWithIniContinueOnError(
    owordUnwindPlan.programPath,
    owordUnwindPlan.iniPath,
  ),
  [
    "file_open=0",
    "file_read_5=5",
    "file_read_10=5",
    "file_read_count=11",
    "file_execute_count=9",
    "file_saw_error=1",
    "canon_event=MESSAGE:  pre divide-by-zero",
    "canon_event=PROGRAM_END",
    "absent=canon_event=MESSAGE:  post divide-by-zero",
  ].join("\n"),
);

const abortHotCommentPlan = stageInterpIniContext("abort-hot-comment");
const abortHotCommentNgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  abortHotCommentNgcFiles,
  interpRegressionNgcFilesRecursive("abort-hot-comment"),
  "interp abort-hot-comment fixture coverage drift",
);
assertInterpIniContextNgcStaging(
  "abort-hot-comment",
  abortHotCommentNgcFiles,
  abortHotCommentPlan,
);
verifyExpectedOutput(
  "interp_abort_hot_comment_wasm",
  interp.runFileWithIniContinueOnError(
    abortHotCommentPlan.programPath,
    abortHotCommentPlan.iniPath,
  ),
  [
    "file_open=0",
    "file_read_count=125",
    "file_execute_count=125",
    "file_saw_error=1",
    "file_error_text= MixedCase param42=20.000000 named=4711.000000 INI=3.140000",
    "absent=canon_event=PROGRAM_END",
  ].join("\n"),
);

const m19Plan = stageInterpIniContext("m19");
const m19NgcFiles = [
  "test.ngc",
];
assert.deepEqual(
  m19NgcFiles,
  interpRegressionNgcFilesRecursive("m19"),
  "interp m19 fixture coverage drift",
);
assertInterpIniContextNgcStaging(
  "m19",
  m19NgcFiles,
  m19Plan,
);
verifyExpectedOutput(
  "interp_m19_wasm",
  interp.runFileWithIni(m19Plan.programPath, m19Plan.iniPath),
  [
    "file_open=0",
    "file_read_count=8",
    "file_execute_count=8",
    "file_saw_error=0",
    "canon_event=ORIENT_SPINDLE spindle=0 orientation=87 mode=0",
    "canon_event=WAIT_SPINDLE_ORIENT_COMPLETE spindle=0 timeout=2",
    "canon_event=ORIENT_SPINDLE spindle=0 orientation=42 mode=1",
    "canon_event=ORIENT_SPINDLE spindle=0 orientation=132 mode=0",
    "canon_event=ORIENT_SPINDLE spindle=0 orientation=132 mode=1",
    "canon_event=WAIT_SPINDLE_ORIENT_COMPLETE spindle=0 timeout=1",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const magicCommentsParamFormatPath = writeInterpRegressionFile(
  "magic_comments/param_format_printing",
  "test.ngc",
);
const magicCommentsRegressionFiles = [
  "param_format_printing/test.ngc",
];
assert.deepEqual(
  magicCommentsRegressionFiles,
  interpRegressionNgcFilesRecursive("magic_comments"),
  "interp_magic_comments_fixture_coverage: upstream .ngc manifest",
);
assertInterpRegressionFileStaging(
  "magic_comments/param_format_printing",
  "test.ngc",
  magicCommentsParamFormatPath,
);
verifyExpectedOutput(
  "interp_magic_comments_param_format_wasm",
  interp.runFile(magicCommentsParamFormatPath),
  [
    "file_open=0",
    "file_read_count=13",
    "file_execute_count=13",
    "file_saw_error=0",
    "canon_event=MESSAGE:  native value = 1.123457",
    "canon_event=MESSAGE:  Test round to integer: 1",
    "canon_event=MESSAGE:  Test round to 4 decimals: 1.1235",
    "canon_event=MESSAGE:  Test format separate from param:  The value is: 1.1235",
    "canon_event=MESSAGE:  Test round to 7 decimals: 1.1234568",
    "canon_event=MESSAGE:  native value2 = 2.345679",
    "canon_event=MESSAGE:  Test2 round all params in line to 4 decimals:  The values are: 1.1235,  2.3457",
    "canon_event=MESSAGE:  Test2 only round last value to integer: The values are: 1.123457,  2",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const m98m99RegressionFiles = [
  "01-basics/test.ngc",
  "02-variables/test.ngc",
  "03-error-M98-no-P-word/test.ngc",
  "04-M98-but-no-sub/test.ngc",
  "05-M98-loops/test.ngc",
  "06-error-mixed-sub-styles/O...-called-with-O..._call.ngc",
  "06-error-mixed-sub-styles/O...-ended-with-O..._endsub.ngc",
  "06-error-mixed-sub-styles/O...-sub-called-with-M98.ngc",
  "06-error-mixed-sub-styles/O...-sub-ended-with-M99.ngc",
  "07-nested-subs/test.ngc",
  "08-sub-follows-main/test.ngc",
  "09-disable-fanuc-subs/test-fanuc.ngc",
  "09-disable-fanuc-subs/test-rs274ngc.ngc",
  "10-M98-P001/test.ngc",
  "11-main-program-oword/test-illegal-end-main-with-eof.ngc",
  "11-main-program-oword/test-illegal-no-m30-before-osub.ngc",
  "11-main-program-oword/test-illegal-sub-after-percent.ngc",
  "11-main-program-oword/test-legal-end-main-with-m02.ngc",
  "11-main-program-oword/test-legal-end-main-with-m2.ngc",
  "11-main-program-oword/test-legal-end-main-with-m30.ngc",
  "11-main-program-oword/test-legal-end-main-with-percent.ngc",
  "13-named-program/test-named.ngc",
  "13-named-program/test-numbered.ngc",
  "14-o-expression-call/test.ngc",
];
assert.deepEqual(
  m98m99RegressionFiles,
  interpRegressionNgcFilesRecursive("m98m99"),
  "interp m98m99 fixture coverage drift",
);

const m98m99BasicsPath = writeInterpRegressionFile("m98m99/01-basics", "test.ngc");
assertInterpRegressionFileStaging("m98m99/01-basics", "test.ngc", m98m99BasicsPath);
verifyExpectedOutput(
  "interp_m98m99_01_basics_wasm",
  interp.runFile(m98m99BasicsPath),
  [
    "file_open=0",
    "file_read_count=22",
    "file_execute_count=22",
    "file_saw_error=0",
    "canon_event=COMMENT: A simple O sub example ",
    "canon_event=STRAIGHT_TRAVERSE line=10 x=3 y=0 z=0.25",
    "canon_event=STRAIGHT_FEED line=11 x=3 y=0 z=-1",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const m98m99VariablesPath = writeInterpRegressionFile("m98m99/02-variables", "test.ngc");
assertInterpRegressionFileStaging("m98m99/02-variables", "test.ngc", m98m99VariablesPath);
const m98m99VariablesRun = runWithCapturedPrints(() => interp.runFile(m98m99VariablesPath));
verifyExpectedOutput(
  "interp_m98m99_02_variables_wasm",
  m98m99VariablesRun.output,
  [
    "file_open=0",
    "file_read_count=54",
    "file_execute_count=54",
    "file_saw_error=0",
    "canon_event=COMMENT: Fanuc params have global scope; rs274ngc params #1..#30 have local scope ",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);
verifyExpectedOutput(
  "interp_m98m99_02_variables_prints_wasm",
  m98m99VariablesRun.prints,
  [
    "Q MAIN/FANUC:  POST-M98:  1=13.010000; 30=13.300000; 31=13.310000",
    "Q MAIN/RS274NGC:  POST-O-CALL:  1=42.010000; 30=42.300000; 31=13.310000",
  ].join("\n"),
);

const m98m99M98NoPWordPath = writeInterpRegressionFile(
  "m98m99/03-error-M98-no-P-word",
  "test.ngc",
);
assertInterpRegressionFileStaging(
  "m98m99/03-error-M98-no-P-word",
  "test.ngc",
  m98m99M98NoPWordPath,
);
verifyExpectedOutput(
  "interp_m98m99_03_error_m98_no_p_word_wasm",
  interp.runFile(m98m99M98NoPWordPath),
  [
    "file_open=0",
    "file_read_count=3",
    "file_execute_count=2",
    "file_saw_error=1",
    "file_error_text=Found 'm98' code with no P-word",
    "run_step phase=read step=3 rc=5 line=4",
    "statement_uri=M98",
    "canon_event=COMMENT: Fanuc M98 requires P-word ",
    "absent=canon_event=PROGRAM_END",
  ].join("\n"),
);

const m98m99M98ButNoSubPath = writeInterpRegressionFile(
  "m98m99/04-M98-but-no-sub",
  "test.ngc",
);
assertInterpRegressionFileStaging("m98m99/04-M98-but-no-sub", "test.ngc", m98m99M98ButNoSubPath);
verifyExpectedOutput(
  "interp_m98m99_04_m98_but_no_sub_wasm",
  interp.runFile(m98m99M98ButNoSubPath),
  [
    "file_open=0",
    "file_read_count=5",
    "file_execute_count=4",
    "file_saw_error=1",
    "file_error_text=Failed to find sub 'O1' before EOF",
    "run_step phase=read step=5 rc=5 line=4",
    "statement_uri=%25",
    "canon_event=COMMENT: M98 call non-existant sub ",
    "absent=canon_event=PROGRAM_END",
  ].join("\n"),
);

const m98m99M98LoopsPath = writeInterpRegressionFile("m98m99/05-M98-loops", "test.ngc");
assertInterpRegressionFileStaging("m98m99/05-M98-loops", "test.ngc", m98m99M98LoopsPath);
const m98m99M98LoopsRun = runWithCapturedPrints(() => interp.runFile(m98m99M98LoopsPath));
verifyExpectedOutput(
  "interp_m98m99_05_m98_loops_wasm",
  m98m99M98LoopsRun.output,
  [
    "file_open=0",
    "file_read_count=102",
    "file_execute_count=102",
    "file_saw_error=0",
    "canon_event=COMMENT: A simple O sub example ",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);
verifyExpectedOutput(
  "interp_m98m99_05_m98_loops_prints_wasm",
  m98m99M98LoopsRun.prints,
  [
    "X SUB O1 PARAM1 = 10.000000",
    "X MAIN 10LOOP PARAM1 = 10.000000",
    "X MAIN 0LOOP PARAM1 = 0.000000",
    "X MAIN 2LOOP PARAM1 = 2.000000",
  ].join("\n"),
);

const m98m99MixedSubStyleFiles = [
  "O...-called-with-O..._call.ngc",
  "O...-ended-with-O..._endsub.ngc",
  "O...-sub-called-with-M98.ngc",
  "O...-sub-ended-with-M99.ngc",
];
const m98m99MixedSubStyleDir = writeInterpRegressionFiles(
  "m98m99/06-error-mixed-sub-styles",
  m98m99MixedSubStyleFiles,
);
assertInterpRegressionFilesCoverage(
  "m98m99/06-error-mixed-sub-styles",
  m98m99MixedSubStyleFiles,
);
assertInterpRegressionFilesStaging(
  "m98m99/06-error-mixed-sub-styles",
  m98m99MixedSubStyleFiles,
  m98m99MixedSubStyleDir,
);
for (const mixedSubStyleFixture of [
  {
    name: "called_with_o_call",
    file: "O...-called-with-O..._call.ngc",
    readCount: 5,
    executeCount: 5,
    errorText: "Fanuc 'O....' subroutine must be called with 'M98'",
    errorStep: "run_step phase=execute step=5 rc=5 line=4",
    statementUri: "statement_uri=O1",
    comment: "canon_event=COMMENT: Fanuc 'O...' sub must be called with M98 ",
  },
  {
    name: "ended_with_o_endsub",
    file: "O...-ended-with-O..._endsub.ngc",
    readCount: 7,
    executeCount: 7,
    errorText: "Fanuc 'O....' subroutine definition must end with 'M99'",
    errorStep: "run_step phase=execute step=7 rc=5 line=4",
    statementUri: "statement_uri=O1%20endsub",
    comment: "canon_event=COMMENT: Fanuc 'O...' sub must end with M99 ",
    print: "X FANUC",
  },
  {
    name: "sub_called_with_m98",
    file: "O...-sub-called-with-M98.ngc",
    readCount: 5,
    executeCount: 5,
    errorText: "'O.... sub' subroutine must be called with 'O.... call'",
    errorStep: "run_step phase=execute step=5 rc=5 line=4",
    statementUri: "statement_uri=O1%20sub",
    comment: "canon_event=COMMENT: RS274NGC 'O...' sub must not be called with M98 ",
  },
  {
    name: "sub_ended_with_m99",
    file: "O...-sub-ended-with-M99.ngc",
    readCount: 7,
    executeCount: 7,
    errorText: "'O.... endsub' or 'O.... return' must follow 'O.... sub' subroutine definition",
    errorStep: "run_step phase=execute step=7 rc=5 line=4",
    statementUri: "statement_uri=M99",
    comment: "canon_event=COMMENT: RS274NGC 'O... sub' sub must not end with M99 ",
    print: "X FANUC",
  },
]) {
  const mixedSubStylePath = `${m98m99MixedSubStyleDir}/${mixedSubStyleFixture.file}`;
  const mixedSubStyleRun = runWithCapturedPrints(() => interp.runFile(mixedSubStylePath));
  verifyExpectedOutput(
    `interp_m98m99_06_${mixedSubStyleFixture.name}_wasm`,
    mixedSubStyleRun.output,
    [
      "file_open=0",
      `file_read_count=${mixedSubStyleFixture.readCount}`,
      `file_execute_count=${mixedSubStyleFixture.executeCount}`,
      "file_saw_error=1",
      `file_error_text=${mixedSubStyleFixture.errorText}`,
      mixedSubStyleFixture.errorStep,
      mixedSubStyleFixture.statementUri,
      mixedSubStyleFixture.comment,
      "absent=canon_event=PROGRAM_END",
    ].join("\n"),
  );
  if (mixedSubStyleFixture.print) {
    verifyExpectedOutput(
      `interp_m98m99_06_${mixedSubStyleFixture.name}_prints_wasm`,
      mixedSubStyleRun.prints,
      mixedSubStyleFixture.print,
    );
  }
}

const m98m99NestedSubsPath = writeInterpRegressionFile("m98m99/07-nested-subs", "test.ngc");
assertInterpRegressionFileStaging("m98m99/07-nested-subs", "test.ngc", m98m99NestedSubsPath);
const m98m99NestedSubsRun = runWithCapturedPrints(() => interp.runFile(m98m99NestedSubsPath));
verifyExpectedOutput(
  "interp_m98m99_07_nested_subs_wasm",
  m98m99NestedSubsRun.output,
  [
    "file_open=0",
    "file_read_count=163",
    "file_execute_count=163",
    "file_saw_error=0",
    "canon_event=COMMENT: A nested Fanuc subroutine example ",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);
verifyExpectedOutput(
  "interp_m98m99_07_nested_subs_prints_wasm",
  m98m99NestedSubsRun.prints,
  [
    "X >>>> LOOP [O2.O1]:  4.500000",
    "X MAIN END:  1=5.000000",
  ].join("\n"),
);

const m98m99SubFollowsMainPath = writeInterpRegressionFile(
  "m98m99/08-sub-follows-main",
  "test.ngc",
);
assertInterpRegressionFileStaging(
  "m98m99/08-sub-follows-main",
  "test.ngc",
  m98m99SubFollowsMainPath,
);
const m98m99SubFollowsMainRun = runWithCapturedPrints(() =>
  interp.runFile(m98m99SubFollowsMainPath),
);
verifyExpectedOutput(
  "interp_m98m99_08_sub_follows_main_wasm",
  m98m99SubFollowsMainRun.output,
  [
    "file_open=0",
    "file_read_count=9",
    "file_execute_count=9",
    "file_saw_error=0",
    "canon_event=COMMENT: Fanuc-style subs may follow main program ",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);
verifyExpectedOutput(
  "interp_m98m99_08_sub_follows_main_prints_wasm",
  m98m99SubFollowsMainRun.prints,
  "X IN O1",
);

const m98m99DisableFanucSubsFiles = [
  "test-fanuc.ini",
  "test-no-fanuc.ini",
  "test-fanuc.ngc",
  "test-rs274ngc.ngc",
];
const m98m99DisableFanucSubsDir = writeInterpRegressionFiles(
  "m98m99/09-disable-fanuc-subs",
  m98m99DisableFanucSubsFiles,
);
assertInterpRegressionFilesCoverage(
  "m98m99/09-disable-fanuc-subs",
  m98m99DisableFanucSubsFiles,
);
assertInterpRegressionFilesStaging(
  "m98m99/09-disable-fanuc-subs",
  m98m99DisableFanucSubsFiles,
  m98m99DisableFanucSubsDir,
);
for (const disableFanucCase of [
  {
    name: "fanuc_ini",
    program: "test-fanuc.ngc",
    ini: "test-fanuc.ini",
    readCount: 22,
    keyTraverse: "canon_event=STRAIGHT_TRAVERSE line=10 x=3 y=0 z=0.25",
    keyFeed: "canon_event=STRAIGHT_FEED line=11 x=3 y=0 z=-1",
  },
  {
    name: "rs274ngc_ini",
    program: "test-rs274ngc.ngc",
    ini: "test-fanuc.ini",
    readCount: 15,
    keyTraverse: "canon_event=STRAIGHT_TRAVERSE line=5 x=1 y=0 z=0.25",
    keyFeed: "canon_event=STRAIGHT_FEED line=6 x=1 y=0 z=-1",
  },
  {
    name: "rs274ngc_no_fanuc",
    program: "test-rs274ngc.ngc",
    ini: "test-no-fanuc.ini",
    readCount: 15,
    keyTraverse: "canon_event=STRAIGHT_TRAVERSE line=5 x=1 y=0 z=0.25",
    keyFeed: "canon_event=STRAIGHT_FEED line=6 x=1 y=0 z=-1",
  },
  {
    name: "fanuc_default",
    program: "test-fanuc.ngc",
    readCount: 22,
    keyTraverse: "canon_event=STRAIGHT_TRAVERSE line=10 x=3 y=0 z=0.25",
    keyFeed: "canon_event=STRAIGHT_FEED line=11 x=3 y=0 z=-1",
  },
  {
    name: "rs274ngc_default",
    program: "test-rs274ngc.ngc",
    readCount: 15,
    keyTraverse: "canon_event=STRAIGHT_TRAVERSE line=5 x=1 y=0 z=0.25",
    keyFeed: "canon_event=STRAIGHT_FEED line=6 x=1 y=0 z=-1",
  },
]) {
  const output = disableFanucCase.ini
    ? interp.runFileWithIni(
        `${m98m99DisableFanucSubsDir}/${disableFanucCase.program}`,
        `${m98m99DisableFanucSubsDir}/${disableFanucCase.ini}`,
      )
    : interp.runFile(`${m98m99DisableFanucSubsDir}/${disableFanucCase.program}`);
  verifyExpectedOutput(
    `interp_m98m99_09_${disableFanucCase.name}_wasm`,
    output,
    [
      "file_open=0",
      `file_read_count=${disableFanucCase.readCount}`,
      `file_execute_count=${disableFanucCase.readCount}`,
      "file_saw_error=0",
      "canon_event=COMMENT: A simple O sub example ",
      disableFanucCase.keyTraverse,
      disableFanucCase.keyFeed,
      "canon_event=PROGRAM_END",
      "absent=file_error_text=DISABLE_FANUC_STYLE_SUB",
    ].join("\n"),
  );
}
verifyExpectedOutput(
  "interp_m98m99_09_fanuc_no_fanuc_wasm",
  interp.runFileWithIni(
    `${m98m99DisableFanucSubsDir}/test-fanuc.ngc`,
    `${m98m99DisableFanucSubsDir}/test-no-fanuc.ini`,
  ),
  [
    "file_open=0",
    "file_read_count=5",
    "file_execute_count=4",
    "file_saw_error=1",
    "file_error_text=DISABLE_FANUC_STYLE_SUB set in INI file, but found m98",
    "run_step phase=read step=5 rc=5 line=6",
    "statement_uri=M98%20P1%20L3",
    "canon_event=STRAIGHT_TRAVERSE line=5 x=0 y=0 z=0.25",
    "absent=canon_event=PROGRAM_END",
  ].join("\n"),
);

const m98m99M98P001Path = writeInterpRegressionFile("m98m99/10-M98-P001", "test.ngc");
assertInterpRegressionFileStaging("m98m99/10-M98-P001", "test.ngc", m98m99M98P001Path);
const m98m99M98P001Run = runWithCapturedPrints(() => interp.runFile(m98m99M98P001Path));
verifyExpectedOutput(
  "interp_m98m99_10_m98_p001_wasm",
  m98m99M98P001Run.output,
  [
    "file_open=0",
    "file_read_count=8",
    "file_execute_count=8",
    "file_saw_error=0",
    "canon_event=COMMENT: main program",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);
verifyExpectedOutput(
  "interp_m98m99_10_m98_p001_prints_wasm",
  m98m99M98P001Run.prints,
  [
    "x got here",
    "absent=ERROR: should not get here",
  ].join("\n"),
);

const m98m99MainProgramOwordFiles = [
  "test-illegal-end-main-with-eof.ngc",
  "test-illegal-no-m30-before-osub.ngc",
  "test-illegal-sub-after-percent.ngc",
  "test-legal-end-main-with-m02.ngc",
  "test-legal-end-main-with-m2.ngc",
  "test-legal-end-main-with-m30.ngc",
  "test-legal-end-main-with-percent.ngc",
];
const m98m99MainProgramOwordDir = writeInterpRegressionFiles(
  "m98m99/11-main-program-oword",
  m98m99MainProgramOwordFiles,
);
assertInterpRegressionFilesCoverage(
  "m98m99/11-main-program-oword",
  m98m99MainProgramOwordFiles,
);
assertInterpRegressionFilesStaging(
  "m98m99/11-main-program-oword",
  m98m99MainProgramOwordFiles,
  m98m99MainProgramOwordDir,
);
for (const mainProgramFixture of [
  {
    name: "legal_m2",
    file: "test-legal-end-main-with-m2.ngc",
    readCount: 17,
    firstLine: 4,
    subLine: 13,
    endEvent: "canon_event=PROGRAM_END",
  },
  {
    name: "legal_m02",
    file: "test-legal-end-main-with-m02.ngc",
    readCount: 17,
    firstLine: 4,
    subLine: 13,
    endEvent: "canon_event=PROGRAM_END",
  },
  {
    name: "legal_m30",
    file: "test-legal-end-main-with-m30.ngc",
    readCount: 17,
    firstLine: 4,
    subLine: 13,
    endEvent: "canon_event=PROGRAM_END",
  },
  {
    name: "legal_percent",
    file: "test-legal-end-main-with-percent.ngc",
    readCount: 20,
    firstLine: 11,
    subLine: 6,
    endEvent: "canon_event=FINISH",
  },
]) {
  verifyExpectedOutput(
    `interp_m98m99_11_${mainProgramFixture.name}_wasm`,
    interp.runFile(`${m98m99MainProgramOwordDir}/${mainProgramFixture.file}`),
    [
      "file_open=0",
      `file_read_count=${mainProgramFixture.readCount}`,
      `file_execute_count=${mainProgramFixture.readCount}`,
      "file_saw_error=0",
      "canon_event=COMMENT: legal example",
      `canon_event=STRAIGHT_TRAVERSE line=${mainProgramFixture.firstLine} x=1 y=2 z=0`,
      `canon_event=STRAIGHT_TRAVERSE line=${mainProgramFixture.subLine} x=1 y=2 z=3`,
      mainProgramFixture.endEvent,
      "absent=should never get here",
    ].join("\n"),
  );
}
for (const mainProgramErrorFixture of [
  {
    name: "illegal_eof",
    file: "test-illegal-end-main-with-eof.ngc",
    readCount: 21,
    executeCount: 20,
    errorText: "File ended with no percent sign (%) or program end (M2)",
    marker: "canon_event=COMMENT: end of main signaled by EOF",
  },
  {
    name: "illegal_no_m30",
    file: "test-illegal-no-m30-before-osub.ngc",
    readCount: 18,
    executeCount: 18,
    errorText: "File:",
    marker: "statement_uri=O2%20sub%20%28subprogram%20begin%29",
    extraMarker: "sub: o|2| found in illegal location",
  },
  {
    name: "illegal_sub_after_percent",
    file: "test-illegal-sub-after-percent.ngc",
    readCount: 8,
    executeCount: 7,
    errorText: "Failed to find sub 'O2' before EOF",
    marker: "canon_event=FINISH",
  },
]) {
  verifyExpectedOutput(
    `interp_m98m99_11_${mainProgramErrorFixture.name}_wasm`,
    interp.runFile(`${m98m99MainProgramOwordDir}/${mainProgramErrorFixture.file}`),
    [
      "file_open=0",
      `file_read_count=${mainProgramErrorFixture.readCount}`,
      `file_execute_count=${mainProgramErrorFixture.executeCount}`,
      "file_saw_error=1",
      `file_error_text=${mainProgramErrorFixture.errorText}`,
      mainProgramErrorFixture.marker,
      mainProgramErrorFixture.extraMarker ?? "",
      "absent=canon_event=PROGRAM_END",
    ].join("\n"),
  );
}

const m98m99NamedProgramFiles = [
  "test-named.ngc",
  "test-numbered.ngc",
];
const m98m99NamedProgramDir = writeInterpRegressionFiles(
  "m98m99/13-named-program",
  m98m99NamedProgramFiles,
);
assertInterpRegressionFilesCoverage(
  "m98m99/13-named-program",
  m98m99NamedProgramFiles,
);
assertInterpRegressionFilesStaging(
  "m98m99/13-named-program",
  m98m99NamedProgramFiles,
  m98m99NamedProgramDir,
);
verifyExpectedOutput(
  "interp_m98m99_13_named_program_named_wasm",
  interp.runFile(`${m98m99NamedProgramDir}/test-named.ngc`),
  [
    "file_open=0",
    "file_read_count=4",
    "file_execute_count=4",
    "file_saw_error=0",
    "canon_event=COMMENT: test-named.ngc:  Test named programs",
    "canon_event=COMMENT: ...program body",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

verifyExpectedOutput(
  "interp_m98m99_13_named_program_numbered_wasm",
  interp.runFile(`${m98m99NamedProgramDir}/test-numbered.ngc`),
  [
    "file_open=0",
    "file_read_count=4",
    "file_execute_count=4",
    "file_saw_error=0",
    "canon_event=COMMENT: test-numbered.ngc:  Test numbered programs",
    "canon_event=COMMENT: ...program body",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const m98m99OExpressionCallPath = writeInterpRegressionFile(
  "m98m99/14-o-expression-call",
  "test.ngc",
);
assertInterpRegressionFileStaging(
  "m98m99/14-o-expression-call",
  "test.ngc",
  m98m99OExpressionCallPath,
);
const m98m99OExpressionCallRun = runWithCapturedPrints(() =>
  interp.runFile(m98m99OExpressionCallPath),
);
verifyExpectedOutput(
  "interp_m98m99_14_o_expression_call_wasm",
  m98m99OExpressionCallRun.output,
  [
    "file_open=0",
    "file_read_count=29",
    "file_execute_count=29",
    "file_saw_error=0",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);
verifyExpectedOutput(
  "interp_m98m99_14_o_expression_call_prints_wasm",
  m98m99OExpressionCallRun.prints,
  [
    "In sub 100",
    "In sub 200",
  ].join("\n"),
);

const g10RegressionFiles = [
  "g10-l1-l10/test.ngc",
  "g10-l11/test.ngc",
  "g10-l2-while-active/test.ngc",
  "g10-l20-while-active/test.ngc",
  "g10-with-g92/test.ngc",
];
assert.deepEqual(
  g10RegressionFiles,
  interpRegressionNgcFilesRecursive("g10"),
  "interp g10 fixture coverage drift",
);

const g10L1L10Dir = writeG10RegressionFiles("g10-l1-l10", ["test.ngc", "test.tbl"]);
assertG10RegressionCoverage("g10-l1-l10", ["test.ngc", "test.tbl"]);
assertG10RegressionFilesStaging("g10-l1-l10", ["test.ngc", "test.tbl"], g10L1L10Dir);
verifyExpectedOutput(
  "interp_g10_l1_l10_wasm",
  interp.runFileWithIni(`${g10L1L10Dir}/test.ngc`, `${g10L1L10Dir}/test.ini`),
  [
    "file_open=0",
    "file_read_count=115",
    "file_execute_count=115",
    "file_saw_error=0",
    "canon_event=MESSAGE: G10 L1:  set tool offsets direct",
    "canon_event=MESSAGE: G10 L10:  set tool offsets relative to position + 45 deg. rotation",
    "canon_event=MESSAGE: Model B contract: M6 alone and G10 alone do not change tool offset params",
    "canon_event=MESSAGE:  G10 alone does not apply offset, should still be 0 0 0: 0.000000 0.000000 0.000000",
    "canon_event=USE_TOOL_LENGTH_OFFSET x=8 y=6 z=7",
    "canon_event=SET_XY_ROTATION rotation=45",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const g10L11Dir = writeG10RegressionFiles("g10-l11", ["test.ngc", "test.tbl"]);
assertG10RegressionCoverage("g10-l11", ["test.ngc", "test.tbl"]);
assertG10RegressionFilesStaging("g10-l11", ["test.ngc", "test.tbl"], g10L11Dir);
verifyExpectedOutput(
  "interp_g10_l11_wasm",
  interp.runFileWithIni(`${g10L11Dir}/test.ngc`, `${g10L11Dir}/test.ini`),
  [
    "file_open=0",
    "file_read_count=41",
    "file_execute_count=41",
    "file_saw_error=0",
    "canon_event=SET_G5X_OFFSET index=1 x=1 y=2 z=-3",
    "canon_event=SET_G92_OFFSET x=-41.1962 y=-46.1962 z=-72",
    "canon_event=USE_TOOL_LENGTH_OFFSET x=0 y=0 z=-4",
    "canon_event=MESSAGE: -101.600000",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const g10L2WhileActiveDir = writeG10RegressionFiles("g10-l2-while-active", ["test.ngc"]);
assertG10RegressionCoverage("g10-l2-while-active", ["test.ngc"]);
assertG10RegressionFilesStaging("g10-l2-while-active", ["test.ngc"], g10L2WhileActiveDir);
verifyExpectedOutput(
  "interp_g10_l2_while_active_wasm",
  interp.runFile(`${g10L2WhileActiveDir}/test.ngc`),
  [
    "file_open=0",
    "file_read_count=24",
    "file_execute_count=24",
    "file_saw_error=0",
    "canon_event=SET_G5X_OFFSET index=1 x=1 y=0 z=0",
    "canon_event=SET_XY_ROTATION rotation=-45",
    "canon_event=MESSAGE:  Should be 0 1.414214: 0.000000 1.414214",
    "canon_event=SET_XY_ROTATION rotation=90",
    "canon_event=MESSAGE:  Should be 1 1: 1.000000 1.000000",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const g10L20WhileActiveDir = writeG10RegressionFiles("g10-l20-while-active", ["test.ngc"]);
assertG10RegressionCoverage("g10-l20-while-active", ["test.ngc"]);
assertG10RegressionFilesStaging("g10-l20-while-active", ["test.ngc"], g10L20WhileActiveDir);
verifyExpectedOutput(
  "interp_g10_l20_while_active_wasm",
  interp.runFile(`${g10L20WhileActiveDir}/test.ngc`),
  [
    "file_open=0",
    "file_read_count=20",
    "file_execute_count=20",
    "file_saw_error=0",
    "canon_event=SET_XY_ROTATION rotation=45",
    "canon_event=MESSAGE:  Should be -1 0: -1.000000 0.000000",
    "canon_event=MESSAGE:  Should be 0 -1: 0.000000 -1.000000",
    "canon_event=MESSAGE:  Should be 1 1: 1.000000 1.000000",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const g10WithG92Dir = writeG10RegressionFiles("g10-with-g92", ["test.ngc", "test.tbl"]);
assertG10RegressionCoverage("g10-with-g92", ["test.ngc", "test.tbl"]);
assertG10RegressionFilesStaging("g10-with-g92", ["test.ngc", "test.tbl"], g10WithG92Dir);
verifyExpectedOutput(
  "interp_g10_with_g92_wasm",
  interp.runFileWithIni(`${g10WithG92Dir}/test.ngc`, `${g10WithG92Dir}/test.ini`),
  [
    "file_open=0",
    "file_read_count=61",
    "file_execute_count=61",
    "file_saw_error=0",
    "canon_event=SET_G5X_OFFSET index=9 x=25 y=26 z=27",
    "canon_event=SET_G92_OFFSET x=-0.1 y=-0.2 z=-10.3",
    "canon_event=MESSAGE:  X0.100000 Y0.200000 Z0.300000",
    "canon_event=MESSAGE:  X-23.900000 Y-23.800000 Z-23.700000",
    "canon_event=SET_G92_OFFSET x=0 y=0 z=0",
    "canon_event=MESSAGE:  X-24.000000 Y-24.000000 Z-34.000000",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);

const g52G92InteractionPath = writeInterpRegressionFile(
  "g52/g52-g92-interaction",
  "g52-g92-interaction.ngc",
);
const g52RegressionFiles = [
  "g52-g92-interaction/g52-g92-interaction.ngc",
];
assert.deepEqual(
  g52RegressionFiles,
  interpRegressionNgcFilesRecursive("g52"),
  "interp g52 fixture coverage drift",
);
assertInterpRegressionFileStaging(
  "g52/g52-g92-interaction",
  "g52-g92-interaction.ngc",
  g52G92InteractionPath,
);
const g52G92InteractionRun = runWithCapturedPrints(() =>
  interp.runFile(g52G92InteractionPath),
);
verifyExpectedOutput(
  "interp_g52_g92_interaction_wasm",
  g52G92InteractionRun.output,
  [
    "file_open=0",
    "file_read_count=39",
    "file_execute_count=39",
    "file_saw_error=0",
    "canon_event=COMMENT: G52 and G92 param #5210 setting behavior",
    "canon_event=SET_G92_OFFSET x=-1 y=-2 z=0",
    "canon_event=SET_G92_OFFSET x=2 y=3 z=0",
    "canon_event=PALLET_SHUTTLE",
    "canon_event=PROGRAM_END",
  ].join("\n"),
);
verifyExpectedOutput(
  "interp_g52_g92_interaction_prints_wasm",
  g52G92InteractionRun.prints,
  [
    "G92 params:  1.000000 -25.400000 -50.800000",
    "G92 params:  0.000000 -25.400000 -50.800000",
    "G92 params:  1.000000 50.800000 76.200000",
    "G92 params:  1.000000 0.000000 0.000000",
  ].join("\n"),
);

const g92Persistence = writeG92PersistenceStaging(
  "/work/interp/g52/g92-persistence",
  "/work/interp/g52/g92-persistence",
);
verifyExpectedOutput(
  "interp_g92_persistence_enabled_wasm",
  runWithCapturedPrints(() =>
    interp.runFileWithIni(g92Persistence.programPath, g92Persistence.iniPath),
  ).prints,
  "Startup G92 params: 1.000000 1.250000 2.500000 3.750000",
);
verifyExpectedOutput(
  "interp_g92_persistence_disabled_wasm",
  runWithCapturedPrints(() =>
    interp.runFileWithIni(g92Persistence.programPath, g92Persistence.disabledIniPath),
  ).prints,
  "Startup G92 params: 0.000000 0.000000 0.000000 0.000000",
);

const userM110 = writeUserMCodeFixture("m110", "M110");
verifyExpectedOutput(
  "interp_user_m110_wasm",
  interp.runFileWithIni(userM110.programPath, userM110.iniPath),
  [
    "file_open=0",
    "file_read_count=2",
    "file_execute_count=2",
    "canon_event=USER_M_COMMAND code=M110",
    "canon_event=PROGRAM_END",
    "absent=Unknown m code used: M110",
  ].join("\n"),
);

const userM111 = writeUserMCodeFixture("m111", "M111");
verifyExpectedOutput(
  "interp_user_m111_wasm",
  interp.runFileWithIni(userM111.programPath, userM111.iniPath),
  [
    "file_open=0",
    "file_read_count=2",
    "file_execute_count=2",
    "canon_event=USER_M_COMMAND code=M111",
    "canon_event=PROGRAM_END",
    "absent=Unknown m code used: M111",
  ].join("\n"),
);

const parameterFilePath = writeGeneratedParameterFixture(
  "/work/rs274ngc.var",
  "/work/rs274ngc.var",
  [
    "5161 10.5",
    "5162 20.25",
    "5220 1",
    "5221 2.25",
    "5399 44",
    "<_named_param> 123",
    "",
  ].join("\n"),
);
verifyExpectedOutput(
  "restore_parameters",
  interp.restoreParameters(parameterFilePath),
  [
    "restore_parameters=0",
    "parameter_5161=10.5",
    "parameter_5162=20.25",
    "parameter_5220=1",
    "parameter_5221=2.25",
    "parameter_5399=44",
  ].join("\n"),
);
verifyExpectedOutput(
  "restore_parameters_missing_file",
  interp.restoreParameters(generatedParameterPath("/work/missing.var", "/work/missing.var")),
  "restore_parameters=0",
);

const outOfOrderParameterFilePath = writeGeneratedParameterFixture(
  "/work/out-of-order.var",
  "/work/out-of-order.var",
  "5220 1\n5161 2\n",
);
verifyExpectedOutput(
  "restore_parameters_out_of_order",
  interp.restoreParameters(outOfOrderParameterFilePath),
  [
    "restore_parameters=5",
    "restore_error_text=Parameter file out of order",
  ].join("\n"),
);

const missingRequiredParameterFilePath = writeGeneratedParameterFixture(
  "/work/missing-required.var",
  "/work/missing-required.var",
  "5161 3.5\n5220 1\n",
);
verifyExpectedOutput(
  "restore_parameters_missing_required",
  interp.restoreParameters(missingRequiredParameterFilePath),
  [
    "restore_parameters=0",
    "parameter_5161=3.5",
    "parameter_5162=0",
  ].join("\n"),
);

verifyExpectedOutput(
  "save_parameters",
  interp.saveParameters(parameterFilePath, {
    5161: 12.34,
    5162: 56.78,
    5220: 1.0,
    5221: 9.87,
    5399: 66.6,
  }),
  [
    "save_parameters=0",
    "parameter_5161=12.34",
    "parameter_5162=56.78",
    "parameter_5220=1",
    "parameter_5221=9.87",
    "parameter_5399=66.6",
  ].join("\n"),
);
const savedParameterFile = interp.readTextFile(parameterFilePath);
const backupParameterFile = interp.readTextFile(`${parameterFilePath}.bak`);
assert.equal(savedParameterFile.includes("5161\t12.340000"), true);
assert.equal(savedParameterFile.includes("5162\t56.780000"), true);
assert.equal(savedParameterFile.includes("5221\t9.870000"), true);
assert.equal(savedParameterFile.includes("5399\t66.600000"), true);
assert.equal(savedParameterFile.includes("_named_param"), false);
assert.equal(backupParameterFile.includes("5161 10.5"), true);

const toolTablePath = writeGeneratedToolTableFixture(
  "/work/tool.tbl",
  "/work/tool.tbl",
  [
    "T2 P7 Z3.125 D1.5 I12 J34 Q4 ;finish tool",
    "T5 P9 X1 Y2 Z3 ;rough tool",
    "",
  ].join("\n"),
);
verifyExpectedOutput(
  "load_tool_table",
  interp.loadToolTable(toolTablePath),
  [
    "tooldata_load=0",
    "tooldata_last_index=2",
    "tool_0.toolno=-1",
    "tool_1.toolno=2",
    "tool_1.pocketno=7",
    "tool_1.z=3.125",
    "tool_1.diameter=1.5",
    "tool_1.frontangle=12",
    "tool_1.backangle=34",
    "tool_1.orientation=4",
    "tool_1.comment=finish tool",
    "tool_2.toolno=5",
    "tool_2.pocketno=9",
    "tool_2.z=3",
    "tool_2.comment=rough tool",
    "tool_index_for_tool_2=1",
  ].join("\n"),
);
verifyExpectedOutput(
  "save_tool_table",
  interp.saveToolTable(toolTablePath),
  [
    "tooldata_save=0",
    "tool_1.toolno=2",
    "tool_2.toolno=5",
  ].join("\n"),
);
const savedToolTable = interp.readTextFile(toolTablePath);
assert.equal(savedToolTable.includes("T2"), true);
assert.equal(savedToolTable.includes("P7"), true);
assert.equal(savedToolTable.includes("D+1.500000"), true);
assert.equal(savedToolTable.includes("Z+3.125000"), true);
assert.equal(savedToolTable.includes("I+12.000000"), true);
assert.equal(savedToolTable.includes("J+34.000000"), true);
assert.equal(savedToolTable.includes("Q4"), true);
assert.equal(savedToolTable.includes(";finish tool"), true);
assert.equal(savedToolTable.includes("T5"), true);
assert.equal(savedToolTable.includes("P9"), true);
assert.equal(savedToolTable.includes(";rough tool"), true);

const randomToolTablePath = writeGeneratedToolTableFixture(
  "/work/random-tool.tbl",
  "/work/random-tool.tbl",
  [
    "T2 P7 Z3.125 D1.5 I12 J34 Q4 ;random finish tool",
    "T5 P9 X1 Y2 Z3 ;random rough tool",
    "",
  ].join("\n"),
);
verifyExpectedOutput(
  "load_tool_table_random",
  interp.loadToolTable(randomToolTablePath, { randomToolChanger: true }),
  [
    "tooldata_random_toolchanger=1",
    "tooldata_load=0",
    "tooldata_last_index=9",
    "tool_1.toolno=-1",
    "tool_2.toolno=-1",
    "tool_pocket_7.toolno=2",
    "tool_pocket_7.pocketno=7",
    "tool_pocket_7.z=3.125",
    "tool_pocket_7.diameter=1.5",
    "tool_pocket_7.frontangle=12",
    "tool_pocket_7.backangle=34",
    "tool_pocket_7.orientation=4",
    "tool_pocket_7.comment=random finish tool",
    "tool_pocket_9.toolno=5",
    "tool_pocket_9.pocketno=9",
    "tool_pocket_9.z=3",
    "tool_pocket_9.comment=random rough tool",
    "tool_index_for_tool_2=7",
  ].join("\n"),
);
verifyExpectedOutput(
  "save_tool_table_random",
  interp.saveToolTable(randomToolTablePath),
  [
    "tooldata_save=0",
    "tool_pocket_7.toolno=2",
    "tool_pocket_9.toolno=5",
  ].join("\n"),
);
const savedRandomToolTable = interp.readTextFile(randomToolTablePath);
assert.equal(savedRandomToolTable.includes("T2"), true);
assert.equal(savedRandomToolTable.includes("P7"), true);
assert.equal(savedRandomToolTable.includes(";random finish tool"), true);
assert.equal(savedRandomToolTable.includes("T5"), true);
assert.equal(savedRandomToolTable.includes("P9"), true);
assert.equal(savedRandomToolTable.includes(";random rough tool"), true);
console.log("interp_wasm_node_smoke=ok");
