' =====================================================================
'  QuantumNES  -  a NES emulator written in QuantumBASIC 7.1
'
'  Plays .NES game files (iNES format).
'  Mappers: 0 NROM, 1 MMC1, 2 UxROM, 3 CNROM, 4 MMC3, 7 AxROM,
'           11 Color Dreams, 34 BNROM, 66 GxROM, 71 Camerica
'
'  Start it and pick a game from the menu, or give the game's name:
'           QuantumNES game.nes
'
'  Keys:    Arrows = D-pad     X = A     Z = B
'           Enter  = Start     Space or Tab = Select
'           Esc = Menu         P = Pause              F1 = Reset
'           F2 = Sound on/off  F11 = Full screen
'
'  Games with a battery (Zelda and others) save to name.SAV next to the
'  game file.  The recent games list is kept in QuantumNES.ini next to
'  the program.
'
'  Test switches (after the game name):
'    /NESTEST  CPU trace of nestest.nes to NESTEST.TXT
'    /BLARGG   run a blargg test ROM, its result to RESULT.TXT
'    /BENCH    900 frames as fast as possible, the speed to BENCH.TXT
'    /WAV      as /BENCH, the sound to SOUND.RAW (16-bit mono 44100 Hz)
' =====================================================================
DEFLNG A-Z

DECLARE FUNCTION Rd& (a&)
DECLARE SUB Wr (a&, v&)
DECLARE FUNCTION PpuRead& (r&)
DECLARE SUB PpuWrite (r&, v&)
DECLARE FUNCTION VramRd& (a&)
DECLARE SUB VramWr (a&, v&)
DECLARE SUB RunCpu (untilDot&)
DECLARE SUB RunFrame ()
DECLARE SUB RenderLine (y&)
DECLARE SUB BlankLine (y&)
DECLARE SUB IncY ()
DECLARE SUB A12Watch ()
DECLARE SUB DecodeChrRow (ab&)
DECLARE FUNCTION GetP& (b&)
DECLARE SUB SetP (p&)
DECLARE SUB Interrupt (vec&)
DECLARE SUB ResetNes ()
DECLARE FUNCTION LoadRom& (f$)
DECLARE SUB MapperReset ()
DECLARE SUB MapperWrite (a&, v&)
DECLARE SUB MapperScanline ()
DECLARE SUB Mmc1Apply ()
DECLARE SUB Mmc3Apply ()
DECLARE SUB SetPrg8 (slot&, bank&)
DECLARE SUB SetPrg16 (slot&, bank&)
DECLARE SUB SetPrg32 (bank&)
DECLARE SUB SetChr1 (slot&, bank&)
DECLARE SUB SetChr4 (slot&, bank&)
DECLARE SUB SetChr8 (bank&)
DECLARE SUB SetMirror (m&)
DECLARE SUB ApuWrite (a&, v&)
DECLARE FUNCTION ApuStatus& ()
DECLARE SUB ApuLine ()
DECLARE SUB ApuQuarter ()
DECLARE SUB ApuHalf ()
DECLARE SUB ReadPad ()
DECLARE SUB Present ()
DECLARE SUB InitTables ()
DECLARE SUB SaveBattery ()
DECLARE SUB PlayGame ()
DECLARE SUB OpenGame (fname$)
DECLARE SUB Splash (autoStart&)
DECLARE SUB MainMenu ()
DECLARE SUB PauseMenu ()
DECLARE SUB AddItem (t$, a$)
DECLARE FUNCTION RunMenu& (kind&, sel&)
DECLARE SUB MessageBox (m$)
DECLARE SUB ShowControls ()
DECLARE SUB UiInit ()
DECLARE SUB DrawBack ()
DECLARE SUB Logo (y&, sc&)
DECLARE SUB BigText (x&, y&, t$, sc&, col&)
DECLARE FUNCTION CenterX& (t$, sc&)
DECLARE SUB DrawPad (cx&, cy&)
DECLARE SUB RoundBox (x1&, y1&, x2&, y2&, r&, c&)
DECLARE SUB FillCircle (cx&, cy&, r&, c&)
DECLARE SUB ToggleFull ()
DECLARE SUB WaitKeysUp ()
DECLARE FUNCTION MouseClick& ()
DECLARE FUNCTION ShortName$ (f$)
DECLARE SUB AddRecent (f$)
DECLARE SUB LoadRecent ()
DECLARE SUB SaveRecent ()

' ---- CPU registers and flags --------------------------------------
' Z is (zr = 0), N is (nr AND 128); the other flags are 0 or 1.
DIM SHARED ra, rx, ry, rs, pc, fc, fi, fd, fv, zr, nr
DIM SHARED cdot              ' CPU time this frame, in PPU dots (3 per cycle)
DIM SHARED nmiPend, irqMap, irqApu, irqDmc

' ---- memory ---------------------------------------------------------
DIM SHARED ram(2047), sram(8191), vram(4095), pal(31), oam(255)
REDIM SHARED prg(0), chrMem(0), chrPix(0)
DIM SHARED prgOff(3)         ' $8000 $A000 $C000 $E000: offset into prg()
DIM SHARED chrOff(7)         ' eight 1 KB windows of the PPU pattern tables
DIM SHARED ntOff(3)          ' four nametables: offset into vram()
DIM SHARED prgSize, chrSize, chrRam, prgBanks8, chrBanks1
DIM SHARED mapper, mirrorHw, hasBattery, savFile$, sramDirty

' ---- 6502 decode tables -----------------------------------------------
DIM SHARED opIns(255), opMode(255), opCyc(255), opPen(255), opRead(255)

' ---- PPU ----------------------------------------------------------------
DIM SHARED pctrl, pmask, pstat, oamAddr, pv, pt, pfx, pw, rdBuf, ppuBus
DIM SHARED s0dot, s0done, lineDot
DIM SHARED nesRGB(63), fb(61439), bgPix(271), sprLine(255), sprList(8)
DIM SHARED bitv(7), attShift(7), lc(31)

' ---- mappers --------------------------------------------------------------
DIM SHARED m1sr, m1cnt, m1ctrl, m1chr0, m1chr1, m1prg
DIM SHARED m3sel, m3r(7), m3cnt, m3latch, m3reload, m3en

' ---- controller ---------------------------------------------------------
DIM SHARED pad1, padShift, padStrobe

' ---- APU ------------------------------------------------------------------
DIM SHARED sndRate, sndOn, sampFrac#, apuCyc#, apuStep, apuMode, apuIrqOff
DIM SHARED lenTab(31), dutyTab(31), noiseTab(15), triTab(31)
' pulse 1 and 2 (index 0, 1)
DIM SHARED pOn(1), pDuty(1), pHalt(1), pConst(1), pVol(1), pLen(1), pTimer(1)
DIM SHARED pEnvStart(1), pEnvDiv(1), pEnvDecay(1)
DIM SHARED pSwEn(1), pSwPer(1), pSwNeg(1), pSwShift(1), pSwReload(1), pSwDiv(1)
DIM SHARED pPhase#(1)
' triangle
DIM SHARED tEn, tHalt, tLinLoad, tLin, tLinReload, tLen, tTimer, tPhase#, tOut
' noise
DIM SHARED nEn, nHalt, nConst, nVol, nLen, nMode, nPeriod, nLfsr, nAcc#
DIM SHARED nEnvStart, nEnvDiv, nEnvDecay
' DMC (direct output level only)
DIM SHARED dOut
DIM SHARED hpIn#, hpOut#

' ---- display and user interface ----------------------------------------
DIM SHARED img, quitNow, grayMask, menuReq, gameOn, gameName$
DIM SHARED bgImg, uiTick, starX(89), starY(89), starV(89)
DIM SHARED msX, msY, msLast
DIM SHARED mItem$(20), mAct$(20), mCount, recent$(7), recentCount, iniFile$

' ---- test switches: /NESTEST /BLARGG /BENCH /WAV (see the top of the file)
DIM SHARED testMode, wavOut, paused, fullScr

CONST SCALE = 3
CONST SW = 768, SH = 720 ' the window: the NES picture at three times size
CONST VERSION$ = "1.0"

InitTables

' ---- the command line: a game to start, and test switches ---------------
cmd$ = LTRIM$(RTRIM$(COMMAND$))
IF INSTR(UCASE$(cmd$), "/NESTEST") THEN testMode = 1
IF INSTR(UCASE$(cmd$), "/BLARGG") THEN testMode = 2
IF INSTR(UCASE$(cmd$), "/BENCH") THEN testMode = 4
IF INSTR(UCASE$(cmd$), "/WAV") THEN testMode = 4: wavOut = 1
' remove /SWITCH words (a / that starts a word; a path may contain / too)
cmd$ = " " + cmd$
p = INSTR(cmd$, " /")
DO WHILE p > 0
    q = INSTR(p + 1, cmd$ + " ", " ")
    cmd$ = LEFT$(cmd$, p - 1) + MID$(cmd$, q)
    p = INSTR(cmd$, " /")
LOOP
rom$ = LTRIM$(RTRIM$(cmd$))
IF LEFT$(rom$, 1) = CHR$(34) THEN rom$ = MID$(rom$, 2)
IF RIGHT$(rom$, 1) = CHR$(34) THEN rom$ = LEFT$(rom$, LEN(rom$) - 1)

' ---- CPU test: nestest.nes from $C000, one trace line per instruction ---
IF testMode = 1 THEN
    IF LoadRom(rom$) THEN SYSTEM
    ResetNes
    pc = &HC000&: SetP &H24: rs = &HFD: cdot = 7 * 3
    OPEN "NESTEST.TXT" FOR OUTPUT AS #9
    FOR i = 1 TO 8991
        PRINT #9, HEX$(pc + 65536); " "; HEX$(ra + 256); " "; HEX$(rx + 256); " "; HEX$(ry + 256); " "; HEX$(GetP(0) + 256); " "; HEX$(rs + 256); cdot \ 3
        RunCpu cdot + 1
    NEXT
    CLOSE #9
    SYSTEM
END IF

' ---- the window ----------------------------------------------------------
SCREEN _NEWIMAGE(SW, SH, 32)
_TITLE "QuantumNES"
img = _NEWIMAGE(256, 240, 32)
UiInit
sndRate = _SNDRATE
sndOn = (sndRate > 0) AND testMode = 0
IF wavOut THEN
    sndRate = 44100: sndOn = -1
    OPEN "SOUND.RAW" FOR BINARY AS #7
END IF

' ---- test runs go straight to the game --------------------------------------
IF testMode THEN
    IF LoadRom(rom$) THEN SYSTEM
    ResetNes
    gameOn = 1
    PlayGame
    SYSTEM
END IF

' ---- splash, then the menus and the game ----------------------------------
Splash rom$ <> ""
IF rom$ <> "" AND quitNow = 0 THEN OpenGame rom$
' menuReq: 0 = playing, 1 = the menu over the game (Esc), 2 = the main menu
DO UNTIL quitNow
    IF gameOn = 0 OR menuReq = 2 THEN
        MainMenu
    ELSEIF menuReq THEN
        PauseMenu
    ELSE
        PlayGame
    END IF
LOOP
SaveBattery
SaveRecent
SYSTEM

' ---- NES colours (2C02), red green blue for each of the 64 -------------
NesPalette:
DATA 84,84,84, 0,30,116, 8,16,144, 48,0,136, 68,0,100, 92,0,48, 84,4,0, 60,24,0
DATA 32,42,0, 8,58,0, 0,64,0, 0,60,0, 0,50,60, 0,0,0, 0,0,0, 0,0,0
DATA 152,150,152, 8,76,196, 48,50,236, 92,30,228, 136,20,176, 160,20,100, 152,34,32, 120,60,0
DATA 84,90,0, 40,114,0, 8,124,0, 0,118,40, 0,102,120, 0,0,0, 0,0,0, 0,0,0
DATA 236,238,236, 76,154,236, 120,124,236, 176,98,236, 228,84,236, 236,88,180, 236,106,100, 212,136,32
DATA 160,170,0, 116,196,0, 76,208,32, 56,204,108, 56,180,204, 60,60,60, 0,0,0, 0,0,0
DATA 236,238,236, 168,204,236, 188,188,236, 212,178,236, 236,174,236, 236,174,212, 236,180,176, 228,196,144
DATA 204,210,120, 180,222,120, 168,226,144, 152,226,180, 160,214,228, 160,162,160, 0,0,0, 0,0,0

