MOS6510.java

/**
 * Cycle Accurate 6510 Emulation ----------------------------- begin                : Thu May 11 06:22:40 BST 2000
 * copyright            : (C) 2000 by Simon White email                : s_a_white@email.com
 * <p>
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either version 2 of the License or (at your option) any later
 * version.
 *
 * @author Ken Händel
 *
 */
package libsidplay.components.mos6510;

import libsidplay.common.Event;
import libsidplay.common.Event.Phase;
import libsidplay.common.EventScheduler;

import java.util.function.IntConsumer;

import static libsidplay.components.mos6510.IOpCode.*;

/**
 * Cycle-exact 6502/6510 emulation core.
 * <p>
 * Code is based on work by Simon A. White &lt;sidplay2@yahoo.com&gt; Original Java port by Ken Händel. Later on, it has
 * been hacked to improve compatibility with Lorenz suite on VICE's test suite.
 *
 * @author Antti Lankila
 */
public abstract class MOS6510 {
    /**
     * Status register interrupt bit.
     */
    public static final int SR_INTERRUPT = 2;

    /**
     * Stack page location
     */
    protected static final byte SP_PAGE = 0x01;

    /**
     * IRQ/NMI magic limit values. Need to be larger than about 0x103 &lt;&lt; 3, but can't be min/max for an Integer
     * type.
     */
    private static final int MAX = 65536;

    /**
     * The result of the ANE opcode is A = ((A | CONST) &amp; X &amp; IMM), with CONST apparently being both chip- and
     * temperature-dependent.
     * <p>
     * The commonly used value for CONST in various documents is 0xee, which is, however, not to be taken for granted
     * (as it is unstable). Current VICE uses 0xef for normal cycles and 0xee when the ANE operand fetch is affected by
     * RDY. See here:
     * <a href="http://visual6502.org/wiki/index.php?title=6502_Opcode_8B_(XAA,_ANE)">(XAA,_ANE)</a>
     */
    private static final int ANE_CONST = 0xef;

    /**
     * ANE magic constant when RDY stalls its immediate operand-fetch cycle.
     */
    private static final int ANE_RDY_CONST = 0xee;

    /**
     * ANE immediate operand fetch was stalled by RDY.
     */
    private boolean aneRdyCycle;
    private boolean shxRdyCycle;
    private boolean shyRdyCycle;
    private boolean tasRdyCycle;

    /**
     * SHA/AHX dummy-read cycle was stalled by RDY.
     * <p>
     * In this case the value written loses the usual {@code &(H+1)} term. Page-crossing address corruption still uses A
     * &amp; X &amp; (H+1).
     */
    private boolean shaRdyCycle;

    /**
     * Our event context copy.
     */
    protected final EventScheduler context;

    /**
     * RDY pin state (stop CPU on read)
     */
    private boolean rdy;

    /** Address carry settles while RDY holds an indexed/branch dummy read. */
    private boolean stalledDummyRead;

    /** RESET reads the three stack locations which IRQ/BRK would write. */
    private boolean resetStackAccess;

    /**
     * Table of CPU opcode implementations
     */
    private final Runnable[] instrTable = new Runnable[0x100 << 3];

    /**
     * true - Represents an instruction subcycle that writes. Whereas false - represents an instruction subcycle that
     * reads.
     */
    private final boolean[] processorCycleNoSteal = new boolean[instrTable.length];

    /**
     * Current instruction and subcycle within instruction
     */
    protected int cycleCount;

    /**
     * Data regarding current instruction
     */
    protected int Cycle_EffectiveAddress;
    protected int Cycle_HighByteWrongEffectiveAddress;
    protected int Register_ProgramCounter;
    protected int Cycle_Pointer;

    protected byte Cycle_Data;

    private final Runnable throwAwayReadStealable = () -> {
        cpuRead(stalledDummyRead ? Cycle_EffectiveAddress : Cycle_HighByteWrongEffectiveAddress);
        stalledDummyRead = false;
    };

    private final Runnable branchReadStealable = () -> {
        // RDY lets the unsigned carry settle; a backward branch's signed
        // high-byte correction belongs to the following cycle.
        cpuRead(stalledDummyRead && Cycle_Data >= 0
                ? Cycle_EffectiveAddress : Cycle_HighByteWrongEffectiveAddress);
        stalledDummyRead = false;
    };

    protected byte Register_Accumulator;
    protected byte Register_X;
    protected byte Register_Y;
    protected byte Register_StackPointer;

    protected boolean flagN;
    protected boolean flagC;
    protected boolean flagD;
    protected boolean flagZ;
    protected boolean flagV;
    protected boolean flagI;
    protected boolean flagU;
    protected boolean flagB;

    protected IntConsumer jmpJsr = null;

    protected abstract byte cpuRead(int address);

    protected abstract void cpuWrite(int address, byte data);

    protected boolean v(boolean v) {
        return v;
    }

    /**
     * Sample the external SO input before instructions which test or push V.
     * <p>
     * The normal C64 CPU has no external producer for this hook. The 1541 overrides it because BYTE READY is connected
     * to the drive CPU's SO pin.
     */
    protected void sampleOverflow() {
    }

    /**
     * IRQ asserted on CPU
     */
    protected boolean irqAssertedOnPin;

    /**
     * When IRQ was triggered. -MAX means "during some previous instruction", MAX means "no IRQ"
     */
    protected int interruptCycle;

    /**
     * NMI requested?
     */
    protected boolean nmiFlag;

    /**
     * RST requested?
     */
    protected boolean rstFlag;

    public void setJmpJsrHandler(final IntConsumer jmpJsr) {
        this.jmpJsr = jmpJsr;
    }

    /**
     * Set the value of a V flag (often related to the SO pin)
     *
     * @param flag new V flag state
     */
    public void setFlagV(final boolean flag) {
        flagV = flag;
    }

    /**
     * Evaluate when to execute an interrupt. Calling this method can also result in the decision that no interrupt at
     * all needs to be scheduled.
     */
    protected void calculateInterruptTriggerCycle() {
        /* Interrupt cycle not going to trigger? */
        if (interruptCycle == MAX) {
            if (rstFlag || nmiFlag || !flagI && irqAssertedOnPin) {
                interruptCycle = cycleCount;
            }
        }
    }

    /**
     * When AEC signal is high, no stealing is possible
     */
    private final Event eventWithoutSteals;

    /**
     * When AEC signal is low, steals permitted
     */
    private final Event eventWithSteals;

    /**
     * Remove a previously sampled IRQ condition after the CPU's two-cycle interrupt recognition delay.
     */
    private final Event clearInt = Event.of("Remove IRQ", event -> {
        if (!rstFlag && !nmiFlag && interruptCycle != MAX) {
            interruptCycle = MAX;
        }
    });

    /**
     * Initialize CPU Emulation (Registers)
     */
    private void Initialise() {
        // Reset stack
        Register_StackPointer = (byte) 0xff;

        // Reset Status Register
        flagU = flagB = true;
        flagN = flagC = flagD = flagV = flagZ = flagI = false;

        // Set PC to some value
        Register_ProgramCounter = 0;

        // IRQs pending check
        irqAssertedOnPin = false;
        nmiFlag = false;
        rstFlag = false;
        interruptCycle = MAX;

        // Signals
        aneRdyCycle = false;
        shaRdyCycle = false;
        shxRdyCycle = false;
        shyRdyCycle = false;
        tasRdyCycle = false;
        rdy = true;
        stalledDummyRead = false;
        resetStackAccess = false;
        context.schedule(eventWithoutSteals, 0, Phase.PHI2);
    }

    protected void interruptsAndNextOpcode() {
        if (cycleCount > interruptCycle + 2) {
            interrupt();
        } else {
            fetchNextOpcode();
        }
    }

    protected void interrupt() {
        cpuRead(Register_ProgramCounter);
        cycleCount = BRKn << 3;
        flagB = false;
        interruptCycle = MAX;
    }

    /** Called when the CPU selects the NMI vector, before reading it. */
    protected void nmiAcknowledged() {
    }

