"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadOpcode = void 0;
const opcodes_1 = require("./opcodes");
const codepage = opcodes_1.CP0Auto;
function loadOpcode(sc) {
    let opCode = '';
    while (sc.remainingBits > 0) {
        // Load next bit
        let opCodePart = sc.loadBit();
        opCode += opCodePart ? '1' : '0';
        // Find opcode in codepage
        // Edit maxOccurencies for debugging purposes
        let matches = codepage.find(opCode, 2);
        if (matches.length > 1) {
            continue;
        }
        if (matches.length == 1 && opCode.length !== matches[0].length) {
            continue;
        }
        if (matches.length == 0) {
            return { ok: false, read: opCode };
        }
        // Load opcode
        let op = codepage.getOp(opCode);
        // Resolve real opcode
        let resolvedOpcode;
        if (typeof op === 'function') {
            resolvedOpcode = op(sc);
        }
        else {
            resolvedOpcode = op;
        }
        return { ok: true, read: resolvedOpcode };
    }
    return { ok: false, read: opCode };
}
exports.loadOpcode = loadOpcode;