' ---- APU tables ----------------------------------------------------------
LengthTable:
DATA 10,254,20,2,40,4,80,6,160,8,60,10,14,12,26,14
DATA 12,16,24,18,48,20,96,22,192,24,72,26,16,28,32,30
NoiseTable:
DATA 4,8,16,32,64,96,128,160,202,254,380,508,762,1016,2034,4068
DutyTable:
DATA 0,1,0,0,0,0,0,0, 0,1,1,0,0,0,0,0, 0,1,1,1,1,0,0,0, 1,0,0,1,1,1,1,1

' ---- the Controls screen: what, which key ---------------------------------
ControlKeys:
DATA "D-pad", "Arrow keys"
DATA "A button", "X"
DATA "B button", "Z"
DATA "Start", "Enter"
DATA "Select", "Space or Tab"
DATA "Menu", "Esc"
DATA "Pause", "P"
DATA "Reset", "F1"
DATA "Sound on/off", "F2"
DATA "Full screen", "F11"
DATA "Quit", "close the window"

' 6502 opcode table: instruction*10000 + mode*100 + cycles*10 + page penalty
OpcodeTable:
DATA 550070, 260960, 690020, 610980, 560230, 260230, 320250, 610250, 450030, 260120, 321220, 650120, 560540, 260540, 320560, 610560
DATA 91120, 261051, 690020, 611080, 560340, 260340, 320360, 610360, 470020, 260741, 560020, 610770, 560641, 260641, 320670, 610670
DATA 160560, 250960, 690020, 620980, 360230, 250230, 340250, 620250, 460040, 250120, 341220, 650120, 360540, 250540, 340560, 620560
DATA 101120, 251051, 690020, 621080, 560340, 250340, 340360, 620360, 480020, 250741, 560020, 620770, 560641, 250641, 340670, 620670
DATA 540060, 270960, 690020, 630980, 560230, 270230, 330250, 630250, 430030, 270120, 331220, 660120, 150530, 270540, 330560, 630560
DATA 131120, 271051, 690020, 631080, 560340, 270340, 330360, 630360, 490020, 270741, 560020, 630770, 560641, 270641, 330670, 630670
DATA 170060, 280960, 690020, 640980, 560230, 280230, 350250, 640250, 440040, 280120, 351220, 670120, 150850, 280540, 350560, 640560
DATA 141120, 281051, 690020, 641080, 560340, 280340, 350360, 640360, 500020, 280741, 560020, 640770, 560641, 280641, 350670, 640670
DATA 560120, 20960, 560120, 580960, 60230, 20230, 40230, 580230, 210020, 560120, 380020, 750120, 60540, 20540, 40540, 580540
DATA 111120, 21060, 690020, 721060, 60340, 20340, 40440, 580440, 400020, 20750, 420020, 730750, 700650, 20650, 710750, 720750
DATA 50120, 10960, 30120, 570960, 50230, 10230, 30230, 570230, 390020, 10120, 370020, 570120, 50540, 10540, 30540, 570540
DATA 121120, 11051, 690020, 571051, 50340, 10340, 30440, 570440, 530020, 10741, 410020, 740741, 50641, 10641, 30741, 570741
DATA 240120, 220960, 560120, 590980, 240230, 220230, 310250, 590250, 190020, 220120, 200020, 680120, 240540, 220540, 310560, 590560
DATA 71120, 221051, 690020, 591080, 560340, 220340, 310360, 590360, 510020, 220741, 560020, 590770, 560641, 220641, 310670, 590670
DATA 230120, 290960, 560120, 600980, 230230, 290230, 300250, 600250, 180020, 290120, 560020, 290120, 230540, 290540, 300560, 600560
DATA 81120, 291051, 690020, 601080, 560340, 290340, 300360, 600360, 520020, 290741, 560020, 600770, 560641, 290641, 300670, 600670
' =====================================================================
'  6502 CPU
'  Runs instructions until the CPU clock (cdot, in PPU dots) reaches
'  untilDot.  Each opcode is decoded through tables: the addressing mode
'  first, then the instruction.
' =====================================================================
SUB RunCpu (untilDot)
STATIC ipoll
DO WHILE cdot < untilDot
    ' ---- interrupts ----
    ' ipoll is the I flag as the last instruction left it for polling:
    ' after CLI, SEI and PLP one more instruction runs first
    IF nmiPend = 1 THEN
        nmiPend = 0
        Interrupt &HFFFA&
    ELSEIF ipoll = 0 THEN
        IF irqMap OR irqApu OR irqDmc THEN Interrupt &HFFFE&
    END IF
    IF nmiPend = 2 THEN nmiPend = 1
    ipoll = fi

    ' ---- fetch the opcode ----
    IF pc >= 32768 THEN op = prg(prgOff((pc - 32768) \ 8192) + (pc AND 8191)) ELSE op = Rd(pc)
    pc = (pc + 1) AND 65535
    cy = opCyc(op)

    ' ---- work out the effective address (ea) ----
    SELECT CASE opMode(op)
        CASE 1 ' #immediate
            ea = pc: pc = (pc + 1) AND 65535
        CASE 2 ' zero page
            IF pc >= 32768 THEN ea = prg(prgOff((pc - 32768) \ 8192) + (pc AND 8191)) ELSE ea = Rd(pc)
            pc = (pc + 1) AND 65535
        CASE 5 ' absolute
            IF pc >= 32768 THEN lo = prg(prgOff((pc - 32768) \ 8192) + (pc AND 8191)) ELSE lo = Rd(pc)
            pc = (pc + 1) AND 65535
            IF pc >= 32768 THEN hi = prg(prgOff((pc - 32768) \ 8192) + (pc AND 8191)) ELSE hi = Rd(pc)
            pc = (pc + 1) AND 65535
            ea = lo + hi * 256
        CASE 11 ' relative (branches): ea is the offset byte
            IF pc >= 32768 THEN ea = prg(prgOff((pc - 32768) \ 8192) + (pc AND 8191)) ELSE ea = Rd(pc)
            pc = (pc + 1) AND 65535
        CASE 0, 12 ' implied, accumulator
        CASE 3 ' zero page,X
            ea = (Rd(pc) + rx) AND 255: pc = (pc + 1) AND 65535
        CASE 6 ' absolute,X
            lo = Rd(pc): hi = Rd((pc + 1) AND 65535): pc = (pc + 2) AND 65535
            b = lo + hi * 256: ea = (b + rx) AND 65535
            IF opPen(op) THEN IF (b XOR ea) AND &HFF00& THEN cy = cy + 1
        CASE 7 ' absolute,Y
            lo = Rd(pc): hi = Rd((pc + 1) AND 65535): pc = (pc + 2) AND 65535
            b = lo + hi * 256: ea = (b + ry) AND 65535
            IF opPen(op) THEN IF (b XOR ea) AND &HFF00& THEN cy = cy + 1
        CASE 10 ' (zero page),Y
            z = Rd(pc): pc = (pc + 1) AND 65535
            b = ram(z) + ram((z + 1) AND 255) * 256: ea = (b + ry) AND 65535
            IF opPen(op) THEN IF (b XOR ea) AND &HFF00& THEN cy = cy + 1
        CASE 9 ' (zero page,X)
            z = (Rd(pc) + rx) AND 255: pc = (pc + 1) AND 65535
            ea = ram(z) + ram((z + 1) AND 255) * 256
        CASE 4 ' zero page,Y
            ea = (Rd(pc) + ry) AND 255: pc = (pc + 1) AND 65535
        CASE 8 ' (indirect) - JMP only, with the 6502 page-wrap bug
            lo = Rd(pc): hi = Rd((pc + 1) AND 65535): pc = (pc + 2) AND 65535
            b = lo + hi * 256
            ea = Rd(b) + Rd((b AND &HFF00&) OR ((b + 1) AND 255)) * 256
    END SELECT

    ' ---- read the operand ----
    IF opRead(op) THEN
        IF ea < 8192 THEN
            v = ram(ea AND 2047)
        ELSEIF ea >= 32768 THEN
            v = prg(prgOff((ea - 32768) \ 8192) + (ea AND 8191))
        ELSE
            v = Rd(ea)
        END IF
    END IF

    ' ---- execute (most used first) ----
    SELECT CASE opIns(op)
        CASE 1 ' LDA
            ra = v: zr = v: nr = v
        CASE 7 ' BNE
            IF zr THEN tk = 1
        CASE 2 ' STA
            IF ea < 8192 THEN ram(ea AND 2047) = ra ELSE Wr ea, ra
        CASE 8 ' BEQ
            IF zr = 0 THEN tk = 1
        CASE 3 ' LDX
            rx = v: zr = v: nr = v
        CASE 5 ' LDY
            ry = v: zr = v: nr = v
        CASE 22 ' CMP
            t = ra - v: fc = 1 + (t < 0): zr = t AND 255: nr = zr
        CASE 16 ' JSR
            t = (pc - 1) AND 65535
            ram(256 + rs) = t \ 256: rs = (rs - 1) AND 255
            ram(256 + rs) = t AND 255: rs = (rs - 1) AND 255
            pc = ea
        CASE 17 ' RTS
            rs = (rs + 1) AND 255: lo = ram(256 + rs)
            rs = (rs + 1) AND 255: pc = (ram(256 + rs) * 256 + lo + 1) AND 65535
        CASE 18 ' INX
            rx = (rx + 1) AND 255: zr = rx: nr = rx
        CASE 21 ' DEY
            ry = (ry - 1) AND 255: zr = ry: nr = ry
        CASE 20 ' DEX
            rx = (rx - 1) AND 255: zr = rx: nr = rx
        CASE 19 ' INY
            ry = (ry + 1) AND 255: zr = ry: nr = ry
        CASE 25 ' AND
            ra = ra AND v: zr = ra: nr = ra
        CASE 9 ' BPL
            IF (nr AND 128) = 0 THEN tk = 1
        CASE 15 ' JMP
            pc = ea
        CASE 12 ' BCS
            IF fc THEN tk = 1
        CASE 11 ' BCC
            IF fc = 0 THEN tk = 1
        CASE 10 ' BMI
            IF nr AND 128 THEN tk = 1
        CASE 28 ' ADC
            t = ra + v + fc
            fv = ((ra XOR t) AND (v XOR t) AND 128) \ 128
            fc = t \ 256: ra = t AND 255: zr = ra: nr = ra
        CASE 29 ' SBC
            v = v XOR 255
            t = ra + v + fc
            fv = ((ra XOR t) AND (v XOR t) AND 128) \ 128
            fc = t \ 256: ra = t AND 255: zr = ra: nr = ra
        CASE 30 ' INC
            v = (v + 1) AND 255: zr = v: nr = v
            IF ea < 8192 THEN ram(ea AND 2047) = v ELSE Wr ea, v
        CASE 31 ' DEC
            v = (v - 1) AND 255: zr = v: nr = v
            IF ea < 8192 THEN ram(ea AND 2047) = v ELSE Wr ea, v
        CASE 26 ' ORA
            ra = ra OR v: zr = ra: nr = ra
        CASE 27 ' EOR
            ra = ra XOR v: zr = ra: nr = ra
        CASE 4 ' STX
            IF ea < 8192 THEN ram(ea AND 2047) = rx ELSE Wr ea, rx
        CASE 6 ' STY
            IF ea < 8192 THEN ram(ea AND 2047) = ry ELSE Wr ea, ry
        CASE 23 ' CPX
            t = rx - v: fc = 1 + (t < 0): zr = t AND 255: nr = zr
        CASE 24 ' CPY
            t = ry - v: fc = 1 + (t < 0): zr = t AND 255: nr = zr
        CASE 32 ' ASL
            IF opMode(op) = 12 THEN
                fc = ra \ 128: ra = (ra * 2) AND 255: zr = ra: nr = ra
            ELSE
                fc = v \ 128: v = (v * 2) AND 255: zr = v: nr = v
                IF ea < 8192 THEN ram(ea AND 2047) = v ELSE Wr ea, v
            END IF
        CASE 33 ' LSR
            IF opMode(op) = 12 THEN
                fc = ra AND 1: ra = ra \ 2: zr = ra: nr = ra
            ELSE
                fc = v AND 1: v = v \ 2: zr = v: nr = v
                IF ea < 8192 THEN ram(ea AND 2047) = v ELSE Wr ea, v
            END IF
        CASE 34 ' ROL
            IF opMode(op) = 12 THEN
                t = ra * 2 + fc: fc = t \ 256: ra = t AND 255: zr = ra: nr = ra
            ELSE
                t = v * 2 + fc: fc = t \ 256: v = t AND 255: zr = v: nr = v
                IF ea < 8192 THEN ram(ea AND 2047) = v ELSE Wr ea, v
            END IF
        CASE 35 ' ROR
            IF opMode(op) = 12 THEN
                t = ra + fc * 256: fc = ra AND 1: ra = t \ 2: zr = ra: nr = ra
            ELSE
                t = v + fc * 256: fc = v AND 1: v = t \ 2: zr = v: nr = v
                IF ea < 8192 THEN ram(ea AND 2047) = v ELSE Wr ea, v
            END IF
        CASE 36 ' BIT
            zr = ra AND v: nr = v: fv = (v \ 64) AND 1
        CASE 37 ' TAX
            rx = ra: zr = rx: nr = rx
        CASE 39 ' TAY
            ry = ra: zr = ry: nr = ry
        CASE 38 ' TXA
            ra = rx: zr = ra: nr = ra
        CASE 40 ' TYA
            ra = ry: zr = ra: nr = ra
        CASE 43 ' PHA
            ram(256 + rs) = ra: rs = (rs - 1) AND 255
        CASE 44 ' PLA
            rs = (rs + 1) AND 255: ra = ram(256 + rs): zr = ra: nr = ra
        CASE 47 ' CLC
            fc = 0
        CASE 48 ' SEC
            fc = 1
        CASE 13 ' BVC
            IF fv = 0 THEN tk = 1
        CASE 14 ' BVS
            IF fv THEN tk = 1
        CASE 54 ' RTI
            rs = (rs + 1) AND 255: SetP ram(256 + rs)
            rs = (rs + 1) AND 255: lo = ram(256 + rs)
            rs = (rs + 1) AND 255: pc = ram(256 + rs) * 256 + lo
        CASE 45 ' PHP
            ram(256 + rs) = GetP(16): rs = (rs - 1) AND 255
        CASE 46 ' PLP
            rs = (rs + 1) AND 255: SetP ram(256 + rs)
        CASE 41 ' TSX
            rx = rs: zr = rx: nr = rx
        CASE 42 ' TXS
            rs = rx
        CASE 50 ' SEI
            fi = 1
        CASE 49 ' CLI
            fi = 0
        CASE 51 ' CLD
            fd = 0
        CASE 52 ' SED
            fd = 1
        CASE 53 ' CLV
            fv = 0
        CASE 56 ' NOP (and the unofficial NOPs)
        CASE 55 ' BRK
            pc = (pc + 1) AND 65535
            ram(256 + rs) = pc \ 256: rs = (rs - 1) AND 255
            ram(256 + rs) = pc AND 255: rs = (rs - 1) AND 255
            ram(256 + rs) = GetP(16): rs = (rs - 1) AND 255
            fi = 1
            pc = Rd(&HFFFE&) + Rd(&HFFFF&) * 256
        ' ---- unofficial opcodes some games use ----
        CASE 57 ' LAX
            ra = v: rx = v: zr = v: nr = v
        CASE 58 ' SAX
            IF ea < 8192 THEN ram(ea AND 2047) = ra AND rx ELSE Wr ea, ra AND rx
        CASE 59 ' DCP
            v = (v - 1) AND 255
            IF ea < 8192 THEN ram(ea AND 2047) = v ELSE Wr ea, v
            t = ra - v: fc = 1 + (t < 0): zr = t AND 255: nr = zr
        CASE 60 ' ISB
            v = (v + 1) AND 255
            IF ea < 8192 THEN ram(ea AND 2047) = v ELSE Wr ea, v
            v = v XOR 255
            t = ra + v + fc
            fv = ((ra XOR t) AND (v XOR t) AND 128) \ 128
            fc = t \ 256: ra = t AND 255: zr = ra: nr = ra
        CASE 61 ' SLO
            fc = v \ 128: v = (v * 2) AND 255
            IF ea < 8192 THEN ram(ea AND 2047) = v ELSE Wr ea, v
            ra = ra OR v: zr = ra: nr = ra
        CASE 62 ' RLA
            t = v * 2 + fc: fc = t \ 256: v = t AND 255
            IF ea < 8192 THEN ram(ea AND 2047) = v ELSE Wr ea, v
            ra = ra AND v: zr = ra: nr = ra
        CASE 63 ' SRE
            fc = v AND 1: v = v \ 2
            IF ea < 8192 THEN ram(ea AND 2047) = v ELSE Wr ea, v
            ra = ra XOR v: zr = ra: nr = ra
        CASE 64 ' RRA
            t = v + fc * 256: fc = v AND 1: v = t \ 2
            IF ea < 8192 THEN ram(ea AND 2047) = v ELSE Wr ea, v
            t = ra + v + fc
            fv = ((ra XOR t) AND (v XOR t) AND 128) \ 128
            fc = t \ 256: ra = t AND 255: zr = ra: nr = ra
        CASE 65 ' ANC
            ra = ra AND v: zr = ra: nr = ra: fc = ra \ 128
        CASE 66 ' ALR
            ra = ra AND v: fc = ra AND 1: ra = ra \ 2: zr = ra: nr = ra
        CASE 67 ' ARR
            ra = ((ra AND v) \ 2) OR (fc * 128): zr = ra: nr = ra
            fc = (ra \ 64) AND 1: fv = ((ra \ 64) XOR (ra \ 32)) AND 1
        CASE 68 ' AXS
            t = (ra AND rx) - v: fc = 1 + (t < 0): rx = t AND 255: zr = rx: nr = rx
        CASE 74 ' LAS
            t = v AND rs: ra = t: rx = t: rs = t: zr = t: nr = t
        CASE 75 ' XAA
            ra = rx AND v: zr = ra: nr = ra
        CASE 69 ' KIL: the CPU stops
            pc = (pc - 1) AND 65535
        CASE 70, 71, 72, 73 ' SHY SHX AHX TAS: store a register AND (high byte + 1)
            SELECT CASE opIns(op)
                CASE 70: t = ry
                CASE 71: t = rx
                CASE 72: t = ra AND rx
                CASE 73: rs = ra AND rx: t = rs
            END SELECT
            t = t AND ((b \ 256 + 1) AND 255)
            IF (b XOR ea) AND &HFF00& THEN ea = t * 256 + (ea AND 255)
            Wr ea, t
    END SELECT

    ' ---- a branch that was taken ----
    IF tk THEN
        tk = 0
        t = (pc + ea - (ea AND 128) * 2) AND 65535
        IF (t XOR pc) AND &HFF00& THEN cy = cy + 2 ELSE cy = cy + 1
        pc = t
    END IF

    SELECT CASE opIns(op)
        CASE 49, 50, 46 ' CLI SEI PLP: polled with the old I flag
        CASE ELSE: ipoll = fi
    END SELECT
    cdot = cdot + cy * 3