    protected void interruptEnd() {
        Register_ProgramCounter = Cycle_EffectiveAddress;
        interruptsAndNextOpcode();
    }

    protected void fetchNextOpcode() {
        cycleCount = (cpuRead(Register_ProgramCounter) & 0xff) << 3;
        Register_ProgramCounter = Register_ProgramCounter + 1 & 0xffff;

        if (!rstFlag && !nmiFlag && !(!flagI && irqAssertedOnPin)) {
            interruptCycle = MAX;
        }
        if (interruptCycle != MAX) {
            interruptCycle = -MAX;
        }
    }

    /**
     * Fetch low address byte, increment PC<BR>
     * <p>
     * Addressing Modes:
     * <UL>
     * <LI>Stack Manipulation
     * <LI>Absolute
     * <LI>Zero Page
     * <LI>Zero Page Indexed
     * <LI>Absolute Indexed
     * <LI>Absolute Indirect
     * </UL>
     */
    protected void FetchLowAddr() {
        Cycle_EffectiveAddress = cpuRead(Register_ProgramCounter) & 0xff;
        Register_ProgramCounter = Register_ProgramCounter + 1 & 0xffff;
    }

    /**
     * Read from address, add index register X to it<BR>
     * <p>
     * Addressing Modes:
     * <UL>
     * <LI>Zero Page Indexed
     * </UL>
     */
    protected void FetchLowAddrX() {
        FetchLowAddr();
        Cycle_EffectiveAddress = Cycle_EffectiveAddress + Register_X & 0xFF;
    }

    /**
     * Read from address, add index register Y to it<BR>
     * <p>
     * Addressing Modes:
     * <UL>
     * <LI>Zero Page Indexed
     * </UL>
     */
    protected void FetchLowAddrY() {
        FetchLowAddr();
        Cycle_EffectiveAddress = Cycle_EffectiveAddress + Register_Y & 0xFF;
    }

    /**
     * Fetch high address byte, increment PC (Absolute Addressing)<BR>
     * <p>
     * Low byte must have been obtained first!<BR>
     * <p>
     * Addressing Modes:
     * <UL>
     * <LI>Absolute
     * </UL>
     */
    protected void FetchHighAddr() {
        // Get the high byte of an address from memory
        Cycle_EffectiveAddress |= (cpuRead(Register_ProgramCounter) & 0xff) << 8;
        Register_ProgramCounter = Register_ProgramCounter + 1 & 0xffff;
    }

    /**
     * Fetch high byte of address, add index register X to low address byte,<BR>
     * <p>
     * increment PC<BR>
     * <p>
     * Addressing Modes:
     * <UL>
     * <LI>Absolute Indexed
     * </UL>
     */
    protected void FetchHighAddrX() {
        FetchHighAddr();
        Cycle_HighByteWrongEffectiveAddress = Cycle_EffectiveAddress & 0xff00
                | Cycle_EffectiveAddress + Register_X & 0xff;
        Cycle_EffectiveAddress = Cycle_EffectiveAddress + (Register_X & 0xff) & 0xffff;
    }

    /**
     * Fetch high byte of address, add index register Y to low address byte,<BR>
     * <p>
     * increment PC<BR>
     * <p>
     * Addressing Modes:
     * <UL>
     * <LI>Absolute Indexed
     * </UL>
     */
    protected void FetchHighAddrY() {
        FetchHighAddr();
        Cycle_HighByteWrongEffectiveAddress = Cycle_EffectiveAddress & 0xff00
                | Cycle_EffectiveAddress + Register_Y & 0xff;
        Cycle_EffectiveAddress = Cycle_EffectiveAddress + (Register_Y & 0xff) & 0xffff;
    }

    /**
     * Fetch effective address low<BR>
     * <p>
     * Addressing Modes:
     * <UL>
     * <LI>Indirect
     * <LI>Indexed Indirect (pre X)
     * <LI>Indirect indexed (post Y)
     * </UL>
     */
    protected void FetchLowEffAddr() {
        Cycle_EffectiveAddress = cpuRead(Cycle_Pointer) & 0xff;
    }

    /**
     * Fetch effective address high<BR>
     * <p>
     * Addressing Modes:
     * <UL>
     * <LI>Indirect
     * <LI>Indexed Indirect (pre X)
     * </UL>
     */
    protected void FetchHighEffAddr() {
        Cycle_Pointer = Cycle_Pointer & 0xff00 | Cycle_Pointer + 1 & 0xff;
        Cycle_EffectiveAddress |= (cpuRead(Cycle_Pointer) & 0xff) << 8;
    }

    /**
     * Fetch effective address high, add Y to low byte of effective address<BR>
     * <p>
     * Addressing Modes:
     * <UL>
     * <LI>Indirect indexed (post Y)
     * <UL>
     */
    protected void FetchHighEffAddrY() {
        FetchHighEffAddr();
        Cycle_HighByteWrongEffectiveAddress = Cycle_EffectiveAddress & 0xff00
                | Cycle_EffectiveAddress + Register_Y & 0xff;
        Cycle_EffectiveAddress = Cycle_EffectiveAddress + (Register_Y & 0xff) & 0xffff;
    }

    /**
     * Fetch pointer address low, increment PC<BR>
     * <p>
     * Addressing Modes:
     * <UL>
     * <LI>Absolute Indirect
     * <LI>Indirect indexed (post Y)
     * </UL>
     */
    protected void FetchLowPointer() {
        Cycle_Pointer = cpuRead(Register_ProgramCounter) & 0xff;
        Register_ProgramCounter = Register_ProgramCounter + 1 & 0xffff;
    }

    /**
     * Fetch pointer address high, increment PC<BR>
     * <p>
     * Addressing Modes:
     * <UL>
     * <LI>Absolute Indirect
     * </UL>
     */
    protected void FetchHighPointer() {
        Cycle_Pointer |= (cpuRead(Register_ProgramCounter) & 0xff) << 8;
        Register_ProgramCounter = Register_ProgramCounter + 1 & 0xffff;
    }

    /**
     * Write Cycle_Data to an effective address.
     */
    protected void PutEffAddrDataByte() {
        cpuWrite(Cycle_EffectiveAddress, Cycle_Data);
    }

    /**
     * Push Program Counter Low Byte on stack, decrement S
     */
    protected void PushLowPC() {
        if (resetStackAccess) {
            cpuRead(SP_PAGE << 8 | Register_StackPointer & 0xff);
        } else {
            cpuWrite(SP_PAGE << 8 | Register_StackPointer & 0xff, (byte) (Register_ProgramCounter & 0xff));
        }
        Register_StackPointer--;
    }

    /**
     * Push Program Counter High Byte on stack, decrement S
     */
    protected void PushHighPC() {
        if (resetStackAccess) {
            cpuRead(SP_PAGE << 8 | Register_StackPointer & 0xff);
        } else {
            cpuWrite(SP_PAGE << 8 | Register_StackPointer & 0xff, (byte) (Register_ProgramCounter >> 8));
        }
        Register_StackPointer--;
    }

    /**
     * Push P on stack, decrement S
     */
    protected void PushSR() {
        if (resetStackAccess) {
            cpuRead(SP_PAGE << 8 | Register_StackPointer & 0xff);
        } else {
            cpuWrite(SP_PAGE << 8 | Register_StackPointer & 0xff, getStatusRegister());
        }
        Register_StackPointer--;
    }

    /**
     * Increment stack and pull program counter low byte from stack.
     */
    protected void PopLowPC() {
        Register_StackPointer++;
        Cycle_EffectiveAddress = cpuRead(SP_PAGE << 8 | Register_StackPointer & 0xff) & 0xff;
    }

    /**
     * Increment stack and pull program counter high byte from stack.
     */
    protected void PopHighPC() {
        Register_StackPointer++;
        Cycle_EffectiveAddress |= (cpuRead(SP_PAGE << 8 | Register_StackPointer & 0xff) & 0xff) << 8;
    }