LOOP
END SUB

' the status register as a byte (b = 16 for BRK and PHP)
FUNCTION GetP (b)
    p = 32 OR b OR fc OR fi * 4 OR fd * 8 OR fv * 64
    IF zr = 0 THEN p = p OR 2
    IF nr AND 128 THEN p = p OR 128
    GetP = p
END FUNCTION

SUB SetP (p)
    fc = p AND 1
    zr = (p AND 2) XOR 2
    fi = (p \ 4) AND 1
    fd = (p \ 8) AND 1
    fv = (p \ 64) AND 1
    nr = p AND 128
END SUB

' NMI ($FFFA) or IRQ ($FFFE)
SUB Interrupt (vec)
    ram(256 + rs) = pc \ 256: rs = (rs - 1) AND 255
    ram(256 + rs) = pc AND 255: rs = (rs - 1) AND 255
    ram(256 + rs) = GetP(0): rs = (rs - 1) AND 255
    fi = 1
    pc = Rd(vec) + Rd(vec + 1) * 256
    cdot = cdot + 21
END SUB

' =====================================================================
'  CPU memory map
' =====================================================================
FUNCTION Rd (a)
    IF a < 8192 THEN Rd = ram(a AND 2047): EXIT FUNCTION
    IF a >= 32768 THEN Rd = prg(prgOff((a - 32768) \ 8192) + (a AND 8191)): EXIT FUNCTION
    IF a < 16384 THEN Rd = PpuRead(a AND 7): EXIT FUNCTION
    IF a >= 24576 THEN Rd = sram(a - 24576): EXIT FUNCTION
    SELECT CASE a
        CASE &H4016 ' controller 1: one button per read, A B Select Start Up Down Left Right
            IF padStrobe THEN
                v = pad1 AND 1
            ELSE
                v = padShift AND 1: padShift = (padShift \ 2) OR 128
            END IF
            Rd = v OR &H40
        CASE &H4015
            Rd = ApuStatus
        CASE &H4017 ' no controller 2
            Rd = &H40
        CASE ELSE ' open bus
            Rd = a \ 256
    END SELECT
END FUNCTION

SUB Wr (a, v)
    IF a < 8192 THEN ram(a AND 2047) = v: EXIT SUB
    IF a < 16384 THEN PpuWrite a AND 7, v: EXIT SUB
    IF a >= 32768 THEN MapperWrite a, v: EXIT SUB
    IF a >= 24576 THEN sram(a - 24576) = v: sramDirty = 1: EXIT SUB
    IF a = &H4014 THEN
        ' sprite DMA: 256 bytes from page v into OAM, 513 CPU cycles
        pg = v * 256
        FOR i = 0 TO 255
            IF pg < 8192 THEN
                oam((oamAddr + i) AND 255) = ram((pg + i) AND 2047)
            ELSE
                oam((oamAddr + i) AND 255) = Rd(pg + i)
            END IF
        NEXT
        cdot = cdot + 513 * 3
        EXIT SUB
    END IF
    IF a = &H4016 THEN
        IF v AND 1 THEN
            padStrobe = 1: padShift = pad1
        ELSE
            IF padStrobe THEN padShift = pad1
            padStrobe = 0
        END IF
        EXIT SUB
    END IF
    IF a < &H4018 THEN ApuWrite a, v
END SUB

' =====================================================================
'  PPU (picture)
'  The picture is drawn one scanline at a time.  A frame is 262 lines
'  of 341 dots; the CPU runs one cycle for every 3 dots.
' =====================================================================
SUB RunFrame
    STATIC oddFrame
    s0dot = -1: s0done = 0
    FOR y = 0 TO 239
        lineDot = y * 341
        IF pmask AND 24 THEN RenderLine y ELSE BlankLine y
        RunCpu lineDot + 257
        IF pmask AND 24 THEN
            IncY
            pv = (pv AND &H7BE0) OR (pt AND &H41F) ' horizontal scroll from t
            MapperScanline
        END IF
        RunCpu lineDot + 341
        IF s0dot >= 0 THEN pstat = pstat OR 64: s0dot = -1
        ApuLine
    NEXT

    ' line 240 is idle, vertical blank starts on line 241
    RunCpu 241 * 341 + 1
    ApuLine
    pstat = pstat OR 128
    IF pctrl AND 128 THEN nmiPend = 1
    FOR y = 241 TO 260
        RunCpu (y + 1) * 341
        ApuLine
    NEXT

    ' pre-render line 261
    pstat = pstat AND &H1F
    RunCpu 261 * 341 + 257
    IF pmask AND 24 THEN
        pv = (pv AND &H7BE0) OR (pt AND &H41F)
        MapperScanline
    END IF
    RunCpu 261 * 341 + 304
    IF pmask AND 24 THEN pv = (pv AND &H41F) OR (pt AND &H7BE0) ' vertical scroll from t
    ' odd frames are one dot shorter while rendering
    oddFrame = 1 - oddFrame
    lastDot = 262 * 341
    IF oddFrame = 1 AND (pmask AND 24) <> 0 THEN lastDot = lastDot - 1
    RunCpu lastDot
    ApuLine
    cdot = cdot - lastDot
END SUB

' fine Y + 1, into the next row of tiles and the next nametable down
SUB IncY
    IF (pv AND &H7000) <> &H7000 THEN
        pv = pv + &H1000
    ELSE
        pv = pv AND &HFFF
        cy = (pv AND &H3E0) \ 32
        IF cy = 29 THEN
            cy = 0: pv = pv XOR &H800
        ELSEIF cy = 31 THEN
            cy = 0
        ELSE
            cy = cy + 1
        END IF
        pv = (pv AND &H7C1F) OR (cy * 32)
    END IF
END SUB

' rendering off: the backdrop colour
SUB BlankLine (y)
    c = nesRGB(pal(0) AND grayMask)
    o = y * 256
    FOR x = 0 TO 255
        IF fb(o + x) <> c THEN fb(o + x) = c: PSET (x, y), c
    NEXT
END SUB

SUB RenderLine (y)
    ' ---- background: 33 tiles, shifted left by fine X ----
    IF pmask AND 8 THEN
        cx = pv AND 31: cyy = (pv \ 32) AND 31: fy = (pv \ 4096) AND 7
        nt = (pv \ 1024) AND 3
        bgBase = (pctrl AND 16) * 256
        x = 8 - pfx
        FOR i = 0 TO 32
            ntb = ntOff(nt)
            tile = vram(ntb + cyy * 32 + cx)
            at = vram(ntb + 960 + (cyy \ 4) * 8 + (cx \ 4))
            ph = ((at \ attShift((cyy AND 2) * 2 + (cx AND 2))) AND 3) * 4
            pa = bgBase + tile * 16 + fy
            ab = chrOff(pa \ 1024) + (pa AND 1023)
            d = (ab \ 16) * 64 + (ab AND 7) * 8
            FOR k = 0 TO 7
                p = chrPix(d + k)
                IF p THEN bgPix(x) = ph + p ELSE bgPix(x) = 0
                x = x + 1
            NEXT
            cx = cx + 1
            IF cx = 32 THEN cx = 0: nt = nt XOR 1
        NEXT
        IF (pmask AND 2) = 0 THEN FOR x = 8 TO 15: bgPix(x) = 0: NEXT
    ELSE
        FOR x = 8 TO 263: bgPix(x) = 0: NEXT
    END IF

    ' ---- this line's 32 palette entries as screen colours ----
    FOR i = 0 TO 31: lc(i) = nesRGB(pal(i) AND grayMask): NEXT

    ' ---- sprites: up to 8 on this line ----
    cnt = 0
    IF pmask AND 16 THEN
        h = 8: IF pctrl AND 32 THEN h = 16
        FOR n = 0 TO 63
            row = y - oam(n * 4) - 1
            IF row >= 0 AND row < h THEN
                IF cnt = 8 THEN pstat = pstat OR 32: EXIT FOR
                cnt = cnt + 1: sprList(cnt) = n
            END IF
        NEXT
    END IF

    o = y * 256
    IF cnt = 0 THEN
        ' no sprites: background only
        FOR x = 0 TO 255
            c = lc(bgPix(x + 8))
            IF fb(o + x) <> c THEN fb(o + x) = c: PSET (x, y), c
        NEXT
        EXIT SUB
    END IF

    ' lowest number drawn last, so it ends up in front
    FOR x = 0 TO 255: sprLine(x) = 0: NEXT
    FOR j = cnt TO 1 STEP -1
        n = sprList(j): so = n * 4
        tile = oam(so + 1): at = oam(so + 2): sx = oam(so + 3)
        row = y - oam(so) - 1
        IF at AND 128 THEN row = h - 1 - row
        IF h = 16 THEN
            sb = (tile AND 1) * 4096: tile = tile AND 254
            IF row >= 8 THEN tile = tile + 1: row = row - 8
        ELSE
            sb = (pctrl AND 8) * 512
        END IF
        pa = sb + tile * 16 + row
        ab = chrOff(pa \ 1024) + (pa AND 1023)
        d = (ab \ 16) * 64 + (ab AND 7) * 8
        fl = 16 + (at AND 3) * 4
        IF at AND 32 THEN fl = fl + 256 ' behind the background
        IF n = 0 THEN fl = fl + 512 ' sprite 0
        FOR k = 0 TO 7
            IF at AND 64 THEN p = chrPix(d + 7 - k) ELSE p = chrPix(d + k)
            IF p THEN
                x = sx + k
                IF x < 256 THEN sprLine(x) = fl + p
            END IF
        NEXT
    NEXT
    IF (pmask AND 4) = 0 THEN FOR x = 0 TO 7: sprLine(x) = 0: NEXT

    ' ---- mix and draw ----
    FOR x = 0 TO 255
        b = bgPix(x + 8)
        s = sprLine(x)
        IF s THEN
            IF s AND 512 THEN
                IF b THEN
                    IF s0done = 0 AND x < 255 THEN s0done = 1: s0dot = y * 341 + x + 2
                END IF
            END IF
            IF b = 0 OR (s AND 256) = 0 THEN c = lc(s AND 31) ELSE c = lc(b)
        ELSE
            c = lc(b)
        END IF
        IF fb(o + x) <> c THEN fb(o + x) = c: PSET (x, y), c
    NEXT
END SUB

' ---- PPU registers $2000-$2007 -------------------------------------------
FUNCTION PpuRead (r)
    SELECT CASE r
        CASE 2
            IF s0dot >= 0 THEN
                IF cdot >= s0dot THEN pstat = pstat OR 64: s0dot = -1
            END IF
            v = (pstat AND &HE0) OR (ppuBus AND &H1F)
            pstat = pstat AND &H7F: pw = 0
        CASE 4
            v = oam(oamAddr)
        CASE 7
            a = pv AND &H3FFF
            IF a < &H3F00 THEN
                v = rdBuf: rdBuf = VramRd(a)
            ELSE
                v = (VramRd(a) AND 63) OR (ppuBus AND &HC0)
                rdBuf = VramRd(a - 4096)
            END IF
            IF pctrl AND 4 THEN pv = (pv + 32) AND &H7FFF ELSE pv = (pv + 1) AND &H7FFF
            A12Watch
        CASE ELSE
            v = ppuBus
    END SELECT
    ppuBus = v
    PpuRead = v
END FUNCTION

SUB PpuWrite (r, v)
    ppuBus = v
    SELECT CASE r
        CASE 0
            ' NMI turned on during vblank: it comes after the next instruction
            IF (pctrl AND 128) = 0 AND (v AND 128) <> 0 AND (pstat AND 128) <> 0 THEN nmiPend = 2
            pctrl = v
            pt = (pt AND &H73FF) OR ((v AND 3) * 1024)
        CASE 1
            pmask = v
            IF v AND 1 THEN grayMask = &H30 ELSE grayMask = 63
        CASE 3
            oamAddr = v
        CASE 4
            oam(oamAddr) = v: oamAddr = (oamAddr + 1) AND 255
        CASE 5
            IF pw = 0 THEN
                pfx = v AND 7: pt = (pt AND &H7FE0) OR (v \ 8): pw = 1
            ELSE
                pt = (pt AND &HC1F) OR ((v AND 7) * 4096) OR ((v AND &HF8) * 4): pw = 0
            END IF
        CASE 6
            IF pw = 0 THEN
                pt = (pt AND &HFF) OR ((v AND &H3F) * 256): pw = 1
            ELSE
                pt = (pt AND &H7F00) OR v: pv = pt: pw = 0
                A12Watch
            END IF
        CASE 7
            VramWr pv AND &H3FFF, v
            IF pctrl AND 4 THEN pv = (pv + 32) AND &H7FFF ELSE pv = (pv + 1) AND &H7FFF
            A12Watch
    END SELECT
END SUB

' With rendering off, the MMC3 counts rises of PPU address line A12 made
' through $2006/$2007 (while rendering it is clocked once per scanline).
SUB A12Watch
    STATIC lastA12
    IF mapper <> 4 THEN EXIT SUB
    a12 = pv AND &H1000
    IF a12 <> 0 AND lastA12 = 0 AND (pmask AND 24) = 0 THEN MapperScanline
    lastA12 = a12
END SUB

' ---- PPU memory: pattern tables, nametables, palette -------------------
FUNCTION VramRd (a)
    IF a < 8192 THEN
        VramRd = chrMem(chrOff(a \ 1024) + (a AND 1023))
    ELSEIF a < &H3F00 THEN
        VramRd = vram(ntOff((a \ 1024) AND 3) + (a AND 1023))
    ELSE
        i = a AND 31
        IF (i AND 19) = 16 THEN i = i AND 15
        VramRd = pal(i) AND grayMask
    END IF
END FUNCTION

SUB VramWr (a, v)
    IF a < 8192 THEN
        IF chrRam THEN
            ab = chrOff(a \ 1024) + (a AND 1023)
            chrMem(ab) = v
            DecodeChrRow ab
        END IF
    ELSEIF a < &H3F00 THEN
        vram(ntOff((a \ 1024) AND 3) + (a AND 1023)) = v
    ELSE
        i = a AND 31
        IF (i AND 19) = 16 THEN i = i AND 15
        pal(i) = v AND 63
    END IF
END SUB

' one 8-pixel row of a tile, unpacked to colour numbers 0-3
SUB DecodeChrRow (ab)
    tb = ab AND (NOT 15)
    row = ab AND 7
    lo = chrMem(tb + row): hi = chrMem(tb + row + 8)
    d = (tb \ 16) * 64 + row * 8
    FOR k = 0 TO 7
        p = 0
        IF lo AND bitv(k) THEN p = 1
        IF hi AND bitv(k) THEN p = p + 2
        chrPix(d + k) = p
    NEXT
END SUB

SUB Present
    _DEST 0
    _PUTIMAGE (0, 0)-(256 * SCALE - 1, 240 * SCALE - 1), img
    _DISPLAY
    _DEST img
END SUB

' =====================================================================
'  Cartridge: loading, mappers (bank switching), battery saves
' =====================================================================
FUNCTION LoadRom (f$)
    IF NOT _FILEEXISTS(f$) THEN LoadRom = 1: EXIT FUNCTION
    OPEN f$ FOR BINARY AS #1
    h$ = SPACE$(16)
    GET #1, , h$
    IF LEFT$(h$, 4) <> "NES" + CHR$(26) THEN CLOSE #1: LoadRom = 2: EXIT FUNCTION
    prgSize = ASC(h$, 5) * 16384
    chrSize = ASC(h$, 6) * 8192
    f6 = ASC(h$, 7): f7 = ASC(h$, 8)
    mapper = f6 \ 16
    ' the high mapper bits, unless the header ends in junk ("DiskDude!")
    IF (f7 AND 12) = 8 OR (ASC(h$, 13) = 0 AND ASC(h$, 14) = 0 AND ASC(h$, 15) = 0 AND ASC(h$, 16) = 0) THEN
        mapper = mapper OR (f7 AND &HF0)
    END IF
    IF f6 AND 8 THEN mirrorHw = 4 ELSE mirrorHw = f6 AND 1
    hasBattery = (f6 \ 2) AND 1
    SELECT CASE mapper
        CASE 0, 1, 2, 3, 4, 7, 11, 34, 66, 71
        CASE ELSE
            CLOSE #1: LoadRom = 3: EXIT FUNCTION
    END SELECT

    ' a new game: the old game's battery RAM is gone
    FOR i = 0 TO 8191: sram(i) = 0: NEXT
    sramDirty = 0

    IF f6 AND 4 THEN ' 512-byte trainer, loaded at $7000
        t$ = SPACE$(512): GET #1, , t$
        FOR i = 0 TO 511: sram(4096 + i) = ASC(t$, i + 1): NEXT
    END IF

    REDIM prg(prgSize - 1)
    b$ = SPACE$(prgSize): GET #1, , b$
    FOR i = 0 TO prgSize - 1: prg(i) = ASC(b$, i + 1): NEXT

    chrRam = 0
    IF chrSize = 0 THEN chrRam = 1: chrSize = 8192
    REDIM chrMem(chrSize - 1), chrPix(chrSize * 4 - 1)
    IF chrRam = 0 THEN
        b$ = SPACE$(chrSize): GET #1, , b$
        FOR i = 0 TO chrSize - 1: chrMem(i) = ASC(b$, i + 1): NEXT
        FOR i = 0 TO chrSize - 1 STEP 16
            FOR r = 0 TO 7: DecodeChrRow i + r: NEXT
        NEXT
    END IF
    b$ = ""
    CLOSE #1

    prgBanks8 = prgSize \ 8192
    chrBanks1 = chrSize \ 1024

    ' battery-backed RAM: name.SAV next to the game
    savFile$ = f$
    d = INSTR(savFile$, ".")
    DO WHILE INSTR(d + 1, savFile$, ".") > 0: d = INSTR(d + 1, savFile$, "."): LOOP
    IF d > 0 AND d > LEN(savFile$) - 5 THEN savFile$ = LEFT$(savFile$, d - 1)
    savFile$ = savFile$ + ".SAV"
    IF hasBattery AND _FILEEXISTS(savFile$) THEN
        OPEN savFile$ FOR BINARY AS #1
        IF LOF(1) >= 8192 THEN
            b$ = SPACE$(8192): GET #1, , b$
            FOR i = 0 TO 8191: sram(i) = ASC(b$, i + 1): NEXT
        END IF
        CLOSE #1
    END IF
    LoadRom = 0