    /**
     * increment S, Pop P off stack
     */
    protected void PopSR() {
        // Get status register off stack
        Register_StackPointer++;
        setStatusRegister(cpuRead(SP_PAGE << 8 | Register_StackPointer & 0xff));
        flagB = flagU = true;
    }

    /**
     * BCD adding
     */
    protected void doADC() {
        final int C = flagC ? 1 : 0;
        final int A = Register_Accumulator & 0xff;
        final int s = Cycle_Data & 0xff;
        final int regAC2 = A + s + C;

        if (flagD) {
            // BCD mode
            int lo = (A & 0x0f) + (s & 0x0f) + C;
            int hi = (A & 0xf0) + (s & 0xf0);
            if (lo > 0x09) {
                lo += 0x06;
            }
            if (lo > 0x0f) {
                hi += 0x10;
            }

            flagZ = (regAC2 & 0xff) == 0;
            flagN = (hi & 0x80) != 0;
            flagV = v(((hi ^ A) & 0x80) != 0 && ((A ^ s) & 0x80) == 0);
            if (hi > 0x90) {
                hi += 0x60;
            }

            flagC = hi > 0xff;
            Register_Accumulator = (byte) (hi & 0xf0 | lo & 0x0f);
        } else {
            // Binary mode
            flagC = regAC2 > 0xff;
            flagV = v(((regAC2 ^ A) & 0x80) != 0 && ((A ^ s) & 0x80) == 0);
            setFlagsNZ(Register_Accumulator = (byte) regAC2);
        }
    }

    /**
     * BCD subtracting
     */
    protected void doSBC() {
        final int C = flagC ? 0 : 1;
        final int A = Register_Accumulator & 0xff;
        final int s = Cycle_Data & 0xff;
        final int regAC2 = A - s - C;

        flagC = regAC2 >= 0;
        flagV = v(((regAC2 ^ A) & 0x80) != 0 && ((A ^ s) & 0x80) != 0);
        setFlagsNZ((byte) regAC2);

        if (flagD) {
            // BCD mode
            int lo = (A & 0x0f) - (s & 0x0f) - C;
            int hi = (A & 0xf0) - (s & 0xf0);
            if ((lo & 0x10) != 0) {
                lo -= 0x06;
                hi -= 0x10;
            }
            if ((hi & 0x100) != 0) {
                hi -= 0x60;
            }
            Register_Accumulator = (byte) (hi & 0xf0 | lo & 0x0f);
        } else {
            // Binary mode
            Register_Accumulator = (byte) regAC2;
        }
    }

    private enum AccessMode {
        WRITE, READ
    }

    /**
     * Create a new CPU emu
     *
     * @param context The Event Context
     */
    public MOS6510(final EventScheduler context) {
        this.context = context;
        eventWithoutSteals = new Event("CPU-nosteal") {
            @Override
            public void event() {
                /* Run CPU until AEC goes low. */
                instrTable[cycleCount++].run();
                context.schedule(this, 1);
            }
        };
        eventWithSteals = new Event("CPU-steal") {
            @Override
            public void event() {
                /*
                 * Stall CPU when no more cycles are executable.
                 */
                if (processorCycleNoSteal[cycleCount] && !resetStackAccess) {
                    instrTable[cycleCount++].run();
                    context.schedule(this, 1);
                } else {
                    if (instrTable[cycleCount] == throwAwayReadStealable
                            || instrTable[cycleCount] == branchReadStealable) {
                        stalledDummyRead = true;
                    }
                    /*
                     * ANE/XAA has a different unstable result when RDY stalls
                     * its immediate operand-fetch cycle.
                     */
                    if (cycleCount == (ANEb << 3)) {
                        aneRdyCycle = true;
                    }

                    /*
                     * SHA/AHX drops the &(H+1) term from the value written
                     * when RDY stalls the dummy-read cycle immediately before
                     * the final write.
                     */
                    if (cycleCount == (SHAay << 3) + 2
                            || cycleCount == (SHAiy << 3) + 3) {
                        shaRdyCycle = true;
                    }
                    if (cycleCount == (SHXay << 3) + 2) {
                        shxRdyCycle = true;
                    }
                    if (cycleCount == (SHYax << 3) + 2) {
                        shyRdyCycle = true;
                    }
                    if (cycleCount == (SHSay << 3) + 2) {
                        tasRdyCycle = true;
                    }
                    /*
                     * CLI/SEI still affect the interrupt state when the CPU is
                     * stalled by RDY at their read cycle.
                     */
                    if (cycleCount == (CLIn << 3)) {
                        flagI = false;

                        if (irqAssertedOnPin && interruptCycle == MAX) {
                            interruptCycle = -MAX;
                        }

                    } else if (cycleCount == (SEIn << 3)) {
                        flagI = true;

                        if (!rstFlag && !nmiFlag
                                && cycleCount <= interruptCycle + 2) {
                            interruptCycle = MAX;
                        }
                    }
                    /*
                     * Even while stalled, the CPU can process the first clock
                     * of interrupt delay, but only that first clock.
                     */
                    if (interruptCycle == cycleCount) {
                        interruptCycle--;
                    }
                }
            }
        };
        // Initialize Processor Registers
        Register_Accumulator = 0;
        Register_X = 0;
        Register_Y = 0;

        Cycle_EffectiveAddress = 0;
        Cycle_Data = 0;

        buildInstr();
    }