END FUNCTION

SUB SaveBattery
    IF hasBattery = 0 OR sramDirty = 0 THEN EXIT SUB
    b$ = SPACE$(8192)
    FOR i = 0 TO 8191: MID$(b$, i + 1, 1) = CHR$(sram(i)): NEXT
    OPEN savFile$ FOR BINARY AS #1
    PUT #1, 1, b$
    CLOSE #1
END SUB

' ---- bank helpers: bank numbers wrap to the ROM size; -1 = the last ----
SUB SetPrg8 (slot, bank)
    b = bank MOD prgBanks8
    IF b < 0 THEN b = b + prgBanks8
    prgOff(slot) = b * 8192
END SUB

SUB SetPrg16 (slot, bank)
    SetPrg8 slot * 2, bank * 2
    SetPrg8 slot * 2 + 1, bank * 2 + 1
END SUB

SUB SetPrg32 (bank)
    SetPrg16 0, bank * 2
    SetPrg16 1, bank * 2 + 1
END SUB

SUB SetChr1 (slot, bank)
    b = bank MOD chrBanks1
    IF b < 0 THEN b = b + chrBanks1
    chrOff(slot) = b * 1024
END SUB

SUB SetChr4 (slot, bank)
    FOR i = 0 TO 3: SetChr1 slot * 4 + i, bank * 4 + i: NEXT
END SUB

SUB SetChr8 (bank)
    SetChr4 0, bank * 2
    SetChr4 1, bank * 2 + 1
END SUB

' 0 horizontal, 1 vertical, 2 one-screen A, 3 one-screen B, 4 four-screen
SUB SetMirror (m)
    SELECT CASE m
        CASE 0: ntOff(0) = 0: ntOff(1) = 0: ntOff(2) = 1024: ntOff(3) = 1024
        CASE 1: ntOff(0) = 0: ntOff(1) = 1024: ntOff(2) = 0: ntOff(3) = 1024
        CASE 2: ntOff(0) = 0: ntOff(1) = 0: ntOff(2) = 0: ntOff(3) = 0
        CASE 3: ntOff(0) = 1024: ntOff(1) = 1024: ntOff(2) = 1024: ntOff(3) = 1024
        CASE 4: ntOff(0) = 0: ntOff(1) = 1024: ntOff(2) = 2048: ntOff(3) = 3072
    END SELECT
END SUB

SUB MapperReset
    SetPrg8 0, 0: SetPrg8 1, 1: SetPrg8 2, -2: SetPrg8 3, -1
    SetChr8 0
    SetMirror mirrorHw
    irqMap = 0
    SELECT CASE mapper
        CASE 1
            m1sr = 0: m1cnt = 0: m1ctrl = &HC: m1chr0 = 0: m1chr1 = 0: m1prg = 0
            Mmc1Apply
        CASE 4
            m3r(0) = 0: m3r(1) = 2: m3r(2) = 4: m3r(3) = 5
            m3r(4) = 6: m3r(5) = 7: m3r(6) = 0: m3r(7) = 1
            m3sel = 0: m3cnt = 0: m3latch = 0: m3reload = 0: m3en = 0
            Mmc3Apply
        CASE 7
            SetPrg32 0: SetMirror 2
        CASE 11, 34, 66
            SetPrg32 0
    END SELECT
END SUB

SUB MapperWrite (a, v)
    SELECT CASE mapper
        CASE 1 ' MMC1: five writes of one bit each fill a register
            IF v AND 128 THEN
                m1sr = 0: m1cnt = 0: m1ctrl = m1ctrl OR &HC
                Mmc1Apply
            ELSE
                IF v AND 1 THEN m1sr = m1sr OR bitv(7 - m1cnt)
                m1cnt = m1cnt + 1
                IF m1cnt = 5 THEN
                    SELECT CASE (a \ 8192) AND 3
                        CASE 0: m1ctrl = m1sr
                        CASE 1: m1chr0 = m1sr
                        CASE 2: m1chr1 = m1sr
                        CASE 3: m1prg = m1sr
                    END SELECT
                    m1sr = 0: m1cnt = 0
                    Mmc1Apply
                END IF
            END IF
        CASE 4 ' MMC3
            SELECT CASE a AND &HE001&
                CASE &H8000&: m3sel = v: Mmc3Apply
                CASE &H8001&: m3r(m3sel AND 7) = v: Mmc3Apply
                CASE &HA000&
                    IF mirrorHw <> 4 THEN
                        IF v AND 1 THEN SetMirror 0 ELSE SetMirror 1
                    END IF
                CASE &HC000&: m3latch = v
                CASE &HC001&: m3cnt = 0: m3reload = 1
                CASE &HE000&: m3en = 0: irqMap = 0
                CASE &HE001&: m3en = 1
            END SELECT
        CASE 2 ' UxROM
            SetPrg16 0, v AND prg(prgOff((a - 32768) \ 8192) + (a AND 8191))
        CASE 3 ' CNROM
            SetChr8 v AND prg(prgOff((a - 32768) \ 8192) + (a AND 8191))
        CASE 7 ' AxROM
            SetPrg32 v AND 15
            IF v AND 16 THEN SetMirror 3 ELSE SetMirror 2
        CASE 11 ' Color Dreams
            SetPrg32 v AND 3: SetChr8 v \ 16
        CASE 34 ' BNROM
            SetPrg32 v
        CASE 66 ' GxROM
            SetPrg32 (v \ 16) AND 3: SetChr8 v AND 3
        CASE 71 ' Camerica
            IF a >= &HC000& THEN
                SetPrg16 0, v
            ELSEIF a >= &H9000& AND a < &HA000& THEN
                IF v AND 16 THEN SetMirror 3 ELSE SetMirror 2
            END IF
    END SELECT
END SUB

SUB Mmc1Apply
    SELECT CASE m1ctrl AND 3
        CASE 0: SetMirror 2
        CASE 1: SetMirror 3
        CASE 2: SetMirror 1
        CASE 3: SetMirror 0
    END SELECT
    outer = 0
    IF prgSize > 262144 THEN outer = m1chr0 AND 16 ' 512 KB boards: which 256 KB half
    pb = m1prg AND 15
    SELECT CASE (m1ctrl \ 4) AND 3
        CASE 0, 1: SetPrg32 (pb + outer) \ 2
        CASE 2: SetPrg16 0, outer: SetPrg16 1, pb + outer
        CASE 3: SetPrg16 0, pb + outer: SetPrg16 1, 15 + outer
    END SELECT
    IF m1ctrl AND 16 THEN
        SetChr4 0, m1chr0: SetChr4 1, m1chr1
    ELSE
        SetChr8 m1chr0 \ 2
    END IF
END SUB

SUB Mmc3Apply
    IF m3sel AND 128 THEN
        SetChr1 0, m3r(2): SetChr1 1, m3r(3): SetChr1 2, m3r(4): SetChr1 3, m3r(5)
        SetChr1 4, m3r(0) AND 254: SetChr1 5, m3r(0) OR 1
        SetChr1 6, m3r(1) AND 254: SetChr1 7, m3r(1) OR 1
    ELSE
        SetChr1 0, m3r(0) AND 254: SetChr1 1, m3r(0) OR 1
        SetChr1 2, m3r(1) AND 254: SetChr1 3, m3r(1) OR 1
        SetChr1 4, m3r(2): SetChr1 5, m3r(3): SetChr1 6, m3r(4): SetChr1 7, m3r(5)
    END IF
    IF m3sel AND 64 THEN
        SetPrg8 0, -2: SetPrg8 2, m3r(6) AND 63
    ELSE
        SetPrg8 0, m3r(6) AND 63: SetPrg8 2, -2
    END IF
    SetPrg8 1, m3r(7) AND 63: SetPrg8 3, -1
END SUB

' once per scanline while rendering (the MMC3 counts scanlines for its IRQ)
SUB MapperScanline
    IF mapper <> 4 THEN EXIT SUB
    IF m3cnt = 0 OR m3reload THEN
        m3cnt = m3latch: m3reload = 0
    ELSE
        m3cnt = m3cnt - 1
    END IF
    IF m3cnt = 0 AND m3en <> 0 THEN irqMap = 1
END SUB

' =====================================================================
'  APU (sound): two pulse channels, triangle, noise, DMC level
'  Updated once per scanline; samples go out with _SNDRAW.
' =====================================================================
SUB ApuWrite (a, v)
    SELECT CASE a
        CASE &H4000, &H4004
            i = (a - &H4000) \ 4
            pDuty(i) = v \ 64: pHalt(i) = (v \ 32) AND 1
            pConst(i) = (v \ 16) AND 1: pVol(i) = v AND 15
        CASE &H4001, &H4005
            i = (a - &H4000) \ 4
            pSwEn(i) = v \ 128: pSwPer(i) = (v \ 16) AND 7
            pSwNeg(i) = (v \ 8) AND 1: pSwShift(i) = v AND 7: pSwReload(i) = 1
        CASE &H4002, &H4006
            i = (a - &H4000) \ 4
            pTimer(i) = (pTimer(i) AND &H700) OR v
        CASE &H4003, &H4007
            i = (a - &H4000) \ 4
            pTimer(i) = (pTimer(i) AND 255) OR ((v AND 7) * 256)
            IF pOn(i) THEN pLen(i) = lenTab(v \ 8)
            pEnvStart(i) = 1: pPhase#(i) = 0
        CASE &H4008
            tHalt = v \ 128: tLinLoad = v AND 127
        CASE &H400A
            tTimer = (tTimer AND &H700) OR v
        CASE &H400B
            tTimer = (tTimer AND 255) OR ((v AND 7) * 256)
            IF tEn THEN tLen = lenTab(v \ 8)
            tLinReload = 1
        CASE &H400C
            nHalt = (v \ 32) AND 1: nConst = (v \ 16) AND 1: nVol = v AND 15
        CASE &H400E
            nMode = v \ 128: nPeriod = noiseTab(v AND 15)
        CASE &H400F
            IF nEn THEN nLen = lenTab(v \ 8)
            nEnvStart = 1
        CASE &H4011
            dOut = v AND 127
        CASE &H4015
            pOn(0) = v AND 1: pOn(1) = (v \ 2) AND 1
            tEn = (v \ 4) AND 1: nEn = (v \ 8) AND 1
            IF pOn(0) = 0 THEN pLen(0) = 0
            IF pOn(1) = 0 THEN pLen(1) = 0
            IF tEn = 0 THEN tLen = 0
            IF nEn = 0 THEN nLen = 0
            irqDmc = 0
        CASE &H4017
            apuMode = v \ 128: apuIrqOff = (v \ 64) AND 1
            IF apuIrqOff THEN irqApu = 0
            apuCyc# = 0: apuStep = 0
            IF apuMode THEN ApuQuarter: ApuHalf
    END SELECT
END SUB

FUNCTION ApuStatus
    v = 0
    IF pLen(0) THEN v = v OR 1
    IF pLen(1) THEN v = v OR 2
    IF tLen THEN v = v OR 4
    IF nLen THEN v = v OR 8
    IF irqApu THEN v = v OR 64
    IF irqDmc THEN v = v OR 128
    irqApu = 0
    ApuStatus = v
END FUNCTION

' envelopes and the triangle's linear counter (240 times a second)
SUB ApuQuarter
    FOR i = 0 TO 1
        IF pEnvStart(i) THEN
            pEnvStart(i) = 0: pEnvDecay(i) = 15: pEnvDiv(i) = pVol(i)
        ELSEIF pEnvDiv(i) = 0 THEN
            pEnvDiv(i) = pVol(i)
            IF pEnvDecay(i) THEN
                pEnvDecay(i) = pEnvDecay(i) - 1
            ELSEIF pHalt(i) THEN
                pEnvDecay(i) = 15
            END IF
        ELSE
            pEnvDiv(i) = pEnvDiv(i) - 1
        END IF
    NEXT
    IF nEnvStart THEN
        nEnvStart = 0: nEnvDecay = 15: nEnvDiv = nVol
    ELSEIF nEnvDiv = 0 THEN
        nEnvDiv = nVol
        IF nEnvDecay THEN
            nEnvDecay = nEnvDecay - 1
        ELSEIF nHalt THEN
            nEnvDecay = 15
        END IF
    ELSE
        nEnvDiv = nEnvDiv - 1
    END IF
    IF tLinReload THEN
        tLin = tLinLoad
    ELSEIF tLin THEN
        tLin = tLin - 1
    END IF
    IF tHalt = 0 THEN tLinReload = 0
END SUB

' length counters and sweeps (120 times a second)
SUB ApuHalf
    FOR i = 0 TO 1
        IF pLen(i) > 0 AND pHalt(i) = 0 THEN pLen(i) = pLen(i) - 1
        ch = pTimer(i) \ bitv(7 - pSwShift(i))
        IF pSwNeg(i) THEN
            tg = pTimer(i) - ch - (1 - i)
        ELSE
            tg = pTimer(i) + ch
        END IF
        IF pSwDiv(i) = 0 AND pSwEn(i) <> 0 AND pSwShift(i) > 0 AND pTimer(i) >= 8 AND tg <= &H7FF AND tg >= 0 THEN pTimer(i) = tg
        IF pSwDiv(i) = 0 OR pSwReload(i) THEN
            pSwDiv(i) = pSwPer(i): pSwReload(i) = 0
        ELSE
            pSwDiv(i) = pSwDiv(i) - 1
        END IF
    NEXT
    IF tLen > 0 AND tHalt = 0 THEN tLen = tLen - 1
    IF nLen > 0 AND nHalt = 0 THEN nLen = nLen - 1
END SUB