    private void buildInstr() {
        final Runnable readStack = () -> cpuRead(SP_PAGE << 8 | Register_StackPointer & 0xff);

        final Runnable readPC = () -> cpuRead(Register_ProgramCounter);

        final Runnable readPC_inc = () -> {
            Cycle_Data = cpuRead(Register_ProgramCounter);
            if (flagB) {
                Register_ProgramCounter = Register_ProgramCounter + 1 & 0xffff;
            }
        };

        final Runnable fetchLowAddr = this::FetchLowAddr;

        final Runnable writeToEffectiveAddress = this::PutEffAddrDataByte;

        // ----------------------------------------------------------------------
        // Build up the processor instruction table
        for (int i = 0; i < 0x100; i++) {
            int buildCycle = i << 3;

            /*
             * So: what cycles are marked as stealable? Rules are:
             *
             * - CPU performs either read or write at every cycle. Reads are always
             * stealable. Writes are rare.
             *
             * - Every instruction begins with a sequence of reads. Writes, if any, are at
             * the end for most instructions.
             */

            AccessMode access = AccessMode.WRITE;
            boolean legalMode = true;
            boolean legalInstr = true;

            switch (i) {
                // Accumulator or Implied addressing
                case ASLn:
                case CLCn:
                case CLDn:
                case CLIn:
                case CLVn:
                case DEXn:
                case DEYn:
                case INXn:
                case INYn:
                case LSRn:
                case NOPn:
                case NOPn_1:
                case NOPn_2:
                case NOPn_3:
                case NOPn_4:
                case NOPn_5:
                case NOPn_6:
                case PHAn:
                case PHPn:
                case PLAn:
                case PLPn:
                case ROLn:
                case RORn:
                case SECn:
                case SEDn:
                case SEIn:
                case TAXn:
                case TAYn:
                case TSXn:
                case TXAn:
                case TXSn:
                case TYAn:
                    /* read the next opcode byte from memory (and throw it away) */
                    instrTable[buildCycle++] = readPC;
                    break;

                // Immediate and Relative Addressing Mode Handler
                case ADCb:
                case ANDb:
                case ANCb:
                case ANCb_1:
                case ANEb:
                case ASRb:
                case ARRb:
                case BCCr:
                case BCSr:
                case BEQr:
                case BMIr:
                case BNEr:
                case BPLr:
                case BRKn:
                case CMPb:
                case CPXb:
                case CPYb:
                case EORb:
                case LDAb:
                case LDXb:
                case LDYb:
                case LXAb:
                case NOPb:
                case NOPb_1:
                case NOPb_2:
                case NOPb_3:
                case NOPb_4:
                case ORAb:
                case RTIn:
                case RTSn:
                case SBCb:
                case SBCb_1:
                case SBXb:
                    instrTable[buildCycle++] = readPC_inc;
                    break;

                /*
                 * The 1541 BYTE READY signal is connected to the drive CPU SO input.
                 * Current VICE samples SO for BVC/BVS one CPU cycle before the branch
                 * decision (its drive core temporarily rewinds CLK by one cycle).
                 *
                 * In this cycle-exact core the relative operand fetch is that cycle.
                 */
                case BVCr:
                case BVSr:
                    instrTable[buildCycle++] = () -> {
                        readPC_inc.run();
                        sampleOverflow();
                    };
                    break;

                // Zero Page Addressing Mode Handler - Read & RMW
                case ADCz:
                case ANDz:
                case BITz:
                case CMPz:
                case CPXz:
                case CPYz:
                case EORz:
                case LAXz:
                case LDAz:
                case LDXz:
                case LDYz:
                case ORAz:
                case NOPz:
                case NOPz_1:
                case NOPz_2:
                case SBCz:
                case ASLz:
                case DCPz:
                case DECz:
                case INCz:
                case ISBz:
                case LSRz:
                case ROLz:
                case RORz:
                case SREz:
                case SLOz:
                case RLAz:
                case RRAz:
                    access = AccessMode.READ;
                    // $FALL-THROUGH$

                case SAXz:
                case STAz:
                case STXz:
                case STYz:
                    instrTable[buildCycle++] = fetchLowAddr;
                    break;

                // Zero Page with X and Y Offset Addressing Mode Handler
                // The unindexed zero-page address is read before adding X/Y.
                case ADCzx:
                case ANDzx:
                case CMPzx:
                case EORzx:
                case LDAzx:
                case LDYzx:
                case NOPzx:
                case NOPzx_1:
                case NOPzx_2:
                case NOPzx_3:
                case NOPzx_4:
                case NOPzx_5:
                case ORAzx:
                case SBCzx:
                case ASLzx:
                case DCPzx:
                case DECzx:
                case INCzx:
                case ISBzx:
                case LSRzx:
                case RLAzx:
                case ROLzx:
                case RORzx:
                case RRAzx:
                case SLOzx:
                case SREzx:
                    access = AccessMode.READ;
                    // $FALL-THROUGH$

                case STAzx:
                case STYzx:
                    instrTable[buildCycle++] = this::FetchLowAddrX;

                    instrTable[buildCycle++] = () -> cpuRead(Cycle_EffectiveAddress - Register_X & 0xff);
                    break;

                // Zero Page with Y Offset Addressing Mode Handler
                case LDXzy:
                case LAXzy:
                    access = AccessMode.READ;
                    // $FALL-THROUGH$

                case STXzy:
                case SAXzy:
                    instrTable[buildCycle++] = this::FetchLowAddrY;

                    instrTable[buildCycle++] = () -> cpuRead(Cycle_EffectiveAddress - Register_Y & 0xff);
                    break;

                // Absolute Addressing Mode Handler
                case ADCa:
                case ANDa:
                case BITa:
                case CMPa:
                case CPXa:
                case CPYa:
                case EORa:
                case LAXa:
                case LDAa:
                case LDXa:
                case LDYa:
                case NOPa:
                case ORAa:
                case SBCa:
                case ASLa:
                case DCPa:
                case DECa:
                case INCa:
                case ISBa:
                case LSRa:
                case ROLa:
                case RORa:
                case SLOa:
                case SREa:
                case RLAa:
                case RRAa:
                    access = AccessMode.READ;
                    // $FALL-THROUGH$

                case JMPw:
                case SAXa:
                case STAa:
                case STXa:
                case STYa:
                    instrTable[buildCycle++] = this::FetchLowAddr;

                    instrTable[buildCycle++] = this::FetchHighAddr;
                    break;

                case JSRw:
                    instrTable[buildCycle++] = this::FetchLowAddr;
                    break;

                // Absolute With X Offset Addressing Mode Handler (Read)
                case ADCax:
                case ANDax:
                case CMPax:
                case EORax:
                case LDAax:
                case LDYax:
                case NOPax:
                case NOPax_1:
                case NOPax_2:
                case NOPax_3:
                case NOPax_4:
                case NOPax_5:
                case ORAax:
                case SBCax:
                    access = AccessMode.READ;

                    instrTable[buildCycle++] = this::FetchLowAddr;
                    instrTable[buildCycle++] = () -> {
                        FetchHighAddrX();
                        // Handle page boundary crossing
                        if (Cycle_EffectiveAddress == Cycle_HighByteWrongEffectiveAddress) {
                            cycleCount++;
                        }
                    };

                    // this cycle is skipped if the address is already correct.
                    // otherwise, it will be read and ignored.
                    instrTable[buildCycle++] = throwAwayReadStealable;
                    break;

                // Absolute X (RMW; no page crossing handled, always reads before
                // writing)
                case ASLax:
                case DCPax:
                case DECax:
                case INCax:
                case ISBax:
                case LSRax:
                case RLAax:
                case ROLax:
                case RORax:
                case RRAax:
                case SLOax:
                case SREax:
                    access = AccessMode.READ;
                    // $FALL-THROUGH$

                case SHYax:
                case STAax:
                    instrTable[buildCycle++] = this::FetchLowAddr;

                    instrTable[buildCycle++] = this::FetchHighAddrX;

                    instrTable[buildCycle++] = throwAwayReadStealable;
                    break;

                // Absolute With Y Offset Addressing Mode Handler (Read)
                case ADCay:
                    access = AccessMode.READ;
                    instrTable[buildCycle++] = this::FetchLowAddr;

                    instrTable[buildCycle++] = () -> {
                        FetchHighAddrY();
                        if (Cycle_EffectiveAddress == Cycle_HighByteWrongEffectiveAddress) {
                            cycleCount++;
                        }
                    };

                    instrTable[buildCycle++] = throwAwayReadStealable;
                    break;
                case ANDay:
                case CMPay:
                case EORay:
                case LASay:
                case LAXay:
                case LDAay:
                case LDXay:
                case ORAay:
                case SBCay:
                    access = AccessMode.READ;
                    instrTable[buildCycle++] = this::FetchLowAddr;

                    instrTable[buildCycle++] = () -> {
                        FetchHighAddrY();
                        if (Cycle_EffectiveAddress == Cycle_HighByteWrongEffectiveAddress) {
                            cycleCount++;
                        }
                    };

                    instrTable[buildCycle++] = throwAwayReadStealable;
                    break;

                // Absolute Y (No page crossing handled)
                case DCPay:
                case ISBay:
                case RLAay:
                case RRAay:
                case SLOay:
                case SREay:
                    access = AccessMode.READ;
                    // $FALL-THROUGH$

                case SHAay:
                case SHSay:
                case SHXay:
                case STAay:
                    instrTable[buildCycle++] = this::FetchLowAddr;

                    instrTable[buildCycle++] = this::FetchHighAddrY;

                    instrTable[buildCycle++] = throwAwayReadStealable;
                    break;

                // Absolute Indirect Addressing Mode Handler
                case JMPi:
                    instrTable[buildCycle++] = this::FetchLowPointer;

                    instrTable[buildCycle++] = this::FetchHighPointer;

                    instrTable[buildCycle++] = this::FetchLowEffAddr;

                    instrTable[buildCycle++] = this::FetchHighEffAddr;
                    break;

                // Indexed with X Preinc Addressing Mode Handler
                case ADCix:
                case ANDix:
                case CMPix:
                case EORix:
                case LAXix:
                case LDAix:
                case ORAix:
                case SBCix:
                case DCPix:
                case ISBix:
                case SLOix:
                case SREix:
                case RLAix:
                case RRAix:
                    access = AccessMode.READ;
                    // $FALL-THROUGH$

                case SAXix:
                case STAix:
                    instrTable[buildCycle++] = this::FetchLowPointer;

                    instrTable[buildCycle++] = () -> {
                        cpuRead(Cycle_Pointer);
                        Cycle_Pointer = Cycle_Pointer + Register_X & 0xFF;
                    };

                    instrTable[buildCycle++] = this::FetchLowEffAddr;

                    instrTable[buildCycle++] = this::FetchHighEffAddr;
                    break;

                // Indexed with Y Postinc Addressing Mode Handler (Read)
                case ADCiy:
                case ANDiy:
                case CMPiy:
                case EORiy:
                case LAXiy:
                case LDAiy:
                case ORAiy:
                case SBCiy:
                    access = AccessMode.READ;

                    instrTable[buildCycle++] = this::FetchLowPointer;

                    instrTable[buildCycle++] = this::FetchLowEffAddr;

                    instrTable[buildCycle++] = () -> {
                        FetchHighEffAddrY();
                        if (Cycle_EffectiveAddress == Cycle_HighByteWrongEffectiveAddress) {
                            cycleCount++;
                        }
                    };

                    instrTable[buildCycle++] = throwAwayReadStealable;
                    break;

                // Indexed Y (No page crossing handled)
                case DCPiy:
                case ISBiy:
                case RLAiy:
                case RRAiy:
                case SLOiy:
                case SREiy:
                    access = AccessMode.READ;
                    // $FALL-THROUGH$

                case SHAiy:
                case STAiy:
                    instrTable[buildCycle++] = this::FetchLowPointer;

                    instrTable[buildCycle++] = this::FetchLowEffAddr;

                    instrTable[buildCycle++] = this::FetchHighEffAddrY;

                    instrTable[buildCycle++] = throwAwayReadStealable;
                    break;

                default:
                    legalMode = false;
                    break;
            }

            if (access == AccessMode.READ) {
                instrTable[buildCycle++] = () -> Cycle_Data = cpuRead(Cycle_EffectiveAddress);
            }

            // ---------------------------------------------------------------------------------------
            // Addressing Modes Finished, other cycles are instruction-
            // dependent
            switch (i) {
                case ADCz:
                case ADCzx:
                case ADCa:
                case ADCax:
                case ADCay:
                case ADCix:
                case ADCiy:
                case ADCb:
                    instrTable[buildCycle++] = () -> {
                        doADC();
                        interruptsAndNextOpcode();
                    };
                    break;

                case ANCb:
                case ANCb_1:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_Accumulator &= Cycle_Data);
                        flagC = flagN;
                        interruptsAndNextOpcode();
                    };
                    break;

                case ANDz:
                case ANDzx:
                case ANDa:
                case ANDax:
                case ANDay:
                case ANDix:
                case ANDiy:
                case ANDb:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_Accumulator &= Cycle_Data);
                        interruptsAndNextOpcode();
                    };
                    break;

                case ANEb: // Also known as XAA
                    instrTable[buildCycle++] = () -> {
                        final boolean rdyCycle = aneRdyCycle;
                        final int aneConst = rdyCycle ? ANE_RDY_CONST : ANE_CONST;
                        final int oldA = Register_Accumulator & 0xff;
                        final int oldX = Register_X & 0xff;
                        final int operand = Cycle_Data & 0xff;
                        final int result = (oldA | aneConst) & oldX & operand;

                        aneRdyCycle = false;

                        setFlagsNZ(Register_Accumulator = (byte) result);
                        interruptsAndNextOpcode();
                    };
                    break;

                case ARRb:
                    instrTable[buildCycle++] = () -> {
                        final int data = Cycle_Data & Register_Accumulator & 0xff;
                        Register_Accumulator = (byte) (data >> 1);
                        if (flagC) {
                            Register_Accumulator |= 0x80;
                        }

                        if (flagD) {
                            flagN = flagC;
                            flagZ = Register_Accumulator == 0;
                            flagV = v(((data ^ Register_Accumulator) & 0x40) != 0);

                            if ((data & 0x0f) + (data & 0x01) > 5) {
                                Register_Accumulator = (byte) (Register_Accumulator & 0xf0
                                        | Register_Accumulator + 6 & 0x0f);
                            }
                            // simplified: flagC = (data + (data & 0x10) & 0x1f0) > 0x50;
                            flagC = data >= 0x50;
                            if (flagC) {
                                Register_Accumulator = (byte) (Register_Accumulator + 0x60 & 0xff);
                            }
                        } else {
                            setFlagsNZ(Register_Accumulator);
                            flagC = (Register_Accumulator & 0x40) != 0;
                            flagV = v((Register_Accumulator & 0x40 ^ (Register_Accumulator & 0x20) << 1) != 0);
                        }
                        interruptsAndNextOpcode();
                    };
                    break;

                case ASLn:
                    instrTable[buildCycle++] = () -> {
                        flagC = Register_Accumulator < 0;
                        setFlagsNZ(Register_Accumulator <<= 1);
                        interruptsAndNextOpcode();
                    };
                    break;

                case ASLz:
                case ASLzx:
                case ASLa:
                case ASLax:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        PutEffAddrDataByte();
                        flagC = Cycle_Data < 0;
                        setFlagsNZ(Cycle_Data <<= 1);
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = writeToEffectiveAddress;
                    break;

                case ASRb: // Also known as ALR
                    instrTable[buildCycle++] = () -> {
                        Register_Accumulator &= Cycle_Data;
                        flagC = (Register_Accumulator & 0x01) != 0;
                        Register_Accumulator >>= 1;
                        Register_Accumulator &= 0x7f;
                        setFlagsNZ(Register_Accumulator);
                        interruptsAndNextOpcode();
                    };
                    break;

                case BCCr:
                case BCSr:
                case BEQr:
                case BMIr:
                case BNEr:
                case BPLr:
                case BVCr:
                case BVSr: {
                    final int _i = i;
                    instrTable[buildCycle++] = () -> {
                        final boolean condition = switch (_i) {
                            case BCSr -> flagC;
                            case BCCr -> !flagC;
                            case BEQr -> flagZ;
                            case BNEr -> !flagZ;
                            case BMIr -> flagN;
                            case BPLr -> !flagN;
                            case BVCr -> !flagV;
                            case BVSr -> flagV;
                            default -> throw new RuntimeException("non-branch opcode: " + _i);
                        };

                        /*
                         * 2 cycles spent before arriving here. spend 0 - 2 cycles here; - condition
                         * false: Continue immediately to FetchNextInstr (return true).
                         *
                         * Otherwise, read the byte following the opcode (which is already scheduled to
                         * occur on this cycle). This effort is wasted. Then calculate the address of the
                         * branch target. If the branch is on the same page, then continue at that insn on the next
                         * cycle (this delays IRQs by 1 clock for some reason, allegedly).
                         *
                         * If the branch is on a different memory page, issue a spurious read with the wrong
                         * high byte before continuing at the correct address.
                         */
                        if (condition) {
                            /* issue the spurious read for next insn here. */
                            cpuRead(Register_ProgramCounter);

                            Cycle_HighByteWrongEffectiveAddress = Register_ProgramCounter & 0xff00
                                    | Register_ProgramCounter + Cycle_Data & 0xff;
                            Cycle_EffectiveAddress = Register_ProgramCounter + Cycle_Data & 0xffff;
                            if (Cycle_EffectiveAddress == Cycle_HighByteWrongEffectiveAddress) {
                                cycleCount += 1;
                                /*
                                 * Hack: delay the interrupt past this instruction.
                                 */
                                if (interruptCycle >> 3 == cycleCount >> 3) {
                                    interruptCycle += 2;
                                }
                            }
                            Register_ProgramCounter = Cycle_EffectiveAddress;
                        } else {
                            /*
                             * the branch isn't taken: skip the following spurious read insn and go to
                             * FetchNextInstr immediately.
                             */
                            interruptsAndNextOpcode();
                        }
                    };

                    instrTable[buildCycle++] = branchReadStealable;
                    break;
                }

                case BITz:
                case BITa:
                    instrTable[buildCycle++] = () -> {
                        flagZ = (Register_Accumulator & Cycle_Data) == 0;
                        flagN = Cycle_Data < 0;
                        flagV = v((Cycle_Data & 0x40) != 0);
                        interruptsAndNextOpcode();
                    };
                    break;

                case BRKn:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = this::PushHighPC;

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        PushLowPC();
                        if (rstFlag) {
                            /* rst = %10x */
                            Cycle_EffectiveAddress = 0xfffc;
                        } else if (nmiFlag) {
                            /* nmi = %01x */
                            Cycle_EffectiveAddress = 0xfffa;
                            nmiAcknowledged();
                        } else {
                            /* irq = %11x */
                            Cycle_EffectiveAddress = 0xfffe;
                        }
                        rstFlag = false;
                        nmiFlag = false;
                        calculateInterruptTriggerCycle();
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        PushSR();
                        resetStackAccess = false;
                        flagB = true;
                        flagI = true;
                    };

                    instrTable[buildCycle++] = () -> Register_ProgramCounter = cpuRead(Cycle_EffectiveAddress) & 0xff;

                    instrTable[buildCycle++] = () -> Register_ProgramCounter |= (cpuRead(Cycle_EffectiveAddress + 1)
                            & 0xff) << 8;

                    instrTable[buildCycle++] = this::fetchNextOpcode;
                    break;

                case CLCn:
                    instrTable[buildCycle++] = () -> {
                        flagC = false;
                        interruptsAndNextOpcode();
                    };
                    break;

                case CLDn:
                    instrTable[buildCycle++] = () -> {
                        flagD = false;
                        interruptsAndNextOpcode();
                    };
                    break;

                case CLIn:
                    instrTable[buildCycle++] = () -> {
                        flagI = false;
                        calculateInterruptTriggerCycle();
                        interruptsAndNextOpcode();
                    };
                    break;

                case CLVn:
                    instrTable[buildCycle++] = () -> {
                        flagV = v(false);
                        interruptsAndNextOpcode();
                    };
                    break;

                case CMPz:
                case CMPzx:
                case CMPa:
                case CMPax:
                case CMPay:
                case CMPix:
                case CMPiy:
                case CMPb:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ((byte) (Register_Accumulator - Cycle_Data));
                        flagC = (Register_Accumulator & 0xff) >= (Cycle_Data & 0xff);
                        interruptsAndNextOpcode();
                    };
                    break;

                case CPXz:
                case CPXa:
                case CPXb:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ((byte) (Register_X - Cycle_Data));
                        flagC = (Register_X & 0xff) >= (Cycle_Data & 0xff);
                        interruptsAndNextOpcode();
                    };
                    break;

                case CPYz:
                case CPYa:
                case CPYb:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ((byte) (Register_Y - Cycle_Data));
                        flagC = (Register_Y & 0xff) >= (Cycle_Data & 0xff);
                        interruptsAndNextOpcode();
                    };
                    break;

                case DCPz:
                case DCPzx:
                case DCPa:
                case DCPax:
                case DCPay:
                case DCPix:
                case DCPiy: // Also known as DCM
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        PutEffAddrDataByte();
                        Cycle_Data--;
                        setFlagsNZ((byte) (Register_Accumulator - Cycle_Data));
                        flagC = (Register_Accumulator & 0xff) >= (Cycle_Data & 0xff);
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = writeToEffectiveAddress;
                    break;

                case DECz:
                case DECzx:
                case DECa:
                case DECax:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        PutEffAddrDataByte();
                        setFlagsNZ(--Cycle_Data);
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = writeToEffectiveAddress;
                    break;

                case DEXn:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(--Register_X);
                        interruptsAndNextOpcode();
                    };
                    break;

                case DEYn:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(--Register_Y);
                        interruptsAndNextOpcode();
                    };
                    break;

                case EORz:
                case EORzx:
                case EORa:
                case EORax:
                case EORay:
                case EORix:
                case EORiy:
                case EORb:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_Accumulator ^= Cycle_Data);
                        interruptsAndNextOpcode();
                    };
                    break;

                case INCz:
                case INCzx:
                case INCa:
                case INCax:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        PutEffAddrDataByte();
                        setFlagsNZ(++Cycle_Data);
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = writeToEffectiveAddress;
                    break;

                case INXn:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(++Register_X);
                        interruptsAndNextOpcode();
                    };
                    break;

                case INYn:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(++Register_Y);
                        interruptsAndNextOpcode();
                    };
                    break;

                case ISBz:
                case ISBzx:
                case ISBa:
                case ISBax:
                case ISBay:
                case ISBix:
                case ISBiy: // Also known as INS
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        PutEffAddrDataByte();
                        setFlagsNZ(++Cycle_Data);
                        doSBC();
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = writeToEffectiveAddress;
                    break;

                case JSRw:
                    instrTable[buildCycle++] = readStack;
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = this::PushHighPC;

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = this::PushLowPC;

                    instrTable[buildCycle++] = this::FetchHighAddr;
                    // $FALL-THROUGH$

                case JMPw:
                case JMPi:
                    instrTable[buildCycle++] = () -> {
                        Register_ProgramCounter = Cycle_EffectiveAddress;
                        if (jmpJsr != null) {
                            jmpJsr.accept(Register_ProgramCounter);
                        }
                        interruptsAndNextOpcode();
                    };
                    break;

                case LASay:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Cycle_Data &= Register_StackPointer);
                        Register_Accumulator = Cycle_Data;
                        Register_X = Cycle_Data;
                        Register_StackPointer = Cycle_Data;
                        interruptsAndNextOpcode();
                    };
                    break;

                case LAXz:
                case LAXzy:
                case LAXa:
                case LAXay:
                case LAXix:
                case LAXiy:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_Accumulator = Register_X = Cycle_Data);
                        interruptsAndNextOpcode();
                    };
                    break;

                case LDAz:
                case LDAzx:
                case LDAa:
                case LDAax:
                case LDAay:
                case LDAix:
                case LDAiy:
                case LDAb:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_Accumulator = Cycle_Data);
                        interruptsAndNextOpcode();
                    };
                    break;

                case LDXz:
                case LDXzy:
                case LDXa:
                case LDXay:
                case LDXb:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_X = Cycle_Data);
                        interruptsAndNextOpcode();
                    };
                    break;

                case LDYz:
                case LDYzx:
                case LDYa:
                case LDYax:
                case LDYb:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_Y = Cycle_Data);
                        interruptsAndNextOpcode();
                    };
                    break;

                case LSRn:
                    instrTable[buildCycle++] = () -> {
                        flagC = (Register_Accumulator & 0x01) != 0;
                        Register_Accumulator >>= 1;
                        Register_Accumulator &= 0x7f;
                        setFlagsNZ(Register_Accumulator);
                        interruptsAndNextOpcode();
                    };
                    break;

                case LSRz:
                case LSRzx:
                case LSRa:
                case LSRax:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        PutEffAddrDataByte();
                        flagC = (Cycle_Data & 0x01) != 0;
                        Cycle_Data >>= 1;
                        Cycle_Data &= 0x7f;
                        setFlagsNZ(Cycle_Data);
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = writeToEffectiveAddress;
                    break;

                case NOPn:
                case NOPn_1:
                case NOPn_2:
                case NOPn_3:
                case NOPn_4:
                case NOPn_5:
                case NOPn_6:
                case NOPb:
                case NOPb_1:
                case NOPb_2:
                case NOPb_3:
                case NOPb_4:
                case NOPz:
                case NOPz_1:
                case NOPz_2:
                case NOPzx:
                case NOPzx_1:
                case NOPzx_2:
                case NOPzx_3:
                case NOPzx_4:
                case NOPzx_5:
                case NOPa:
                case NOPax:
                case NOPax_1:
                case NOPax_2:
                case NOPax_3:
                case NOPax_4:
                case NOPax_5:
                    // NOPb NOPz NOPzx - Also known as SKBn
                    // NOPa NOPax - Also known as SKWn
                    break;

                case LXAb: // Also known as OAL
                    instrTable[buildCycle++] = () -> {
                        final int oldA = Register_Accumulator & 0xff;
                        final int operand = Cycle_Data & 0xff;
                        final int result = operand & (oldA | 0xee);

                        setFlagsNZ(Register_X = Register_Accumulator = (byte) result);
                        interruptsAndNextOpcode();
                    };
                    break;

                case ORAz:
                case ORAzx:
                case ORAa:
                case ORAax:
                case ORAay:
                case ORAix:
                case ORAiy:
                case ORAb:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_Accumulator |= Cycle_Data);
                        interruptsAndNextOpcode();
                    };
                    break;

                case PHAn:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        cpuWrite(SP_PAGE << 8 | Register_StackPointer & 0xff, Register_Accumulator);
                        Register_StackPointer--;
                    };
                    break;

                case PHPn:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        sampleOverflow();
                        PushSR();
                    };
                    break;

                case PLAn:
                    instrTable[buildCycle++] = readStack;

                    instrTable[buildCycle++] = () -> {
                        Register_StackPointer++;
                        setFlagsNZ(Register_Accumulator = cpuRead(SP_PAGE << 8 | Register_StackPointer & 0xff));
                    };
                    break;

                case PLPn:
                    instrTable[buildCycle++] = readStack;

                    instrTable[buildCycle++] = () -> {
                        PopSR();
                        calculateInterruptTriggerCycle();
                    };

                    instrTable[buildCycle++] = this::interruptsAndNextOpcode;

                    break;

                case RLAz:
                case RLAzx:
                case RLAix:
                case RLAa:
                case RLAax:
                case RLAay:
                case RLAiy:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        final boolean newC = Cycle_Data < 0;
                        PutEffAddrDataByte();
                        Cycle_Data <<= 1;
                        if (flagC) {
                            Cycle_Data |= 0x01;
                        }
                        flagC = newC;
                        setFlagsNZ(Register_Accumulator &= Cycle_Data);
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = writeToEffectiveAddress;
                    break;

                case ROLn:
                    instrTable[buildCycle++] = () -> {
                        final boolean newC = Register_Accumulator < 0;
                        Register_Accumulator <<= 1;
                        if (flagC) {
                            Register_Accumulator |= 0x01;
                        }
                        setFlagsNZ(Register_Accumulator);
                        flagC = newC;
                        interruptsAndNextOpcode();
                    };
                    break;

                case ROLz:
                case ROLzx:
                case ROLa:
                case ROLax:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        final boolean newC = Cycle_Data < 0;
                        PutEffAddrDataByte();
                        Cycle_Data <<= 1;
                        if (flagC) {
                            Cycle_Data |= 0x01;
                        }
                        setFlagsNZ(Cycle_Data);
                        flagC = newC;
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = writeToEffectiveAddress;
                    break;

                case RORn:
                    instrTable[buildCycle++] = () -> {
                        final boolean newC = (Register_Accumulator & 0x01) != 0;
                        Register_Accumulator >>= 1;
                        if (flagC) {
                            Register_Accumulator |= 0x80;
                        } else {
                            Register_Accumulator &= 0x7f;
                        }
                        setFlagsNZ(Register_Accumulator);
                        flagC = newC;
                        interruptsAndNextOpcode();
                    };
                    break;

                case RORz:
                case RORzx:
                case RORa:
                case RORax:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        final boolean newC = (Cycle_Data & 0x01) != 0;
                        PutEffAddrDataByte();
                        Cycle_Data >>= 1;
                        if (flagC) {
                            Cycle_Data |= 0x80;
                        } else {
                            Cycle_Data &= 0x7f;
                        }
                        setFlagsNZ(Cycle_Data);
                        flagC = newC;
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = writeToEffectiveAddress;
                    break;

                case RRAa:
                case RRAax:
                case RRAay:
                case RRAz:
                case RRAzx:
                case RRAix:
                case RRAiy:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        final boolean newC = (Cycle_Data & 0x01) != 0;
                        PutEffAddrDataByte();
                        Cycle_Data >>= 1;
                        if (flagC) {
                            Cycle_Data |= 0x80;
                        } else {
                            Cycle_Data &= 0x7f;
                        }
                        flagC = newC;
                        doADC();
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = writeToEffectiveAddress;
                    break;

                case RTIn:
                    instrTable[buildCycle++] = readStack;

                    instrTable[buildCycle++] = () -> {
                        PopSR();
                        calculateInterruptTriggerCycle();
                    };

                    instrTable[buildCycle++] = this::PopLowPC;

                    instrTable[buildCycle++] = this::PopHighPC;

                    instrTable[buildCycle++] = this::interruptEnd;
                    break;

                case RTSn:
                    instrTable[buildCycle++] = readStack;

                    instrTable[buildCycle++] = this::PopLowPC;

                    instrTable[buildCycle++] = this::PopHighPC;

                    instrTable[buildCycle++] = () -> {
                        cpuRead(Cycle_EffectiveAddress);
                        Register_ProgramCounter = Cycle_EffectiveAddress + 1 & 0xffff;
                    };
                    break;

                case SAXz:
                case SAXzy:
                case SAXa:
                case SAXix: // Also known as AXS
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        Cycle_Data = (byte) (Register_Accumulator & Register_X);
                        PutEffAddrDataByte();
                    };
                    break;

                case SBCz:
                case SBCzx:
                case SBCa:
                case SBCax:
                case SBCay:
                case SBCix:
                case SBCiy:
                case SBCb:
                case SBCb_1:
                    instrTable[buildCycle++] = () -> {
                        doSBC();
                        interruptsAndNextOpcode();
                    };
                    break;

                case SBXb:
                    instrTable[buildCycle++] = () -> {
                        final int tmp = (Register_X & Register_Accumulator & 0xff) - (Cycle_Data & 0xff);
                        setFlagsNZ(Register_X = (byte) tmp);
                        flagC = tmp >= 0;
                        interruptsAndNextOpcode();
                    };
                    break;

                case SECn:
                    instrTable[buildCycle++] = () -> {
                        flagC = true;
                        interruptsAndNextOpcode();
                    };
                    break;

                case SEDn:
                    instrTable[buildCycle++] = () -> {
                        flagD = true;
                        interruptsAndNextOpcode();
                    };
                    break;

                case SEIn:
                    instrTable[buildCycle++] = () -> {
                        flagI = true;
                        interruptsAndNextOpcode();
                        if (!rstFlag && !nmiFlag && interruptCycle != MAX) {
                            interruptCycle = MAX;
                        }
                    };
                    break;

                case SHAay:
                case SHAiy: // Also known as AXA
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        /*
                         * The stable value is also used for the page-crossing
                         * address corruption, even when RDY causes the stored
                         * value itself to lose the &(H+1) term.
                         */
                        final int ax = (Register_X & Register_Accumulator) & 0xff;
                        final int stableValue = ax
                                & (((Cycle_HighByteWrongEffectiveAddress >> 8) + 1) & 0xff);

                        Cycle_Data = (byte) (shaRdyCycle
                                ? ax
                                : stableValue);

                        if (Cycle_HighByteWrongEffectiveAddress != Cycle_EffectiveAddress) {
                            Cycle_EffectiveAddress = stableValue << 8
                                    | Cycle_EffectiveAddress & 0xff;
                        }

                        shaRdyCycle = false;
                        PutEffAddrDataByte();
                    };
                    break;

                case SHSay: // Also known as TAS
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        Register_StackPointer =
                                (byte) (Register_Accumulator & Register_X);

                        final int sp = Register_StackPointer & 0xff;
                        final int high = Cycle_HighByteWrongEffectiveAddress >> 8;
                        final int stableValue = sp & ((high + 1) & 0xff);

                        Cycle_Data = (byte) (tasRdyCycle ? sp : stableValue);

                        if (Cycle_HighByteWrongEffectiveAddress != Cycle_EffectiveAddress) {
                            Cycle_EffectiveAddress = stableValue << 8
                                    | Cycle_EffectiveAddress & 0xff;
                        }

                        tasRdyCycle = false;
                        PutEffAddrDataByte();
                    };
                    break;

                case SHXay: // Also known as XAS
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        final int x = Register_X & 0xff;
                        final int high = Cycle_HighByteWrongEffectiveAddress >> 8;

                        final int stableValue = x & ((high + 1) & 0xff);

                        Cycle_Data = (byte) (shxRdyCycle ? x : stableValue);

                        if (Cycle_HighByteWrongEffectiveAddress != Cycle_EffectiveAddress) {
                            Cycle_EffectiveAddress = stableValue << 8
                                    | Cycle_EffectiveAddress & 0xff;
                        }

                        shxRdyCycle = false;
                        PutEffAddrDataByte();
                    };
                    break;

                case SHYax: // Also known as SAY
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        final int y = Register_Y & 0xff;
                        final int high = Cycle_HighByteWrongEffectiveAddress >> 8;
                        final int stableValue = y & ((high + 1) & 0xff);

                        Cycle_Data = (byte) (shyRdyCycle ? y : stableValue);

                        if (Cycle_HighByteWrongEffectiveAddress != Cycle_EffectiveAddress) {
                            Cycle_EffectiveAddress = stableValue << 8
                                    | Cycle_EffectiveAddress & 0xff;
                        }

                        shyRdyCycle = false;
                        PutEffAddrDataByte();
                    };
                    break;
                case SLOz:
                case SLOzx:
                case SLOa:
                case SLOax:
                case SLOay:
                case SLOix:
                case SLOiy: // Also known as ASO
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        PutEffAddrDataByte();
                        flagC = Cycle_Data < 0;
                        Cycle_Data <<= 1;
                        setFlagsNZ(Register_Accumulator |= Cycle_Data);
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = writeToEffectiveAddress;
                    break;

                case SREz:
                case SREzx:
                case SREa:
                case SREax:
                case SREay:
                case SREix:
                case SREiy: // Also known as LSE
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        PutEffAddrDataByte();
                        flagC = (Cycle_Data & 0x01) != 0;
                        Cycle_Data >>= 1;
                        Cycle_Data &= 0x7f;
                        setFlagsNZ(Register_Accumulator ^= Cycle_Data);
                    };

                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = writeToEffectiveAddress;
                    break;

                case STAz:
                case STAzx:
                case STAa:
                case STAax:
                case STAay:
                case STAix:
                case STAiy:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        Cycle_Data = Register_Accumulator;
                        PutEffAddrDataByte();
                    };
                    break;

                case STXz:
                case STXzy:
                case STXa:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        Cycle_Data = Register_X;
                        PutEffAddrDataByte();
                    };
                    break;

                case STYz:
                case STYzx:
                case STYa:
                    processorCycleNoSteal[buildCycle] = true;
                    instrTable[buildCycle++] = () -> {
                        Cycle_Data = Register_Y;
                        PutEffAddrDataByte();
                    };
                    break;

                case TAXn:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_X = Register_Accumulator);
                        interruptsAndNextOpcode();
                    };
                    break;

                case TAYn:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_Y = Register_Accumulator);
                        interruptsAndNextOpcode();
                    };
                    break;

                case TSXn:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_X = Register_StackPointer);
                        interruptsAndNextOpcode();
                    };
                    break;

                case TXAn:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_Accumulator = Register_X);
                        interruptsAndNextOpcode();
                    };
                    break;

                case TXSn:
                    instrTable[buildCycle++] = () -> {
                        Register_StackPointer = Register_X;
                        interruptsAndNextOpcode();
                    };
                    break;

                case TYAn:
                    instrTable[buildCycle++] = () -> {
                        setFlagsNZ(Register_Accumulator = Register_Y);
                        interruptsAndNextOpcode();
                    };
                    break;

                default:
                    legalInstr = false;
                    break;
            }

            /*
             * missing an addressing mode or implementation makes opcode invalid. These are
             * normally called HLT instructions. In the hardware, the CPU state machine
             * locks up and will never recover.
             */
            if (!(legalMode && legalInstr)) {
                instrTable[buildCycle++] = () -> cycleCount--;
            }

            instrTable[buildCycle] = this::interruptsAndNextOpcode;

        }
    }

    /**
     * Force CPU to start execution at a given address
     *
     * @param address The address to start CPU execution at.
     */
    public void forcedJump(final int address) {
        cycleCount = (NOPn << 3) + 1;
        Cycle_EffectiveAddress = Register_ProgramCounter = address;
    }

    /**
     * Module Credits
     *
     * @return credit string
     */
    public static String credits() {
        return """
                MOS6510 (CPU)
                \t(©) 2000 Simon A. White
                \t(©) 2008-2010 Antti S. Lankila
                """;
    }

    /**
     * Handle bus access signal. When the RDY line is asserted, the CPU will pause when executing the next read
     * operation.
     *
     * @param rdy new state for RDY signal
     */
    public final void setRDY(final boolean rdy) {
        this.rdy = rdy;

        if (rdy) {
            context.cancel(eventWithSteals);
            context.schedule(eventWithoutSteals, 0, Phase.PHI2);
        } else {
            context.cancel(eventWithoutSteals);
            context.schedule(eventWithSteals, 0, Phase.PHI2);
        }
    }

    /**
     * This forces the CPU to abort whatever it is doing and immediately enter the RST interrupt handling sequence. The
     * implementation is not compatible: instructions actually get aborted mid-execution. However, there is no possible
     * way to trigger this signal from programs, so it's OK.
     */
    public final void triggerRST() {
        Initialise();
        resetStackAccess = true;
        cycleCount = BRKn << 3;
        rstFlag = true;
        calculateInterruptTriggerCycle();
    }

    /**
     * Trigger NMI interrupt on the CPU. Calling this method flags that CPU must enter the NMI routine at the earliest
     * opportunity. There is no way to cancel an NMI request once given.
     */
    public final void triggerNMI() {
        nmiFlag = true;
        calculateInterruptTriggerCycle();

        /* maybe process 1 clock of interrupt delay. */
        if (!rdy) {
            context.cancel(eventWithSteals);
            context.schedule(eventWithSteals, 0, Phase.PHI2);
        }
    }

    /**
     * Pull IRQ line low on CPU.
     */
    public final void triggerIRQ() {
        irqAssertedOnPin = true;
        calculateInterruptTriggerCycle();

        /* maybe process 1 clock of interrupt delay. */
        if (!rdy && interruptCycle == cycleCount) {
            context.cancel(eventWithSteals);
            context.schedule(eventWithSteals, 0, Phase.PHI2);
        }
    }

    /**
     * Inform CPU that IRQ is no longer pulled low.
     */
    public final void clearIRQ() {
        irqAssertedOnPin = false;
        context.schedule(clearInt, 2, Phase.PHI1);
    }

    /**
     * Set N and Z flag values.
     *
     * @param value to set flags from
     */
    protected final void setFlagsNZ(final byte value) {
        flagZ = value == 0;
        flagN = value < 0;
    }

    private byte getStatusRegister() {
        int sr = 0;
        if (flagN) sr |= 0x80;
        if (flagV) sr |= 0x40;
        if (flagU) sr |= 0x20;
        if (flagB) sr |= 0x10;
        if (flagD) sr |= 0x08;
        if (flagI) sr |= 0x04;
        if (flagZ) sr |= 0x02;
        if (flagC) sr |= 0x01;
        return (byte) sr;
    }

    private void setStatusRegister(final byte sr) {
        int s = sr & 0xff;
        flagC = (s & 0x01) != 0;
        flagZ = (s & 0x02) != 0;
        flagI = (s & 0x04) != 0;
        flagD = (s & 0x08) != 0;
        flagB = (s & 0x10) != 0;
        flagU = (s & 0x20) != 0;
        flagV = (s & 0x40) != 0;
        flagN = (s & 0x80) != 0;
    }

    /**
     * When stalled by BA but not yet tristated by AEC, the CPU generates read requests to the PLA chip. These reads
     * likely concern whatever byte the CPU's current subcycle would need, but full emulation can be really tricky. We
     * normally have this case only immediately after a write-opcode, and thus the next read will concern the next
     * opcode. Therefore, we fake it by reading the byte under the PC.
     *
     * @return the value under PC
     */
    public final byte getStalledOnByte() {
        return cpuRead(Register_ProgramCounter);
    }

    public final EventScheduler getEventScheduler() {
        return context;
    }

}