' one scanline of sound: the frame sequencer, then this line's samples
SUB ApuLine
    apuCyc# = apuCyc# + 113.6667
    IF apuCyc# >= 7457 THEN
        apuCyc# = apuCyc# - 7457
        apuStep = apuStep + 1
        IF apuMode = 0 THEN
            ApuQuarter
            IF apuStep = 2 OR apuStep = 4 THEN ApuHalf
            IF apuStep = 4 THEN
                apuStep = 0
                IF apuIrqOff = 0 THEN irqApu = 1
            END IF
        ELSE
            IF apuStep <> 4 THEN ApuQuarter
            IF apuStep = 2 OR apuStep = 5 THEN ApuHalf
            IF apuStep = 5 THEN apuStep = 0
        END IF
    END IF

    IF sndOn = 0 THEN EXIT SUB
    sampFrac# = sampFrac# + sndRate / 15745.8
    n = INT(sampFrac#)
    IF n = 0 THEN EXIT SUB
    sampFrac# = sampFrac# - n

    ' this line's settings for each channel
    FOR i = 0 TO 1
        pv1# = 0: vol = 0
        IF pLen(i) > 0 AND pTimer(i) >= 8 THEN
            IF pSwNeg(i) = 0 THEN
                IF pTimer(i) + pTimer(i) \ bitv(7 - pSwShift(i)) > &H7FF THEN vol = -1
            END IF
            IF vol = 0 THEN
                IF pConst(i) THEN vol = pVol(i) ELSE vol = pEnvDecay(i)
                pv1# = 894886.5# / (pTimer(i) + 1) / sndRate
            ELSE
                vol = 0
            END IF
        END IF
        IF i = 0 THEN p0Step# = pv1#: p0Vol = vol ELSE p1Step# = pv1#: p1Vol = vol
    NEXT
    tStep# = 0
    IF tLen > 0 AND tLin > 0 AND tTimer >= 2 THEN tStep# = 1789773# / (tTimer + 1) / sndRate
    nVolNow = 0: nStep# = 0
    IF nLen > 0 THEN
        IF nConst THEN nVolNow = nVol ELSE nVolNow = nEnvDecay
        nStep# = 1789773# / nPeriod / sndRate
    END IF
    d0 = pDuty(0) * 8: d1 = pDuty(1) * 8

    FOR s = 1 TO n
        o1 = 0: o2 = 0
        IF p0Vol THEN
            pPhase#(0) = pPhase#(0) + p0Step#
            IF pPhase#(0) >= 8 THEN pPhase#(0) = pPhase#(0) - INT(pPhase#(0) / 8) * 8
            o1 = dutyTab(d0 + INT(pPhase#(0))) * p0Vol
        END IF
        IF p1Vol THEN
            pPhase#(1) = pPhase#(1) + p1Step#
            IF pPhase#(1) >= 8 THEN pPhase#(1) = pPhase#(1) - INT(pPhase#(1) / 8) * 8
            o2 = dutyTab(d1 + INT(pPhase#(1))) * p1Vol
        END IF
        IF tStep# > 0 THEN
            tPhase# = tPhase# + tStep#
            IF tPhase# >= 32 THEN tPhase# = tPhase# - INT(tPhase# / 32) * 32
            tOut = triTab(INT(tPhase#))
        END IF
        no = 0
        IF nStep# > 0 THEN
            nAcc# = nAcc# + nStep#
            DO WHILE nAcc# >= 1
                IF nMode THEN
                    fbk = (nLfsr XOR (nLfsr \ 64)) AND 1
                ELSE
                    fbk = (nLfsr XOR (nLfsr \ 2)) AND 1
                END IF
                nLfsr = (nLfsr \ 2) OR (fbk * 16384)
                nAcc# = nAcc# - 1
            LOOP
            IF (nLfsr AND 1) = 0 THEN no = nVolNow
        END IF
        ' the NES mixer
        mx# = 0
        IF o1 + o2 THEN mx# = 95.88 / (8128 / (o1 + o2) + 100)
        tn# = tOut / 8227 + no / 12241 + dOut / 22638
        IF tn# > 0 THEN mx# = mx# + 159.79 / (1 / tn# + 100)
        ' remove the DC level, then out
        hpOut# = hpOut# * .996 + mx# - hpIn#: hpIn# = mx#
        smp# = hpOut# * 1.6
        IF smp# > 1 THEN smp# = 1
        IF smp# < -1 THEN smp# = -1
        IF wavOut THEN
            w% = INT(smp# * 32000): PUT #7, , w%
        ELSE
            _SNDRAW smp#
        END IF
    NEXT
END SUB

' =====================================================================
'  Controller, reset, tables
' =====================================================================
SUB ReadPad
    STATIC f1was, f2was, pwas, f11was, escWas
    p = 0
    IF _KEYDOWN(120) THEN p = p OR 1 '     X      = A
    IF _KEYDOWN(122) THEN p = p OR 2 '     Z      = B
    IF _KEYDOWN(32) OR _KEYDOWN(9) THEN p = p OR 4 ' Space/Tab = Select
    IF _KEYDOWN(13) THEN p = p OR 8 '      Enter  = Start
    IF _KEYDOWN(18432) THEN p = p OR 16 '  Up
    IF _KEYDOWN(20480) THEN p = p OR 32 '  Down
    IF _KEYDOWN(19200) THEN p = p OR 64 '  Left
    IF _KEYDOWN(19712) THEN p = p OR 128 ' Right
    IF (p AND 48) = 48 THEN p = p AND (NOT 48) '  not up and down at once
    IF (p AND 192) = 192 THEN p = p AND (NOT 192)
    pad1 = p
    k = _KEYDOWN(27) '                          Esc = the menu
    IF k AND escWas = 0 THEN menuReq = 1
    escWas = k
    k = _KEYDOWN(15104) '                       F1 = reset
    IF k AND f1was = 0 THEN ResetNes
    f1was = k
    k = _KEYDOWN(15360) '                       F2 = sound on/off
    IF k AND f2was = 0 THEN
        IF sndRate > 0 THEN sndOn = NOT sndOn
    END IF
    f2was = k
    k = _KEYDOWN(112) OR _KEYDOWN(80) '          P = pause
    IF k AND pwas = 0 THEN paused = NOT paused
    pwas = k
    k = _KEYDOWN(34048) '                       F11 = full screen
    IF k AND f11was = 0 THEN
        ToggleFull
        _DEST img
    END IF
    f11was = k
END SUB

SUB ResetNes
    FOR i = 0 TO 2047: ram(i) = 0: NEXT
    FOR i = 0 TO 4095: vram(i) = 0: NEXT
    FOR i = 0 TO 255: oam(i) = 0: NEXT
    FOR i = 0 TO 31: pal(i) = 15: NEXT
    FOR i = 0 TO 61439: fb(i) = -1: NEXT
    pctrl = 0: pmask = 0: pstat = 0: oamAddr = 0: pv = 0: pt = 0: pfx = 0: pw = 0
    rdBuf = 0: ppuBus = 0: grayMask = 63
    nmiPend = 0: irqMap = 0: irqApu = 0: irqDmc = 0
    MapperReset
    ra = 0: rx = 0: ry = 0: rs = &HFD: SetP &H24
    pc = Rd(&HFFFC&) + Rd(&HFFFD&) * 256
    cdot = 0
    ' sound off until the game turns it on
    FOR i = 0 TO 1: pLen(i) = 0: pOn(i) = 0: NEXT
    tLen = 0: tEn = 0: nLen = 0: nEn = 0: dOut = 0: nLfsr = 1
    ' the frame IRQ starts off: games that use it set $4017 themselves, and
    ' some homebrew turns on interrupts without ever acknowledging it
    apuMode = 0: apuIrqOff = 1: apuCyc# = 0: apuStep = 0
END SUB

SUB InitTables
    RESTORE OpcodeTable
    FOR i = 0 TO 255
        READ t
        opIns(i) = t \ 10000
        opMode(i) = (t \ 100) MOD 100
        opCyc(i) = (t \ 10) MOD 10
        opPen(i) = t MOD 10
        ' instructions that read their operand from memory
        SELECT CASE opIns(i)
            CASE 1, 3, 5, 22, 23, 24, 25, 26, 27, 28, 29, 36, 57, 65, 66, 67, 68, 74, 75
                opRead(i) = 1
            CASE 30, 31, 32, 33, 34, 35, 59, 60, 61, 62, 63, 64
                IF opMode(i) <> 12 THEN opRead(i) = 1
        END SELECT
    NEXT
    RESTORE NesPalette
    FOR i = 0 TO 63
        READ r, g, b
        nesRGB(i) = _RGB32(r, g, b)
    NEXT
    RESTORE LengthTable
    FOR i = 0 TO 31: READ lenTab(i): NEXT
    RESTORE NoiseTable
    FOR i = 0 TO 15: READ noiseTab(i): NEXT
    RESTORE DutyTable
    FOR i = 0 TO 31: READ dutyTab(i): NEXT
    FOR i = 0 TO 15: triTab(i) = 15 - i: triTab(i + 16) = i: NEXT
    FOR i = 0 TO 7: bitv(i) = 2 ^ (7 - i): NEXT
    FOR i = 0 TO 7: attShift(i) = 2 ^ i: NEXT
    nPeriod = 4: nLfsr = 1
END SUB

' =====================================================================
'  The game loop and the user interface: splash screen, menus, messages
' =====================================================================
SUB PlayGame
    WaitKeysUp
    _DEST img
    menuReq = 0
    frames = 0
    fpsTime! = TIMER
    DO
        ReadPad
        IF testMode = 4 THEN
            IF frames = 0 THEN benchT# = TIMER
            IF frames = 200 OR frames = 400 THEN pad1 = 8
            IF frames = 210 OR frames = 410 THEN pad1 = 0
            IF frames = 900 THEN
                OPEN "BENCH.TXT" FOR OUTPUT AS #9
                PRINT #9, "900 frames:"; TIMER - benchT#; "s ="; INT(900 / (TIMER - benchT#)); "fps"
                CLOSE #9
                quitNow = 1: EXIT DO
            END IF
        END IF
        IF paused = 0 THEN RunFrame
        Present
        frames = frames + 1

        ' blargg test ROMs report at $6000: $80 = running, else the result code
        IF testMode = 2 THEN
            done = 0
            IF frames > 30 AND sram(1) = &HDE AND sram(2) = &HB0 AND sram(3) = &H61 AND sram(0) < &H80 THEN done = 1
            IF frames > 3600 THEN done = 1
            IF done THEN
                OPEN "RESULT.TXT" FOR OUTPUT AS #9
                PRINT #9, "status"; sram(0); "frames"; frames
                t$ = ""
                FOR i = 4 TO 8000
                    IF sram(i) = 0 THEN EXIT FOR
                    t$ = t$ + CHR$(sram(i))
                NEXT
                PRINT #9, t$
                CLOSE #9
                quitNow = 1: EXIT DO
            END IF
        END IF

        ' timing: follow the sound card when there is one, else 60 frames a
        ' second (never more than 0.1 s of waiting, in case the sound stalls)
        IF testMode = 0 THEN
            IF sndOn AND paused = 0 THEN
                t0! = TIMER
                DO WHILE _SNDRAWLEN > .05
                    _LIMIT 500
                    IF TIMER - t0! > .1 OR TIMER < t0! THEN EXIT DO
                LOOP
            ELSE
                _LIMIT 60
            END IF
        END IF
        IF _EXIT THEN quitNow = 1

        ' frames per second in the title bar
        fpsCount = fpsCount + 1
        IF TIMER - fpsTime! >= 1 OR TIMER < fpsTime! THEN
            IF paused THEN
                _TITLE "QuantumNES - " + gameName$ + "  (paused - P to go on)"
            ELSE
                _TITLE "QuantumNES - " + gameName$ + "  (" + LTRIM$(STR$(fpsCount)) + " fps)"
            END IF
            fpsCount = 0: fpsTime! = TIMER
        END IF
    LOOP UNTIL quitNow OR menuReq
    _DEST 0
END SUB

' load a game and start it; a message if it can't be played
SUB OpenGame (fname$)
    ' a name without a folder is in the current folder: keep the full path
    f$ = fname$
    IF INSTR(f$, ":") = 0 AND LEFT$(f$, 1) <> "\" AND LEFT$(f$, 1) <> "/" THEN
        c$ = _CWD$
        IF RIGHT$(c$, 1) <> "\" THEN c$ = c$ + "\"
        f$ = c$ + f$
    END IF
    IF gameOn THEN SaveBattery
    r = LoadRom(f$)
    IF r THEN
        SELECT CASE r
            CASE 1: MessageBox "Can't open the file|" + ShortName$(f$)
            CASE 2: MessageBox ShortName$(f$) + "|is not a NES game file"
            CASE 3: MessageBox ShortName$(f$) + "|uses mapper" + STR$(mapper) + ",|which QuantumNES can't play yet"
        END SELECT
        EXIT SUB
    END IF
    gameName$ = ShortName$(f$)
    AddRecent f$
    ResetNes
    gameOn = 1: menuReq = 0: paused = 0
    _TITLE "QuantumNES - " + gameName$
END SUB

' ---- the splash screen ------------------------------------------------------
SUB Splash (autoStart)
    _DEST 0
    _KEYCLEAR
    t = 0
    DO
        _LIMIT 60
        DrawBack
        ly = 120
        IF t < 30 THEN ly = 120 - (30 - t) * 5
        Logo ly, 8
        s$ = "THE NES EMULATOR FOR QUANTUMBASIC 7.1"
        BigText CenterX(s$, 2) + 2, ly + 152, s$, 2, _RGB32(10, 0, 30)
        BigText CenterX(s$, 2), ly + 150, s$, 2, _RGB32(150, 190, 255)
        DrawPad SW \ 2, 420
        IF (t \ 30) MOD 2 = 0 THEN
            s$ = "PRESS ENTER"
            BigText CenterX(s$, 3) + 3, 563, s$, 3, _RGB32(60, 20, 0)
            BigText CenterX(s$, 3), 560, s$, 3, _RGB32(255, 210, 60)
        END IF
        COLOR _RGB32(120, 110, 170)
        _PRINTMODE _KEEPBACKGROUND
        _PRINTSTRING (12, SH - 24), "Version " + VERSION$
        _PRINTSTRING (SW - 12 - 8 * 10, SH - 24), "Esc = Quit"
        IF t < 30 THEN LINE (0, 0)-(SW - 1, SH - 1), _RGBA32(0, 0, 0, 255 - t * 8), BF
        _DISPLAY
        t = t + 1

        k$ = INKEY$
        IF k$ = CHR$(13) OR k$ = " " THEN EXIT DO
        IF k$ = CHR$(27) THEN quitNow = 1: EXIT DO
        IF MouseClick THEN EXIT DO
        IF autoStart AND t > 100 THEN EXIT DO
        IF _EXIT THEN quitNow = 1: EXIT DO
    LOOP
END SUB

' ---- the main menu ------------------------------------------------------------
SUB MainMenu
    STATIC sel
    mCount = 0
    IF gameOn THEN AddItem "Continue Game", "CONT"
    AddItem "Open a Game...", "OPEN"
    IF recentCount THEN
        AddItem "-RECENT GAMES", ""
        FOR i = 0 TO recentCount - 1
            AddItem "  " + ShortName$(recent$(i)), "REC" + STR$(i)
        NEXT
    END IF
    AddItem "Controls", "CTRL"
    AddItem "Quit", "QUIT"
    c = RunMenu(0, sel)
    IF c = -2 THEN EXIT SUB
    IF c = -1 THEN
        IF gameOn THEN menuReq = 0
        EXIT SUB
    END IF
    sel = c
    a$ = mAct$(c)
    SELECT CASE LEFT$(a$, 3)
        CASE "CON": menuReq = 0
        CASE "OPE"
            f$ = _OPENFILEDIALOG$("Open a NES game", "", "*.nes|*.NES", "NES games (*.nes)")
            IF f$ <> "" THEN OpenGame f$
            IF gameOn AND menuReq = 0 THEN sel = 0
        CASE "REC"
            OpenGame recent$(VAL(MID$(a$, 4)))
            IF gameOn AND menuReq = 0 THEN sel = 0
        CASE "CTR": ShowControls
        CASE "QUI": quitNow = 1
    END SELECT
END SUB

' ---- the menu over the game (Esc) -----------------------------------------
SUB PauseMenu
    STATIC sel
    mCount = 0
    AddItem "Resume", "RES"
    AddItem "Reset Game", "RST"
    AddItem "Open Another Game...", "OPEN"
    IF sndRate > 0 THEN
        IF sndOn THEN AddItem "Sound: On", "SND" ELSE AddItem "Sound: Off", "SND"
    ELSE
        AddItem "-Sound: no sound card", ""
    END IF
    IF fullScr THEN AddItem "Full Screen: On", "FULL" ELSE AddItem "Full Screen: Off", "FULL"
    AddItem "Controls", "CTRL"
    AddItem "Main Menu", "MENU"
    AddItem "Quit", "QUIT"
    c = RunMenu(1, sel)
    IF c = -2 THEN EXIT SUB
    IF c = -1 THEN menuReq = 0: EXIT SUB
    sel = c
    SELECT CASE mAct$(c)
        CASE "RES": menuReq = 0
        CASE "RST": ResetNes: menuReq = 0: sel = 0
        CASE "OPEN"
            f$ = _OPENFILEDIALOG$("Open a NES game", "", "*.nes|*.NES", "NES games (*.nes)")
            IF f$ <> "" THEN OpenGame f$
            IF menuReq = 0 THEN sel = 0
        CASE "SND": sndOn = NOT sndOn
        CASE "FULL": ToggleFull
        CASE "CTRL": ShowControls
        CASE "MENU": menuReq = 2: sel = 0
        CASE "QUIT": quitNow = 1
    END SELECT
END SUB

SUB AddItem (t$, a$)
    mItem$(mCount) = t$: mAct$(mCount) = a$
    mCount = mCount + 1
END SUB

' Runs a menu of mItem$(): returns the item chosen, -1 for Esc, -2 when
' the window is closed.  kind 0 = over the stars, 1 = over the game.
' Items starting with "-" are headings that can't be chosen.
FUNCTION RunMenu (kind, sel)
    _DEST 0
    WaitKeysUp
    IF sel < 0 OR sel >= mCount THEN sel = 0
    DO WHILE LEFT$(mItem$(sel), 1) = "-": sel = (sel + 1) MOD mCount: LOOP
    itemH = 34: pw = 520: px = (SW - pw) \ 2
    IF kind = 0 THEN
        py = 210
        IF py + mCount * itemH > SH - 50 THEN py = SH - 50 - mCount * itemH
    ELSE
        py = (SH - mCount * itemH) \ 2 + 20
    END IF
    lastMx = -1: lastMy = -1
    DO
        _LIMIT 60
        IF kind = 0 THEN
            DrawBack
            Logo 50, 6
        ELSE
            _PUTIMAGE (0, 0)-(SW - 1, SH - 1), img
            LINE (0, 0)-(SW - 1, SH - 1), _RGBA32(0, 0, 20, 160), BF
            s$ = "PAUSED"
            BigText CenterX(s$, 4) + 4, py - 96, s$, 4, _RGB32(0, 0, 0)
            BigText CenterX(s$, 4), py - 100, s$, 4, _RGB32(255, 255, 255)
        END IF
        LINE (px - 16, py - 14)-(px + pw + 16, py + mCount * itemH + 10), _RGBA32(12, 8, 34, 215), BF
        LINE (px - 16, py - 14)-(px + pw + 16, py + mCount * itemH + 10), _RGB32(130, 90, 220), B
        LINE (px - 13, py - 11)-(px + pw + 13, py + mCount * itemH + 7), _RGB32(60, 40, 110), B
        FOR i = 0 TO mCount - 1
            t$ = mItem$(i): iy = py + i * itemH
            IF LEFT$(t$, 1) = "-" THEN
                BigText px + 16, iy + 4, MID$(t$, 2), 2, _RGB32(150, 130, 60)
            ELSE
                IF LEN(t$) > 30 THEN t$ = LEFT$(t$, 28) + ".."
                IF i = sel THEN
                    LINE (px, iy)-(px + pw, iy + itemH - 4), _RGB32(196, 24, 56), BF
                    LINE (px, iy)-(px + pw, iy + itemH - 4), _RGB32(255, 120, 140), B
                    BigText px + 16, iy + 1, t$, 2, _RGB32(255, 255, 255)
                ELSE
                    BigText px + 16, iy + 1, t$, 2, _RGB32(200, 200, 225)
                END IF
            END IF
        NEXT
        COLOR _RGB32(140, 130, 190)
        _PRINTMODE _KEEPBACKGROUND
        s$ = "Arrows and Enter, or the mouse     Esc = back"
        _PRINTSTRING ((SW - LEN(s$) * 8) \ 2, SH - 26), s$
        _DISPLAY

        ' keys
        k$ = INKEY$
        SELECT CASE k$
            CASE CHR$(0) + "H" ' up
                DO
                    sel = (sel - 1 + mCount) MOD mCount
                LOOP WHILE LEFT$(mItem$(sel), 1) = "-"
            CASE CHR$(0) + "P" ' down
                DO
                    sel = (sel + 1) MOD mCount
                LOOP WHILE LEFT$(mItem$(sel), 1) = "-"
            CASE CHR$(13), " "
                RunMenu = sel: EXIT FUNCTION
            CASE CHR$(27)
                RunMenu = -1: EXIT FUNCTION
        END SELECT

        ' mouse: point to pick, click to choose
        clk = MouseClick
        mx = msX: my = msY
        IF mx >= px AND mx <= px + pw AND my >= py AND my < py + mCount * itemH THEN
            h = (my - py) \ itemH
            IF LEFT$(mItem$(h), 1) <> "-" THEN
                IF mx <> lastMx OR my <> lastMy THEN sel = h
                IF clk THEN RunMenu = h: EXIT FUNCTION
            END IF
        END IF
        lastMx = mx: lastMy = my

        IF _EXIT THEN quitNow = 1: RunMenu = -2: EXIT FUNCTION
    LOOP
END FUNCTION

' ---- a message in a box until a key or click ('|' starts a new line) ----
SUB MessageBox (m$)
    _DEST 0
    WaitKeysUp
    n = 1
    FOR i = 1 TO LEN(m$): IF MID$(m$, i, 1) = "|" THEN n = n + 1
    NEXT
    bh = n * 36 + 90: by = (SH - bh) \ 2
    DO
        _LIMIT 60
        DrawBack
        Logo 50, 6
        LINE (84, by)-(SW - 85, by + bh), _RGBA32(40, 6, 16, 230), BF
        LINE (84, by)-(SW - 85, by + bh), _RGB32(230, 70, 90), B
        r$ = m$: ly = by + 24
        DO
            p = INSTR(r$ + "|", "|")
            l$ = LEFT$(r$, p - 1): r$ = MID$(r$, p + 1)
            IF LEN(l$) > 34 THEN l$ = LEFT$(l$, 32) + ".."
            BigText CenterX(l$, 2), ly, l$, 2, _RGB32(255, 235, 235)
            ly = ly + 36
        LOOP WHILE r$ <> ""
        s$ = "Press Enter"
        COLOR _RGB32(255, 180, 190)
        _PRINTMODE _KEEPBACKGROUND
        _PRINTSTRING ((SW - LEN(s$) * 8) \ 2, by + bh - 30), s$
        _DISPLAY
        k$ = INKEY$
        IF k$ = CHR$(13) OR k$ = CHR$(27) OR k$ = " " THEN EXIT DO
        IF MouseClick THEN EXIT DO
        IF _EXIT THEN quitNow = 1: EXIT DO
    LOOP
END SUB

' ---- the keys ------------------------------------------------------------------
SUB ShowControls
    DIM ck$(10), ca$(10)
    RESTORE ControlKeys
    FOR i = 0 TO 10: READ ca$(i), ck$(i): NEXT
    _DEST 0
    WaitKeysUp
    DO
        _LIMIT 60
        DrawBack
        Logo 50, 6
        LINE (84, 190)-(SW - 85, 686), _RGBA32(12, 8, 34, 215), BF
        LINE (84, 190)-(SW - 85, 686), _RGB32(130, 90, 220), B
        s$ = "CONTROLS"
        BigText CenterX(s$, 3), 208, s$, 3, _RGB32(255, 210, 60)
        y = 272
        FOR i = 0 TO 10
            BigText 130, y, ca$(i), 2, _RGB32(150, 190, 255)
            BigText 400, y, ck$(i), 2, _RGB32(255, 255, 255)
            y = y + 32
        NEXT
        s$ = "Press Enter"
        COLOR _RGB32(140, 130, 190)
        _PRINTMODE _KEEPBACKGROUND
        _PRINTSTRING ((SW - LEN(s$) * 8) \ 2, 660), s$
        _DISPLAY
        k$ = INKEY$
        IF k$ = CHR$(13) OR k$ = CHR$(27) OR k$ = " " THEN EXIT DO
        IF MouseClick THEN EXIT DO
        IF _EXIT THEN quitNow = 1: EXIT DO
    LOOP
END SUB

' True when the left button went down since the last call; msX, msY is
' where.  Each mouse event is looked at, so a quick click isn't missed.
FUNCTION MouseClick
    c = 0
    DO WHILE _MOUSEINPUT
        b = _MOUSEBUTTON(1)
        IF b <> 0 AND msLast = 0 AND c = 0 THEN c = -1: msX = _MOUSEX: msY = _MOUSEY
        msLast = b
    LOOP
    IF c = 0 THEN msX = _MOUSEX: msY = _MOUSEY
    MouseClick = c
END FUNCTION

' ---- drawing helpers ---------------------------------------------------------
SUB UiInit
    ' the background: a dark gradient with a glowing grid floor
    bgImg = _NEWIMAGE(SW, SH, 32)
    _DEST bgImg
    FOR y = 0 TO SH - 1
        f! = y / SH
        LINE (0, y)-(SW - 1, y), _RGB32(8 + 22 * f!, 8 + 4 * f!, 26 + 44 * f!)
    NEXT
    hy = 520: gap = 3
    DO WHILE hy < SH
        LINE (0, hy)-(SW - 1, hy), _RGB32(70, 34, 120)
        gap = gap + 3: hy = hy + gap
    LOOP
    FOR i = -14 TO 14
        LINE (SW \ 2 + i * 22, 520)-(SW \ 2 + i * 150, SH - 1), _RGB32(70, 34, 120)
    NEXT
    LINE (0, 519)-(SW - 1, 519), _RGB32(200, 90, 255)
    _DEST 0
    RANDOMIZE TIMER
    FOR i = 0 TO 89
        starX(i) = INT(RND * SW): starY(i) = INT(RND * 510): starV(i) = 1 + INT(RND * 3)
    NEXT
    ' the settings file, next to the program
    e$ = COMMAND$(0): d = 0
    FOR i = 1 TO LEN(e$)
        IF MID$(e$, i, 1) = "\" OR MID$(e$, i, 1) = "/" THEN d = i
    NEXT
    iniFile$ = LEFT$(e$, d) + "QuantumNES.ini"
    LoadRecent
END SUB

' the background and moving stars
SUB DrawBack
    uiTick = uiTick + 1
    _PUTIMAGE (0, 0), bgImg
    FOR i = 0 TO 89
        IF uiTick MOD (4 - starV(i)) = 0 THEN starY(i) = starY(i) + 1
        IF starY(i) > 512 THEN starY(i) = 0: starX(i) = INT(RND * SW)
        c = 60 + starV(i) * 60
        PSET (starX(i), starY(i)), _RGB32(c, c, c + 30)
        IF starV(i) = 3 THEN PSET (starX(i) + 1, starY(i)), _RGB32(c, c, c + 30)
    NEXT
END SUB

' "Quantum" in white and "NES" in red, sc times the size of the text font
SUB Logo (y, sc)
    x = CenterX("QuantumNES", sc)
    BigText x + sc, y + sc, "QuantumNES", sc, _RGB32(30, 10, 60)
    BigText x + sc * 2, y + sc * 2, "QuantumNES", sc, _RGB32(30, 10, 60)
    BigText x, y, "Quantum", sc, _RGB32(240, 240, 255)
    BigText x + 7 * 8 * sc, y, "NES", sc, _RGB32(230, 30, 60)
END SUB

' text made sc times bigger (the 8 x 16 font, blown up)
SUB BigText (x, y, t$, sc, col)
    IF t$ = "" THEN EXIT SUB
    w = LEN(t$) * 8
    tmp = _NEWIMAGE(w, 16, 32)
    _DEST tmp
    COLOR col, _RGBA32(0, 0, 0, 0)
    _PRINTMODE _KEEPBACKGROUND
    _PRINTSTRING (0, 0), t$
    _DEST 0
    _PUTIMAGE (x, y)-(x + w * sc - 1, y + 16 * sc - 1), tmp
    _FREEIMAGE tmp
END SUB

FUNCTION CenterX (t$, sc)
    CenterX = (SW - LEN(t$) * 8 * sc) \ 2
END FUNCTION

' a game pad, centred on (cx, cy)
SUB DrawPad (cx, cy)
    x1 = cx - 170: y1 = cy - 62: x2 = cx + 170: y2 = cy + 62
    RoundBox x1 + 4, y1 + 6, x2 + 4, y2 + 6, 26, _RGB32(10, 4, 24) '   shadow
    RoundBox x1, y1, x2, y2, 26, _RGB32(205, 205, 215) '              body
    RoundBox x1 + 10, y1 + 10, x2 - 10, y2 - 10, 18, _RGB32(40, 40, 48) ' face
    ' D-pad
    dx = cx - 105
    LINE (dx - 34, cy - 11)-(dx + 34, cy + 11), _RGB32(15, 15, 18), BF
    LINE (dx - 11, cy - 34)-(dx + 11, cy + 34), _RGB32(15, 15, 18), BF
    FillCircle dx, cy, 6, _RGB32(45, 45, 52)
    ' select and start
    RoundBox cx - 42, cy + 8, cx - 8, cy + 20, 6, _RGB32(120, 120, 130)
    RoundBox cx + 8, cy + 8, cx + 42, cy + 20, 6, _RGB32(120, 120, 130)
    ' B and A
    FillCircle cx + 72, cy + 12, 21, _RGB32(25, 25, 30)
    FillCircle cx + 128, cy + 12, 21, _RGB32(25, 25, 30)
    FillCircle cx + 72, cy + 10, 18, _RGB32(210, 30, 50)
    FillCircle cx + 128, cy + 10, 18, _RGB32(210, 30, 50)
    BigText cx + 68, cy - 32, "B", 1, _RGB32(230, 230, 240)
    BigText cx + 124, cy - 32, "A", 1, _RGB32(230, 230, 240)
END SUB

SUB RoundBox (x1, y1, x2, y2, r, c)
    LINE (x1 + r, y1)-(x2 - r, y2), c, BF
    LINE (x1, y1 + r)-(x2, y2 - r), c, BF
    FillCircle x1 + r, y1 + r, r, c
    FillCircle x2 - r, y1 + r, r, c
    FillCircle x1 + r, y2 - r, r, c
    FillCircle x2 - r, y2 - r, r, c
END SUB

SUB FillCircle (cx, cy, r, c)
    FOR dy = -r TO r
        dx = INT(SQR(r * r - dy * dy))
        LINE (cx - dx, cy + dy)-(cx + dx, cy + dy), c
    NEXT
END SUB

SUB ToggleFull
    fullScr = NOT fullScr
    _DEST 0
    IF fullScr THEN _FULLSCREEN _SQUAREPIXELS ELSE _FULLSCREEN _OFF
END SUB

' wait until Enter, Esc and Space are let go, so a key that closed a
' menu doesn't also reach the game
SUB WaitKeysUp
    _KEYCLEAR
    t! = TIMER
    DO WHILE _KEYDOWN(13) OR _KEYDOWN(27) OR _KEYDOWN(32)
        _LIMIT 60
        IF TIMER - t! > .5 OR TIMER < t! THEN EXIT DO
    LOOP
END SUB

' ---- recent games, kept in QuantumNES.ini ---------------------------------
FUNCTION ShortName$ (f$)
    d = 0
    FOR i = 1 TO LEN(f$)
        IF MID$(f$, i, 1) = "\" OR MID$(f$, i, 1) = "/" THEN d = i
    NEXT
    ShortName$ = MID$(f$, d + 1)
END FUNCTION

SUB AddRecent (f$)
    ' take it out if it is there, then put it first
    j = 0
    FOR i = 0 TO recentCount - 1
        IF UCASE$(recent$(i)) <> UCASE$(f$) THEN recent$(j) = recent$(i): j = j + 1
    NEXT
    recentCount = j
    IF recentCount > 7 THEN recentCount = 7
    FOR i = recentCount TO 1 STEP -1: recent$(i) = recent$(i - 1): NEXT
    recent$(0) = f$
    recentCount = recentCount + 1
    SaveRecent
END SUB

SUB LoadRecent
    recentCount = 0
    IF NOT _FILEEXISTS(iniFile$) THEN EXIT SUB
    OPEN iniFile$ FOR INPUT AS #6
    DO WHILE NOT EOF(6) AND recentCount < 8
        LINE INPUT #6, l$
        IF UCASE$(LEFT$(l$, 7)) = "RECENT=" THEN
            recent$(recentCount) = MID$(l$, 8): recentCount = recentCount + 1
        END IF
    LOOP
    CLOSE #6
END SUB

SUB SaveRecent
    IF testMode THEN EXIT SUB
    OPEN iniFile$ FOR OUTPUT AS #6
    PRINT #6, "[QuantumNES]"
    FOR i = 0 TO recentCount - 1: PRINT #6, "RECENT="; recent$(i): NEXT
    CLOSE #6
END SUB

