]> Shamusworld >> Repos - thunder/blobdiff - src/thunder.cpp
Added save states; updated application icon.
[thunder] / src / thunder.cpp
index d1ebfde22f9e07fbac870ff4c933170210cba2cf..cb91ed1a76e2ebb1062a2a5ff06c3777c71797a8 100644 (file)
@@ -2,7 +2,7 @@
 // Thunder: A Rolling Thunder Emulator
 //
 // by James Hammons
-// (C) 2004, 2014 Underground Software
+// (C) 2004, 2023 Underground Software
 //
 // JLH = James Hammons <jlhamm@acm.org>
 //
 // JLH  08/12/2009  Stabilized emulation so that it works
 // JLH  04/04/2014  Converted to SDL 2
 // JLH  04/17/2014  Removed a metric fuck-tonne of cruft, added YM2151 & MCU
+// JLH  01/13/2023  Finally fixed the sprite lag problem  :-D
+// JLH  01/13/2023  Added save states
 //
 
-#define THUNDER_VERSION                "1.1.0"
+#define THUNDER_VERSION                "1.2.2"
 
 #include <SDL2/SDL.h>
-#include <iostream>
-#include <iomanip>
-#include <fstream>
 #include <string>
-#include <new>
-#include <stdio.h>
 #include <stdlib.h>
-#include <stdint.h>
 #include <time.h>
+#include "fileio.h"
 #include "gui.h"
 #include "log.h"
+#include "psg.h"
 #include "screen.h"
 #include "sound.h"
 #include "v63701.h"
 #include "video.h"
 #include "ym2151.h"
 
-
-using namespace std;
-
-
 #define ROM1   "rt3-1b.9c"
 #define ROM2   "rt3-2b.12c"
 #define ROM3   "rt3-3.12d"
@@ -68,294 +62,160 @@ using namespace std;
 #define PROM5  "mb7112e.6u"
 #define MCUROM "rt1-mcu.bin"
 
-
 // Global defines
 
-SDL_Surface * screen;
-
-uint8_t * gram, * grom;                                // Allocate RAM & ROM pointers
-uint8_t gram1[0x10000], gram2[0x10000], grom1[0x10000], grom2[0x10000];        // Actual memory
-uint8_t grom3[0x8000], grom4[0x8000], data_rom[0x40000], spr_rom[0x80000], voice_rom[0x20000];
-uint8_t chr_rom[0x60000];                      // Character ROM pointer
+uint8_t gram1[0x10000], grom1[0x10000], grom2[0x10000];
+uint8_t grom3[0x8000], data_rom[0x40000], spr_rom[0x80000], voice_rom[0x20000];
+uint8_t charROM[0x60000];              // Character ROM
 uint8_t mcuMem[0x10000];               // 64K for MCU
 
+// CPU execution contexts
 V6809REGS cpu1, cpu2;
 V63701REGS mcu;
 
-bool trace1 = false;                   // ditto...
-bool looking_at_rom = true;            // true = R1, false = R2
-uint32_t banksw1, banksw2;             // Bank switch addresses
-uint16_t game_over_switch;             // Game over delay
-uint16_t dpc;                                  // Debug pc reg...
-bool show_scr = true;                  // Whether or not to show background
-bool enable_cpu = true;                        // Whether or not to enable CPUs
-bool irqGoA = true;                            // IRQ switch for CPU #1
-bool irqGoB = true;                            // IRQ switch for CPU #2
-
-uint16_t refresh_ = 0;                 // Crappy global screen stuff...
-bool refresh2 = true;
-
-uint32_t psg_lens[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
-uint8_t * psg_adrs[16];
-//uint32_t voc_lens[32] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-//                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
-//uint8_t * voc_adrs[32];
-//uint32_t fm_lens[14] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
-//uint8_t * fm_adrs[14];
+// Bank switch addresses
+uint32_t banksw1, banksw2;
 
+// MCU inputs
 Byte input1, input2, input3, input4, input5;
 
-fstream tr;                                                    // Tracelog hook
-uint16_t pcx;                                          // Where we at?
+// Miscellaneous stuff
+bool copySprites = false;
+const uint8_t stateHeader[20] = "THUNDERSAVESTATE1.0";
 
+// Function prototypes
+uint8_t MCUReadMemory(uint16_t address);
+void MCUWriteMemory(uint16_t address, uint8_t data);
 
 //
-// Read a byte from memory (without touching PC. Not a Fetch!)
+// Read a byte from memory
 //
-uint8_t RdMem(uint16_t addr)
+uint8_t MainReadMemory(uint16_t addr)
 {
        uint8_t b;
 
-       // $4000-4300 is RAM shared with the microcontroller...
-
        if (addr < 0x8000)
        {
                // Memory shared with MCU (CPU #1 only! CPU #2 does not)
                if ((addr >= 0x4000) && (addr <= 0x43FF))
                        return mcuMem[addr - 0x3000];
 
-               if (addr > 0x5FFF)
-                       b = data_rom[banksw1 + (addr - 0x6000)];        // Get char data
-               else
-                       b = gram1[addr];
+               if (addr >= 0x6000)
+                       return data_rom[banksw1 + (addr - 0x6000)];     // Get char data
+
+               return gram1[addr];
        }
-       else
-               b = grom1[addr];
 
-       return b;
+       return grom1[addr];
 }
 
-
 //
 // Write a byte to memory
 //
-void WrMem(uint16_t addr, uint8_t b)
+void MainWriteMemory(uint16_t address, uint8_t data)
 {
-       extern bool disasm;
-       extern bool charbase;   // Needed for screen. Extern it in it??
-#if 0
-       if (addr == 0x4182)
-       {
-               WriteLog("\nWriteMem: CPU #1 writing $%02X to $4182!\n\n", b);
-       }
-#endif
-#if 0
-if (((addr >= 0x4180) && (addr <= 0x4191)) || (addr == 0x4380))
-       printf("WriteMem: CPU #1 writing $%02X to $%04X...\n", b, addr);
-#endif
+       if (address == 0x6000)
+               SpawnSound(GAMESOUND, gram1[0x6200], 0);        // Do voice chan 1
+       if (address == 0x6400)
+               SpawnSound(GAMESOUND, gram1[0x6600], 1);        // Do voice chan 2
+       if (address == 0x6800)
+               banksw1 = (uint32_t)data << 13;                         // Set char data bankswitch base address
 
-       if (addr == 0x6000)
-               SpawnSound(GAMESOUND, gram1[0x6200], 0);                // Do voice chan 1
-       if (addr == 0x6400)
-               SpawnSound(GAMESOUND, gram1[0x6600], 1);                // Do voice chan 2
-       if (addr == 0x6800)
-               banksw1 = (uint32_t)b << 13;                                            // Set char data bankswitch base address
-       if (addr > 0x4284 && addr < 0x42A5 && b)
-               SpawnSound(PSGSOUND, addr - 0x4285);                    // Do PSG sound on chans 2, 3
-#if 0
-       if (addr == 0x4380)
-       {
-               SpawnSound(FMSOUND, b);                                                 // Do FM sound on channel 4
-               if (b == 12)
-                       game_over_switch = 240;                                         // Set game over delay...
-       }
-#endif
-//     if (addr < 0x423D || addr > 0x425C)                                     // Protect writes to DSWs
-//if (addr == 0x4191)
-//{
-//     printf("V6809: Writing %02X to $4191...\n", b);
-//}
        // Memory shared with MCU (CPU #1 only! CPU #2 does not)
-       if ((addr >= 0x4000) && (addr <= 0x43FF))
-               mcuMem[addr - 0x3000] = b;
+       if ((address >= 0x4000) && (address <= 0x43FF))
+               mcuMem[address - 0x3000] = data;
        else
-               gram1[addr] = b;
-
-       if (addr == 0x8800)
-               charbase = false;                                                               // Char banksw1
-       if (addr == 0x8C00)
-               charbase = true;                                                                // Char banksw2
-       if (addr == 0x8400)                                                                     // Frame go strobe? VBlank acknowledge?
-       {
-               if (refresh_++ == 1)                                                            // 30 Hz...
-               {
-                       BlitChar(screen, chr_rom, gram1);
-                       refresh_ = (refresh2 ? 1 : 0);                          // 60/30 Hz...
-               }
-
-               // IRQ Ack (may also be frame go...
-               ClearLineOfCurrentV6809(V6809_ASSERT_LINE_IRQ);
-#if 1
-       if (disasm)
-               WriteLog("WriteMem: CPU #1 Acknowledging IRQ...\n", b);
-#endif
-       }
+               gram1[address] = data;
+
+       if (address == 0x5FF2)
+               copySprites = true;
+       if (address == 0x8800)
+               charBankSwitch = false;         // Char banksw1
+       if (address == 0x8C00)
+               charBankSwitch = true;          // Char banksw2
+       if (address == 0x8400)                  // Frame go strobe? VBlank acknowledge?
+               ClearLineOfCurrentV6809(V6809_LINE_IRQ); // IRQ Ack
 }
 
-
 //
-// Read a byte from memory (without touching PC. Not a Fetch!) (2nd processor)
+// Read a byte from memory (2nd processor)
 //
-uint8_t RdMemB(uint16_t addr)
+uint8_t SubReadMemory(uint16_t address)
 {
-       uint8_t b;
-
-       if (addr < 0x8000)
+       if (address < 0x8000)
        {
-               if (addr < 0x2000)
-                       b = gram1[addr + 0x4000];
-               if (addr > 0x1FFF && addr < 0x6000)
-                       b = gram1[addr - 0x2000];
-               if (addr > 0x5FFF)
-                       b = grom3[banksw2 + (addr - 0x6000)];
+               if (address < 0x2000)
+                       return gram1[address + 0x4000];
+               else if ((address >= 0x2000) && (address < 0x6000))
+                       return gram1[address - 0x2000];
+               else if (address >= 0x6000)
+                       return grom3[banksw2 + (address - 0x6000)];
        }
-       else
-               b = grom2[addr];
 
-       return b;
+       return grom2[address];
 }
 
-
 //
 // Write a byte to memory (2nd processor)
 //
-void WrMemB(uint16_t addr, uint8_t b)
+void SubWriteMemory(uint16_t address, uint8_t data)
 {
-       extern bool disasm;
-       extern bool charbase;
+       // Set sprite data bank switch
+       if (address == 0xD803)
+               banksw2 = (uint32_t)(data & 0x03) << 13;
 
-#if 0
-       if (addr == 0x0182)
-       {
-               WriteLog("\nWriteMem: CPU #2 writing $%02X to $0182 ($4182)!\n\n", b);
-       }
-#endif
-#if 0
-if (((addr >= 0x0180) && (addr <= 0x0191)) || (addr == 0x0380))
-       printf("WriteMem: CPU #2 writing $%02X to $%04X...\n", b, addr);
-#endif
+       if (address < 0x2000)
+               gram1[address + 0x4000] = data;
 
-#if 0
-       if (addr == 0x6000)
-               SpawnSound(GAMESOUND, gram1[0x6200], 0);                // Do voice chan 1
-       if (addr == 0x6400)
-               SpawnSound(GAMESOUND, gram1[0x6600], 1);                // Do voice chan 2
-       if (addr > 0x0284 && addr < 0x02A5 && b)
-               SpawnSound(PSGSOUND, addr - 0x0285);                    // Do PSG sound on chans 2, 3
-#endif
-       if (addr == 0xD803)
-               banksw2 = (uint32_t)(b & 0x03) << 13;                           // Set sprite data bank switch
-#if 0
-       if (addr == 0x0380)
-       {
-               SpawnSound(FMSOUND, b);                                                 // Do FM sound on chan 4
-               if (b == 12)
-                       game_over_switch = 240;                                         // Set game over delay...
-       }
-#endif
-//     if (addr < 0x023D || addr > 0x025C)                                     // Protect writes against DSWs
-       {
-               if (addr < 0x2000)
-                       gram1[addr + 0x4000] = b;
-               if (addr > 0x1FFF && addr < 0x6000)
-                       gram1[addr - 0x2000] = b;
-//             if (addr > 0x5FFF)
-//                     gram1[addr] = b;
-       }
-       if (addr == 0x8800)
-       {
-               // IRQ Ack (may also be frame go...)
-               ClearLineOfCurrentV6809(V6809_ASSERT_LINE_IRQ);
-#if 1
-       if (disasm)
-               WriteLog("WriteMem: CPU #2 Acknowledging IRQ...\n", b);
-#endif
-       }
-}
+       if ((address >= 0x2000) && (address < 0x6000))
+               gram1[address - 0x2000] = data;
 
+       if (address == 0x1FF2)
+               copySprites = true;
+
+       if (address == 0x8800)
+               ClearLineOfCurrentV6809(V6809_LINE_IRQ); // IRQ Ack
+}
 
 uint8_t MCUReadMemory(uint16_t address)
 {
        if (address < 0x20)
-       {
-//             printf("V63701 read $%02X from $%02X...\n", memory[address], address);
                return InternalRegisterRead(address);
-       }
+       else if ((address >= 0x1000) && (address <= 0x113F))
+               return ReadPSG(address - 0x1000);
        else if ((address >= 0x2000) && (address <= 0x2001))
-       {
-//             return 0;       //for now
                return YMReadReg(0);
-       }
        // Various joystick + buttons; all are active low.
        else if (address == 0x2020)
-       {
-//printf("MCURead: Returning $%02X from $2020...\n", input1.byte);
                return input1.byte;
-       }
        else if (address == 0x2021)
-       {
-//extern bool V63701LogGo;
-//if (input2.byte == 0xDF)
-//     V63701LogGo = true;
-
-//printf("MCURead: Returning $%02X from $2021...\n", input2.byte);
                return input2.byte;
-       }
        // This is DSW1 & 2. All switch settings are active low.
        else if (address == 0x2030)
-       {
-//printf("MCURead: Returning $%02X from $2030...\n", input4.byte);
                return input4.byte;
-       }
        else if (address == 0x2031)
-       {
-//printf("MCURead: Returning $%02X from $2031...\n", input5.byte);
                return input5.byte;
-       }
 
        return mcuMem[address];
 }
 
-
 void MCUWriteMemory(uint16_t address, uint8_t data)
 {
        static uint8_t ymRegister;
 
-#if 1
        if (address < 0x20)
        {
-//             printf("V63701 wrote $%02X to $%02X...\n", data, address);
                InternalRegisterWrite(address, data);
                return;
        }
-#endif
-
-//if (address == 0x1191)
-//{
-//     printf("V63701: Writing $%02X to $1191...\n", data);
-//}
-#if 0
-       // Translate local reads @ $1000-$13FF to $4000-$43FF in shared RAM
-       if ((address >= 0x1000) && (address <= 0x13FF))
+       else if (((address >= 0x4000) && (address <= 0xBFFF))
+               || (address >= 0xF000))
+               return;
+       else if ((address >= 0x1000) && (address <= 0x113F))
        {
-               gram1[0x3000 + address] = data;
+               WritePSG(address - 0x1000, data);
                return;
        }
-#endif
-
-       if (((address >= 0x4000) && (address <= 0xBFFF))
-               || (address >= 0xF000))
-               return;
        else if (address == 0x2000)
        {
                ymRegister = data;
@@ -363,7 +223,6 @@ void MCUWriteMemory(uint16_t address, uint8_t data)
        }
        else if (address == 0x2001)
        {
-//printf("Writing $%02X to YM2151 register $%02X...\n", data, ymRegister);
                YMWriteReg(0, ymRegister, data);
                return;
        }
@@ -372,32 +231,27 @@ void MCUWriteMemory(uint16_t address, uint8_t data)
        mcuMem[address] = data;
 }
 
-
 uint8_t V63701ReadPort1(void)
 {
 //     printf("V63701ReadPort1: Read $%02X...\n", input3.byte);
        return input3.byte;
 }
 
-
 uint8_t V63701ReadPort2(void)
 {
        return 0xFF;
 }
 
-
 void V63701WritePort1(uint8_t data)
 {
 //     printf("V63701WritePort1: Wrote $%02X...\n", data);
 }
 
-
 void V63701WritePort2(uint8_t data)
 {
 //     printf("V63701WritePort2: Wrote $%02X...\n", data);
 }
 
-
 //
 // Generic Load file into image space
 // (No error checking performed!  Responsibility of caller!)
@@ -411,264 +265,244 @@ bool LoadImg(const char * filename, uint8_t * mem, uint32_t address, uint32_t le
        FILE * file = fopen(path, "rb");
 
        if (!file)
+       {
+               printf("Could not open file \"%s\"!\n", filename);
                return false;
+       }
 
-       fread(&mem[address], 1, length, file);
+       size_t ignored = fread(&mem[address], 1, length, file);
        fclose(file);
 
        return true;
 }
 
-
 //
 // Read color PROMs
 //
 bool ReadColorPROMs(void)
 {
-       fstream ff1, ff2;
-       //  uint8_t ch;
-       char ch;
-       extern uint32_t palette[256];     // Screen physical palette
-       extern uint8_t ccolor[256][8];   // Character color PROM values
-       extern uint8_t scolor[128][16];  // Sprite color PROM values
-
-       ff1.open("./ROMs/"PROM3, ios::binary | ios::in);
+       FILE * file1 = fopen("./ROMs/" PROM3, "rb");
 
-       if (ff1)
+       if (file1)
        {
                for(int i=0; i<256; i++) // Load char pallete with PROM values
-               {
                        for(int j=0; j<8; j++)
-                       {
-                               ff1.get(ch);
-                               ccolor[i][j] = (uint8_t)ch;
-                       }
-               }
+                               ccolor[i][j] = (uint8_t)fgetc(file1);
 
-               ff1.close();
+               fclose(file1);
        }
 
-       ff1.open("./ROMs/"PROM4, ios::binary | ios::in);
+       file1 = fopen("./ROMs/" PROM4, "rb");
 
-       if (ff1)
+       if (file1)
        {
                for(int i=0; i<128; i++) // Load sprite pallete with PROM values
-               {
                        for(int j=0; j<16; j++)
-                       {
-                               ff1.get(ch);
-                               scolor[i][j] = (uint8_t)ch;
-                       }
-               }
+                               scolor[i][j] = (uint8_t)fgetc(file1);
 
-               ff1.close();
+               fclose(file1);
        }
 
-       ff1.open("./ROMs/"PROM1, ios::binary | ios::in);
-       ff2.open("./ROMs/"PROM2, ios::binary | ios::in);
+       file1 = fopen("./ROMs/" PROM1, "rb");
+       FILE * file2 = fopen("./ROMs/" PROM2, "rb");
 
        // If open was successful...
-       if (ff1 && ff2)
+       if (file1 && file2)
        {
                // Palette is 12-bit RGB, we stretch it to 24-bit
                for(int i=0; i<256; i++)
                {
-                       char c1, c2;
-                       ff1.get(c1);
-                       ff2.get(c2);
+                       uint8_t c1 = fgetc(file1);
+                       uint8_t c2 = fgetc(file2);
                        uint8_t r = (uint8_t)c1 & 0x0F;
                        uint8_t g = (uint8_t)c1 >> 4;
                        uint8_t b = (uint8_t)c2;
                        palette[i] = 0xFF000000 | (b << 20) | (b << 16) | (g << 12) | (g << 8) | (r << 4) | r;
                }
 
-               ff1.close();
-               ff2.close();
+               fclose(file1);
+               fclose(file2);
        }
 
        // PROM5 has the following in it (tile address decoder):
        // 00:  00 20 40 60  02 22 42 62  04 24 44 64  06 26 46 66
-       // 10:  88 A8 C8 E8  8A AA CA EA  8C AC CC EC  8E AE CE EE 
+       // 10:  88 A8 C8 E8  8A AA CA EA  8C AC CC EC  8E AE CE EE
 
-       return ff1;
-}
+       if (!file1)
+       {
+               printf("Could not open PROM files!\n");
+               return false;
+       }
 
+       return true;
+}
 
 //
 // Unpack font data
 //
 bool UnpackFonts(void)
 {
-//  uint8_t b1, b2, b3;
-       char b1, b2, b3;
-       fstream f1, f2;
-       //0x4000 $800 chars
-       f1.open("./ROMs/"ROM7, ios::binary | ios::in);
-       f2.open("./ROMs/"ROM8, ios::binary | ios::in);
+       // 0x4000 $800 chars
+       FILE * file1 = fopen("./ROMs/" ROM7, "rb");
+       FILE * file2 = fopen("./ROMs/" ROM8, "rb");
 
-       if ((!f1) || (!f2))
-               return false;  // Return if not found...
+       if (!file1 || !file2)
+       {
+               printf("Could not open either " ROM7 " or " ROM8 "!\n");
+               return false;
+       }
 
        for(long i=0; i<0x40000; i+=64)
        {
                for(int j=0; j<64; j+=8)
                {
-                       f1.get(b1);  f1.get(b2);  f2.get(b3);
-                       b3 ^= 0xFF; // Invert top data...
-                       chr_rom[i+j] = ((b3 & 0x80) >> 5) | ((b1 & 0x80) >> 6) | ((b1 & 0x08) >> 3);
-                       chr_rom[i+j+1] = ((b3 & 0x40) >> 4) | ((b1 & 0x40) >> 5) | ((b1 & 0x04) >> 2);
-                       chr_rom[i+j+2] = ((b3 & 0x20) >> 3) | ((b1 & 0x20) >> 4) | ((b1 & 0x02) >> 1);
-                       chr_rom[i+j+3] = ((b3 & 0x10) >> 2) | ((b1 & 0x10) >> 3) | (b1 & 0x01);
-                       chr_rom[i+j+4] = ((b3 & 0x08) >> 1) | ((b2 & 0x80) >> 6) | ((b2 & 0x08) >> 3);
-                       chr_rom[i+j+5] = (b3 & 0x04)        | ((b2 & 0x40) >> 5) | ((b2 & 0x04) >> 2);
-                       chr_rom[i+j+6] = ((b3 & 0x02) << 1) | ((b2 & 0x20) >> 4) | ((b2 & 0x02) >> 1);
-                       chr_rom[i+j+7] = ((b3 & 0x01) << 2) | ((b2 & 0x10) >> 3) | (b2 & 0x01);
+                       uint8_t b1 = (uint8_t)fgetc(file1);
+                       uint8_t b2 = (uint8_t)fgetc(file1);
+                       uint8_t b3 = (uint8_t)fgetc(file2) ^ 0xFF;
+                       charROM[i + j + 0] = ((b3 & 0x80) >> 5) | ((b1 & 0x80) >> 6) | ((b1 & 0x08) >> 3);
+                       charROM[i + j + 1] = ((b3 & 0x40) >> 4) | ((b1 & 0x40) >> 5) | ((b1 & 0x04) >> 2);
+                       charROM[i + j + 2] = ((b3 & 0x20) >> 3) | ((b1 & 0x20) >> 4) | ((b1 & 0x02) >> 1);
+                       charROM[i + j + 3] = ((b3 & 0x10) >> 2) | ((b1 & 0x10) >> 3) | (b1 & 0x01);
+                       charROM[i + j + 4] = ((b3 & 0x08) >> 1) | ((b2 & 0x80) >> 6) | ((b2 & 0x08) >> 3);
+                       charROM[i + j + 5] = (b3 & 0x04)        | ((b2 & 0x40) >> 5) | ((b2 & 0x04) >> 2);
+                       charROM[i + j + 6] = ((b3 & 0x02) << 1) | ((b2 & 0x20) >> 4) | ((b2 & 0x02) >> 1);
+                       charROM[i + j + 7] = ((b3 & 0x01) << 2) | ((b2 & 0x10) >> 3) | (b2 & 0x01);
                }
        }
 
-       f1.close();
-       f2.close();
+       fclose(file1);
+       fclose(file2);
+
+       file1 = fopen("./ROMs/" ROM5, "rb");
+       file2 = fopen("./ROMs/" ROM6, "rb");
 
-       f1.open("./ROMs/"ROM5, ios::binary | ios::in);
-       f2.open("./ROMs/"ROM6, ios::binary | ios::in);
+       if (!file1 || !file2)
+       {
+               printf("Could not open either " ROM5 " or " ROM6 "!\n");
+               return false;
+       }
 
        for(long i=0x40000; i<0x60000; i+=64)
        {
                for(int j=0; j<64; j+=8)
                {
-                       f1.get(b1);  f1.get(b2);  f2.get(b3);
-                       b3 ^= 0xFF;                             // Invert top data
-                       chr_rom[i+j] = ((b3 & 0x80) >> 5) | ((b1 & 0x80) >> 6) | ((b1 & 0x08) >> 3);
-                       chr_rom[i+j+1] = ((b3 & 0x40) >> 4) | ((b1 & 0x40) >> 5) | ((b1 & 0x04) >> 2);
-                       chr_rom[i+j+2] = ((b3 & 0x20) >> 3) | ((b1 & 0x20) >> 4) | ((b1 & 0x02) >> 1);
-                       chr_rom[i+j+3] = ((b3 & 0x10) >> 2) | ((b1 & 0x10) >> 3) | (b1 & 0x01);
-                       chr_rom[i+j+4] = ((b3 & 0x08) >> 1) | ((b2 & 0x80) >> 6) | ((b2 & 0x08) >> 3);
-                       chr_rom[i+j+5] = (b3 & 0x04)        | ((b2 & 0x40) >> 5) | ((b2 & 0x04) >> 2);
-                       chr_rom[i+j+6] = ((b3 & 0x02) << 1) | ((b2 & 0x20) >> 4) | ((b2 & 0x02) >> 1);
-                       chr_rom[i+j+7] = ((b3 & 0x01) << 2) | ((b2 & 0x10) >> 3) | (b2 & 0x01);
+                       uint8_t b1 = (uint8_t)fgetc(file1);
+                       uint8_t b2 = (uint8_t)fgetc(file1);
+                       uint8_t b3 = (uint8_t)fgetc(file2) ^ 0xFF;
+                       charROM[i + j + 0] = ((b3 & 0x80) >> 5) | ((b1 & 0x80) >> 6) | ((b1 & 0x08) >> 3);
+                       charROM[i + j + 1] = ((b3 & 0x40) >> 4) | ((b1 & 0x40) >> 5) | ((b1 & 0x04) >> 2);
+                       charROM[i + j + 2] = ((b3 & 0x20) >> 3) | ((b1 & 0x20) >> 4) | ((b1 & 0x02) >> 1);
+                       charROM[i + j + 3] = ((b3 & 0x10) >> 2) | ((b1 & 0x10) >> 3) | (b1 & 0x01);
+                       charROM[i + j + 4] = ((b3 & 0x08) >> 1) | ((b2 & 0x80) >> 6) | ((b2 & 0x08) >> 3);
+                       charROM[i + j + 5] = (b3 & 0x04)        | ((b2 & 0x40) >> 5) | ((b2 & 0x04) >> 2);
+                       charROM[i + j + 6] = ((b3 & 0x02) << 1) | ((b2 & 0x20) >> 4) | ((b2 & 0x02) >> 1);
+                       charROM[i + j + 7] = ((b3 & 0x01) << 2) | ((b2 & 0x10) >> 3) | (b2 & 0x01);
                }
        }
 
-       f1.close();
-       f2.close();
+       fclose(file1);
+       fclose(file2);
 
-       return true;                                // Made it!
+       return true;
 }
 
-
-//
-// Get length of sample from WAV format
-//
-uint32_t GetWAVLength(fstream & file)
+void SaveThunderState(const char * filename)
 {
-       char ch;
-       uint32_t len;
-
-       file.ignore(16);                                                                        // Skip header BS
+       WriteLog("Main: Saving Thunder state...\n");
+       FILE * file = fopen(filename, "wb");
 
-       for(int i=0; i<2; i++)
+       if (!file)
        {
-               file.get(ch);  len = (int)(uint8_t)ch;
-               file.get(ch);  len |= (int)(uint8_t)ch << 8;
-               file.get(ch);  len |= (int)(uint8_t)ch << 16;
-               file.get(ch);  len |= (int)(uint8_t)ch << 24;
-
-               // Skip intermediate data
-               file.ignore(len + 4);
+               WriteLog("Could not open file \"%s\" for writing!\n", filename);
+               return;
        }
 
-       // & finally get length of data
-       file.get(ch);  len = (int)(uint8_t)ch;
-       file.get(ch);  len |= (int)(uint8_t)ch << 8;
-       file.get(ch);  len |= (int)(uint8_t)ch << 16;
-       file.get(ch);  len |= (int)(uint8_t)ch << 24;
+       // Write out header
+       size_t ignored = fwrite(stateHeader, 1, 19, file);
 
-       return len;
-}
+       // Write out CPUs' state
+       ignored = fwrite(&cpu1, 1, sizeof(cpu1), file);
+       ignored = fwrite(&cpu2, 1, sizeof(cpu2), file);
+       ignored = fwrite(&mcu, 1, sizeof(mcu), file);
 
+       // Write out main memory
+       ignored = fwrite(gram1, 1, 0x10000, file);
+       ignored = fwrite(mcuMem, 1, 0x10000, file);
 
-//
-// Load PSG samples from disk
-//
-void LoadPSGs(void)
-{
-       char file[40];
-       char ch;
-       uint32_t len;
-
-       for(int i=0; i<16; i++)
-       {
-               fstream fp;
+       // Write out state variables
+       WriteLong(file, banksw1);
+       WriteLong(file, banksw2);
+       fputc((uint8_t)copySprites, file);
+       fputc(input1.byte, file);
+       fputc(input2.byte, file);
+       fputc(input3.byte, file);
+       fputc(input4.byte, file);
+       fputc(input5.byte, file);
 
-               psg_adrs[i] = NULL;                                                             // Zero out pointer
-               sprintf(file, "./sounds/psg%i.wav", i);                 // Create filename
+       PSGSaveState(file);
+       YMSaveState(file);
 
-               fp.open(file, ios::binary | ios::in);                   // Attempt to open it...
+       fclose(file);
+}
 
-               if (fp)
-               {
-                       len = GetWAVLength(fp);                                         // Get WAV data length...
-                       psg_adrs[i] = new uint8_t[len];                         // Attempt to allocate space...
+bool LoadThunderState(const char * filename)
+{
+       WriteLog("Main: Loading Thunder state...\n");
+       FILE * file = fopen(filename, "rb");
 
-                       if (psg_adrs[i] != NULL)
-                       {
-                               for(int j=0; j<(signed)len; j++)
-                               {
-                                       fp.get(ch);
-                                       psg_adrs[i][j] = ch;                            // & load it in...
-                               }
+       if (!file)
+       {
+               WriteLog("Could not open file \"%s\" for reading!\n", filename);
+               return false;
+       }
 
-                               psg_lens[i] = len;
-                               printf("Found sample file: %s\t[Length: %u]\n", file, len);
-                       }
+       uint8_t buffer[19];
+       size_t ignored = fread(buffer, 1, 19, file);
 
-                       fp.close();
-               }
+       // Sanity check...
+       if (memcmp(buffer, stateHeader, 19) != 0)
+       {
+               fclose(file);
+               WriteLog("File \"%s\" is not a valid Thunder save state file!\n", filename);
+               return false;
        }
-}
 
+       // Read CPUs' state
+       ignored = fread(&cpu1, 1, sizeof(cpu1), file);
+       ignored = fread(&cpu2, 1, sizeof(cpu2), file);
+       ignored = fread(&mcu, 1, sizeof(mcu), file);
 
-#if 0
-//
-// Load FM samples from disk
-//
-void LoadFMs(void)
-{
-       char file[200];
-       char ch;
-       uint32_t len;
+       // Read main memory
+       ignored = fread(gram1, 1, 0x10000, file);
+       ignored = fread(mcuMem, 1, 0x10000, file);
 
-       for(int i=0; i<14; i++)
-       {
-               fstream fp;
+       // Read in state variables
+       banksw1 = ReadLong(file);
+       banksw2 = ReadLong(file);
+       copySprites = (bool)fgetc(file);
+       input1.byte = fgetc(file);
+       input2.byte = fgetc(file);
+       input3.byte = fgetc(file);
+       input4.byte = fgetc(file);
+       input5.byte = fgetc(file);
 
-               fm_adrs[i] = NULL;                                              // Zero out pointer
-               sprintf(file, "./sounds/fm%i.wav", i);  // Create filename
-               fp.open(file, ios::binary | ios::in);   // Attempt to open it...
+       PSGLoadState(file);
+       YMLoadState(file);
 
-               if (!fp)
-                       continue;
+       fclose(file);
 
-               len = GetWAVLength(fp);                                 // Get WAV length...
-               fm_adrs[i] = new uint8_t[len];                  // Attempt to allocate space...
+       // Make sure things are in a sane state before execution :-P
+       cpu1.RdMem = MainReadMemory;
+       cpu1.WrMem = MainWriteMemory;
 
-               if (fm_adrs[i] != NULL)
-               {
-                       for(int j=0; j<(signed)len; j++)
-                       {
-                               fp.get(ch);
-                               fm_adrs[i][j] = ch;                                     // & load it in...
-                       }
+       cpu2.RdMem = SubReadMemory;
+       cpu2.WrMem = SubWriteMemory;
 
-                       fm_lens[i] = len;
-                       printf("Found sample file: %s\t[Length: %u]\n", file, len);
-               }
+       mcu.RdMem = MCUReadMemory;
+       mcu.WrMem = MCUWriteMemory;
 
-               fp.close();
-       }
+       return true;
 }
-#endif
-
 
 //
 // Main loop
@@ -677,221 +511,147 @@ int main(int argc, char * argv[])
 {
        InitLog("thunder.log");
 
-extern bool disasm;    // From 'V6809.CPP'
-       extern bool charbase;                                           // From 'SCREEN.CPP'
-       charbase = false;
-
-       char lbuff[80];
-       fstream ff;                       // Declare fstream without file hooks...
-       bool brk = false, brk2 = false;   // Breakpoint set flag
-       uint16_t brkpnt, brkpnt2;             // Where the breakpoint is...
-       bool running;                     // CPU running state flag...
-       bool self_test = false;           // Self-test switch
-       bool scr_type = false;            // false=chars, true=pixels
-       uint16_t debounce = 0;                // Key de-bounce counter
-       uint16_t fire_debounce = 0;           // Fire button debounce counter
-       uint8_t x;                           // General placeholder...
-       bool active = true;                                             // Program running flag
-
-       SDL_Event event;                                                                // SDL "event"
-       extern uint8_t palette[768];                                    // Screen physical palette
+       bool running;                                   // CPU running state flag...
+       SDL_Event event;                                // SDL "event"
        uint32_t ticks, oldTicks;
+       uint8_t frameTickCount = 0;
 
-       cout << endl << "THUNDER v"THUNDER_VERSION" ";
-       cout << "by James Hammons" << endl;
-       cout << "Serial #20149417 / Prerelease" << endl;
-       cout << "© 2003, 2014 Underground Software" << endl << endl;
-
-       cout << "This emulator is free software. If you paid for it you were RIPPED OFF"
-               << endl << endl;
+       printf("THUNDER v" THUNDER_VERSION " by James Hammons\n");
+       printf("Serial #20230113 / Prerelease\n");
+       printf("© 2003, 2023 Underground Software\n\n");
+       printf("This emulator is free software. If you paid for it you were RIPPED OFF\n\n");
 
 //     SDL_WM_SetCaption("Thunder v"THUNDER_VERSION" ", "Thunder");
 
-       gram = gram1;  grom = grom1;           // Needed only for debugger
-
-       memset(gram, 0, 0x10000);
-       memset(grom, 0, 0x10000);
-       memset(gram2, 0, 0x10000);
-       memset(grom2, 0, 0x10000);
-
-       game_over_switch = 0;   // Init game over delay
-
-       cout << "Loading ROMs..." << endl;
-       if (!ReadColorPROMs())                   // Load virtual PROMs
-       { cout << "Could not open PROM files!" << endl;  return -1; }
+       printf("Loading ROMs...\n");
 
-       if (!LoadImg(ROM1, grom1, 0x8000, 0x8000)) // Load $8000-$FFFF 1st ROM
-       { cout << "Could not open file '" << ROM1 << "'!" << endl;  return -1; }
+       if (!ReadColorPROMs())
+               return -1;
 
-       if (!LoadImg(ROM2, grom2, 0x8000, 0x8000)) // Load $8000-$FFFF 2nd ROM
-       { cout << "Could not open file '" << ROM2 << "'!" << endl;  return -1; }
+       // Load $8000-$FFFF 1st ROM
+       if (!LoadImg(ROM1, grom1, 0x8000, 0x8000))
+               return -1;
 
-       if (!LoadImg(ROM3, grom3, 0, 0x8000))      // Load 3rd ROM into its own space
-       { cout << "Could not open file '" << ROM3 << "'!" << endl;  return -1; }
+        // Load $8000-$FFFF 2nd ROM
+       if (!LoadImg(ROM2, grom2, 0x8000, 0x8000))
+               return -1;
 
-//     if (!LoadImg(ROM4, grom4, 0, 0x8000))      // Load 4rd ROM into its own space
-//     { cout << "Could not open file '" << ROM4 << "'!" << endl;  return -1; }
+       // Load 3rd ROM into its own space
+       if (!LoadImg(ROM3, grom3, 0, 0x8000))
+               return -1;
 
-       if (!LoadImg(ROM17, data_rom, 0,       0x10000))  // Load 17th ROM
-       { cout << "Could not open file '" << ROM17 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM17, data_rom, 0,       0x10000))
+               return -1;
 
-       if (!LoadImg(ROM18, data_rom, 0x10000, 0x10000))  // Load 18th ROM
-       { cout << "Could not open file '" << ROM18 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM18, data_rom, 0x10000, 0x10000))
+               return -1;
 
-       if (!LoadImg(ROM19, data_rom, 0x20000, 0x10000))  // Load 19th ROM
-       { cout << "Could not open file '" << ROM19 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM19, data_rom, 0x20000, 0x10000))
+               return -1;
 
-       if (!LoadImg(ROM20, data_rom, 0x30000, 0x10000))  // Load 20th ROM
-       { cout << "Could not open file '" << ROM20 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM20, data_rom, 0x30000, 0x10000))
+               return -1;
 
-       if (!LoadImg(ROM9,  spr_rom, 0,       0x10000))   // Load 9th ROM
-       { cout << "Could not open file '" << ROM9 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM9,  spr_rom, 0,       0x10000))
+               return -1;
 
-       if (!LoadImg(ROM10, spr_rom, 0x10000, 0x10000))   // Load 10th ROM
-       { cout << "Could not open file '" << ROM10 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM10, spr_rom, 0x10000, 0x10000))
+               return -1;
 
-       if (!LoadImg(ROM11, spr_rom, 0x20000, 0x10000))   // Load 11th ROM
-       { cout << "Could not open file '" << ROM11 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM11, spr_rom, 0x20000, 0x10000))
+               return -1;
 
-       if (!LoadImg(ROM12, spr_rom, 0x30000, 0x10000))   // Load 12th ROM
-       { cout << "Could not open file '" << ROM12 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM12, spr_rom, 0x30000, 0x10000))
+               return -1;
 
-       if (!LoadImg(ROM13, spr_rom, 0x40000, 0x10000))   // Load 13th ROM
-       { cout << "Could not open file '" << ROM13 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM13, spr_rom, 0x40000, 0x10000))
+               return -1;
 
-       if (!LoadImg(ROM14, spr_rom, 0x50000, 0x10000))   // Load 14th ROM
-       { cout << "Could not open file '" << ROM14 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM14, spr_rom, 0x50000, 0x10000))
+               return -1;
 
-       if (!LoadImg(ROM15, spr_rom, 0x60000, 0x10000))   // Load 15th ROM
-       { cout << "Could not open file '" << ROM15 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM15, spr_rom, 0x60000, 0x10000))
+               return -1;
 
-       if (!LoadImg(ROM16, spr_rom, 0x70000, 0x10000))   // Load 16th ROM
-       { cout << "Could not open file '" << ROM16 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM16, spr_rom, 0x70000, 0x10000))
+               return -1;
 
-       if (!LoadImg(ROM21, voice_rom, 0, 0x10000))  // Load 21st ROM
-       { cout << "Could not open file '" << ROM21 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM21, voice_rom, 0, 0x10000))
+               return -1;
 
-       if (!LoadImg(ROM22, voice_rom, 0x10000, 0x10000))  // Load 22nd ROM
-       { cout << "Could not open file '" << ROM22 << "'!" << endl;  return -1; }
+       if (!LoadImg(ROM22, voice_rom, 0x10000, 0x10000))
+               return -1;
 
-       if (!UnpackFonts())                         // Load 5, 6, 7, 8th ROMs
-       {
-               cout << "Could not open font files!" << endl;
+       // Load 5, 6, 7, 8th ROMs
+       if (!UnpackFonts())
                return -1;
-       }
 
        // Load MCU program + data
-       if (!LoadImg(MCUROM, mcuMem, 0xF000, 0x1000))   // Load MCU ROM
-       { cout << "Could not open file '" << MCUROM << "'!" << endl;  return -1; }
-
-       if (!LoadImg(ROM4, mcuMem, 0x4000, 0x8000))             // Load 4th ROM
-       { cout << "Could not open file '" << ROM4 << "'!" << endl;  return -1; }
-
-       // Load samples if they're there...
-       LoadPSGs();
-//     LoadFMs();
+       if (!LoadImg(MCUROM, mcuMem, 0xF000, 0x1000))
+               return -1;
 
-       // Set up V6809 execution contexts
+       if (!LoadImg(ROM4, mcuMem, 0x4000, 0x8000))
+               return -1;
 
+       // Set up V6809, V63701 execution contexts
        memset(&cpu1, 0, sizeof(V6809REGS));
-       cpu1.RdMem = RdMem;
-       cpu1.WrMem = WrMem;
-       cpu1.cpuFlags |= V6809_ASSERT_LINE_RESET;
+       cpu1.RdMem = MainReadMemory;
+       cpu1.WrMem = MainWriteMemory;
+       cpu1.cpuFlags |= V6809_LINE_RESET;
 
        memset(&cpu2, 0, sizeof(V6809REGS));
-       cpu2.RdMem = RdMemB;
-       cpu2.WrMem = WrMemB;
-       cpu2.cpuFlags |= V6809_ASSERT_LINE_RESET;
+       cpu2.RdMem = SubReadMemory;
+       cpu2.WrMem = SubWriteMemory;
+       cpu2.cpuFlags |= V6809_LINE_RESET;
 
        memset(&mcu, 0, sizeof(V63701REGS));
        mcu.RdMem = MCUReadMemory;
        mcu.WrMem = MCUWriteMemory;
-       mcu.cpuFlags |= V63701_ASSERT_LINE_RESET;
+       mcu.cpuFlags |= V63701_LINE_RESET;
 
-       uint32_t my_clock = 0;
-       running = true;                                                         // Set running status...
-       trace1 = false;
-       SetRefreshRate(refresh2);                                       // Tell GUI our refresh rate
+       running = true;
 
        // Set all inputs to inactive...
-       input1.byte = input2.byte = input3.byte = input4.byte = input5.byte = 0xFF;
-//     mcu.port1 = 0xFF;
-//     mcu.port2 = 0xFF;
-#if 0
-       // This is data that is supposed to come from the MCU... So that's why it hangs
-       gram1[0x4182] = 0xA6;          // Temp kludge
-       gram1[0x4184] = 0xA6;
-       gram1[0x4183] = 0x00;          // More of the same
-       gram1[0x4185] = 0x00;
-#endif
-       banksw1 = 0;                   // Will this work?
+       input1.byte = input2.byte = input3.byte = 0xFF;
+       banksw1 = 0;
        banksw2 = 0;
-//        iclock = 0;                // Reset instr clock #1...
        InitGUI();                 // Reset # of coins
 
+       // Set up DIP switches...
+       input4.bit.b0 = 1;              // DSW B-0: Continues (1 = 6, 0 = 3)
+       input4.bit.b1 = 1;              // DSW B-2: ???
+       input4.bit.b2 = 1;              // DSW B-4: Difficulty (1 = normal, 0 = easy)
+       input4.bit.b3 = 1;              // DSW B-6: Bonus lives (70K/200K = 1, 100K/300K = 0)
+       input4.bit.b4 = 1;              // DSW A-0: Coin #2 credit
+       input4.bit.b5 = 1;              // DSW A-2: Freeze mode (0 = freeze)
+       input4.bit.b6 = 1;              // DSW A-4: Attract mode sound (1 = on)
+       input4.bit.b7 = 1;              // DSW A-6: Coin #1 credit
+
+       input5.bit.b0 = 1;              // DSW B-1: Cabinet type (1 = A, 0 = B)
+       input5.bit.b1 = 0;              // DSW B-3: Level select (0 = on)
+       input5.bit.b2 = 0;              // DSW B-5: Time (1 = 120, 0 = 150)
+       input5.bit.b3 = 0;              // DSW B-7: Lives (1 = 3, 0 = 5)
+       input5.bit.b4 = 1;              // DSW A-1: Coin #2 credit
+       input5.bit.b5 = 1;              // DSW A-3: Invulnerability (0 = on)
+       input5.bit.b6 = 1;              // DSW A-5: Coin #1 credit
+       input5.bit.b7 = 1;              // DSW A-7: Service mode
+
 WriteLog("About to set up screen...\n");
        InitVideo();
 
        oldTicks = SDL_GetTicks();
 
 WriteLog("About to set up audio...\n");
-#if 0
-       // This crap SHOULD be in sound.cpp (not yet created)...
-       SDL_AudioSpec desired, obtained;
-       desired.freq = 22050;
-       desired.format = AUDIO_U8;
-       desired.channels = 1;
-       desired.samples = 600;
-       desired.callback = SoundFunc;
-       desired.userdata = NULL;
-       // Also, should check to see if it got the hardware it needed, correct sample size, etc.
-       if (SDL_OpenAudio(&desired, &obtained) < 0)
-       {
-               cout << "Couldn't open audio: " << SDL_GetError() << endl;
-               return -1;
-       }
-
-       SDL_PauseAudio(0);                                                      // Get that audio going!
-#else
        InitSound();
-#endif
-
-memset(scrBuffer, 0xFF, VIRTUAL_SCREEN_WIDTH*VIRTUAL_SCREEN_HEIGHT*sizeof(uint32_t));
-RenderScreenBuffer();
 
 WriteLog("About to enter main loop...\n");
        while (running)
        {
-               HandleGUIDebounce();                                    // Debounce GUI keys
-
-#if 0
-               if (game_over_switch)
-               {
-                       game_over_switch--;  // Countdown...
-
-                       if (game_over_switch == 0)
-                               gram1[0x4380] = 0; // Kill music!
-               }
-#endif
+//             HandleGUIDebounce();                                    // Debounce GUI keys
 
 // Dipswitches are presented to the main CPUs as 0 or 1 at locations
 // $423D - $425B by the MCU
 
-//testing... (works)
-//gram1[0x423D] = 1;
-               //gram1[0x423D] = self_test;                    // Reset DSW1-1
-//             gram1[0x4268] = 0;                                              // Reset Video test
-//             gram1[0x427A] = 0;  gram1[0x427C] = 0;
-               //gram1[0x427B] = 0;  gram1[0x427D] = 0;
-//             gram1[0x427E] = 0;//  gram1[0x427F] = 0;
-//             gram1[0x4280] = 0;//  gram1[0x4281] = 0;
-               //gram1[0x4276] = 0;
-//             gram1[0x426A] = 0;
-               //gram1[0x4278] = 0;
-//             gram1[0x426C] = 0;
-//             gram1[0x4262] = 0;  gram1[0x4260] = 0;
-               //gram1[0x4247] = 0;
-
                // SDL key handling...
 
                SDL_Event event;
@@ -908,25 +668,53 @@ WriteLog("About to enter main loop...\n");
                                {
 //                                     SpawnSound(USERSOUND, SCAMERA);
                                        SavePCXSnapshot();
-//                                     debounce = 10;
                                }
 #if 1
                                else if (event.key.keysym.sym == SDLK_5)
                                        input1.bit.b5 = 0;
                                else if (event.key.keysym.sym == SDLK_1)
                                        input1.bit.b6 = 0;
-                               else if (event.key.keysym.sym == SDLK_RIGHT)
+                               else if (event.key.keysym.sym == SDLK_2)
+                                       input2.bit.b6 = 0;
+                               else if (event.key.keysym.sym == SDLK_c)        // Left
                                        input3.bit.b5 = 0;
-                               else if (event.key.keysym.sym == SDLK_LEFT)
+                               else if (event.key.keysym.sym == SDLK_z)        // Right
                                        input3.bit.b4 = 0;
-                               else if (event.key.keysym.sym == SDLK_UP)
+                               else if (event.key.keysym.sym == SDLK_s)        // Up
                                        input2.bit.b2 = 0;
-                               else if (event.key.keysym.sym == SDLK_DOWN)
+                               else if (event.key.keysym.sym == SDLK_x)        // Down
                                        input1.bit.b2 = 0;
-                               else if (event.key.keysym.sym == SDLK_q)        // (Q)  Jump
+                               else if (event.key.keysym.sym == SDLK_k)        // Jump
                                        input1.bit.b1 = 0;
-                               else if (event.key.keysym.sym == SDLK_e)        // (E) Fire
+                               else if (event.key.keysym.sym == SDLK_l)        // Fire
                                        input3.bit.b3 = 0;
+
+                               else if (event.key.keysym.sym == SDLK_F1)       // Service mode
+                                       input5.bit.b7 = !input5.bit.b7;
+
+                               else if (event.key.keysym.sym == SDLK_q)
+                                       input4.bit.b7 = !input4.bit.b7;
+                               else if (event.key.keysym.sym == SDLK_w)
+                                       input5.bit.b6 = !input5.bit.b6;
+                               else if (event.key.keysym.sym == SDLK_e)
+                                       input5.bit.b5 = !input5.bit.b5;
+                               else if (event.key.keysym.sym == SDLK_r)
+                                       input5.bit.b4 = !input5.bit.b4;
+                               else if (event.key.keysym.sym == SDLK_t)
+                                       input5.bit.b3 = !input5.bit.b3;
+                               else if (event.key.keysym.sym == SDLK_y)
+                                       input5.bit.b2 = !input5.bit.b2;
+                               else if (event.key.keysym.sym == SDLK_u)
+                                       input5.bit.b1 = !input5.bit.b1;
+                               else if (event.key.keysym.sym == SDLK_i)
+                                       input5.bit.b0 = !input5.bit.b0;
+
+                               // Quick'n'Dirty save state handling...  :-P
+                               else if (event.key.keysym.sym == SDLK_F8)
+                                       SaveThunderState("thun0001.state");
+                               else if (event.key.keysym.sym == SDLK_F9)
+                                       LoadThunderState("thun0001.state");
+
 #else
                                else if (event.key.keysym.sym == SDLK_1)
                                        input1.bit.b0 = 0;
@@ -981,17 +769,19 @@ WriteLog("About to enter main loop...\n");
                                        input1.bit.b5 = 1;
                                else if (event.key.keysym.sym == SDLK_1)
                                        input1.bit.b6 = 1;
-                               else if (event.key.keysym.sym == SDLK_RIGHT)
+                               else if (event.key.keysym.sym == SDLK_2)
+                                       input2.bit.b6 = 1;
+                               else if (event.key.keysym.sym == SDLK_c)
                                        input3.bit.b5 = 1;
-                               else if (event.key.keysym.sym == SDLK_LEFT)
+                               else if (event.key.keysym.sym == SDLK_z)
                                        input3.bit.b4 = 1;
-                               else if (event.key.keysym.sym == SDLK_UP)
+                               else if (event.key.keysym.sym == SDLK_s)
                                        input2.bit.b2 = 1;
-                               else if (event.key.keysym.sym == SDLK_DOWN)
+                               else if (event.key.keysym.sym == SDLK_x)
                                        input1.bit.b2 = 1;
-                               else if (event.key.keysym.sym == SDLK_q)        // (Q)  Jump
+                               else if (event.key.keysym.sym == SDLK_k)        // (Q)  Jump
                                        input1.bit.b1 = 1;
-                               else if (event.key.keysym.sym == SDLK_e)        // (E) Fire
+                               else if (event.key.keysym.sym == SDLK_l)        // (E) Fire
                                        input3.bit.b3 = 1;
 #else
                                if (event.key.keysym.sym == SDLK_1)
@@ -1218,52 +1008,12 @@ WriteLog("About to enter main loop...\n");
 
                                if (keys[SDLK_F7])
                                        SpawnSound(USERSOUND, 0);       // Do user sound (F7)
-
-//                             if (keys[SDLK_F8])
-//                             {
-//                                     gram1[0x4380] = 0;                      // (F8) kill music (this worx)
-//                                     charbase = false;                       // Switch chars out...
-//                             }
-//                             if (keys[SDLK_F9])  gram1[0x4285] = 1;          // (F9) strobe unknown loc
-
-                               if (keys[SDLK_F11])                             // (F11)
-                               {
-                                       Execute6809(&cpu1, 10);
-                                       Execute6809(&cpu2, 10);
-                               }
-//                     }
-//F12 is used above, but the values are ignored. So we'll do it here too.
-                               if (keys[SDLK_F12])
-                               {
-                                       cpu1.cpuFlags |= V6809_ASSERT_LINE_RESET;
-                                       cpu2.cpuFlags |= V6809_ASSERT_LINE_RESET;
-                               }
-
-                               if (keys[SDLK_d])                               // (D) start disassembly
-                                       disasm = true;
-#if 0
-       if (keys[SDLK_k])
-               gram1[0x5606] = 0x00;
-       if (keys[SDLK_l])
-       {
-               gram1[0x5607] = 0x01; // Hangs here... (CPU #1 waiting...)
-               WriteLog("\nMAIN: Stuffed $01 in $5607!!!\n\n");
-       }
-       if (keys[SDLK_o])
-       {
-               gram1[0x5FF3] = 0x02;
-               WriteLog("\nMAIN: Stuffed $02 in $5FF3!!!\n\n");
-       }
-#endif
 #endif
 
-               if (enable_cpu)
-//                             if (true)
-               {
-                       // We can do this here because we're not executing the cores yet.
-                       cpu1.cpuFlags |= V6809_ASSERT_LINE_IRQ;
-                       cpu2.cpuFlags |= V6809_ASSERT_LINE_IRQ;
-                       mcu.cpuFlags |= V63701_ASSERT_LINE_IRQ;
+               // We can do this here because we're not executing the cores yet.
+               cpu1.cpuFlags |= V6809_LINE_IRQ;
+               cpu2.cpuFlags |= V6809_LINE_IRQ;
+               mcu.cpuFlags |= V63701_LINE_IRQ;
 //                                     while (cpu1.clock < 25000)
 // 1.538 MHz = 25633.333... cycles per frame (1/60 s)
 // 25600 cycles/frame
@@ -1272,174 +1022,48 @@ WriteLog("About to enter main loop...\n");
 // 40 works, until it doesn't... :-P
 // 640 * 40
 // 800 * 32
+// 20 seems to work...  :-)
 // Interesting, putting IRQs at 30 Hz makes it run at the correct speed. Still hangs in the demo, though.
-                       for(uint32_t i=0; i<640; i++)
-//                                     for(uint32_t i=0; i<1280; i++)
-                       {
-                               // Gay, but what are ya gonna do?
-                               // There's better ways, such as keeping track of when slave writes to master, etc...
-                               Execute6809(&cpu1, 40);
-                               Execute6809(&cpu2, 40);
-
-                               // MCU runs at 1,536,000 Hz
-                               // 1536000 / 60 / 640 == 40
-                               Execute63701(&mcu, 40);
-                       }
-               } // END: enable_cpu
+//             for(int i=0; i<640; i++)
+               for(int i=0; i<1280; i++)
+               {
+                       // Gay, but what are ya gonna do?
+                       // There's better ways, such as keeping track of when slave writes to master, etc...
+//                     Execute6809(&cpu1, 40);
+//                     Execute6809(&cpu2, 40);
+                       Execute6809(&cpu1, 20);
+                       Execute6809(&cpu2, 20);
+
+                       // MCU runs at 1,536,000 Hz
+                       // 1536000 / 60 / 640 == 40
+//                     Execute63701(&mcu, 40);
+                       Execute63701(&mcu, 20);
+               }
+
+               BlitChar(charROM, gram1);
+
+               // Make sure that the sprite RAM lags by one frame...  :-)
+               if (copySprites)
+               {
+                       CopySprites();
+                       copySprites = false;
+               }
+
+               frameTickCount++;
+
+               if (frameTickCount == 3)
+                       frameTickCount = 0;
 
                // Speed throttling happens here...
-               while (SDL_GetTicks() - oldTicks < 16)  // Actually, it's 16.66... Need to account for that somehow
-//                             while (SDL_GetTicks() - oldTicks < 32)  // Actually, it's 16.66... Need to account for that somehow
+               // Actually, it's 16.66... Need to account for that somehow [DONE]
+               while (SDL_GetTicks() - oldTicks < (16 + (frameTickCount == 2 ? 1 : 0)))
                        SDL_Delay(1);                           // Release our timeslice...
 
                oldTicks = SDL_GetTicks();
-//cout << "Finished frame..." << endl;
        }
 
        SDL_Quit();
-
-       // Deallocate sounds if they were loaded
-       for(int i=0; i<16; i++)
-               if (psg_adrs[i])
-                       delete[] psg_adrs[i];
-
-#if 0
-       for(int i=0; i<14; i++)
-               if (fm_adrs[i])
-                       delete[] fm_adrs[i];
-#endif
-
        LogDone();
 
        return 1;
 }
-
-#if 0
-Hitachi uC runs at 6.144 MHz
-YM2151 runs at 3.579580 MHz
-
-
-Rolling Thunder Memory map
---------------------------
-Most of the decoding is done by custom chips (CUS47 and CUS41), so the memory
-map is inferred by program behaviour. The customs also handle internally irq
-and watchdog.
-
-The main CPU memory map is the same in all games because CUS47 is used by all
-games. The sub CPU and sound CPU, on the other hand, change because CUS41 is
-replaced by other chips.
-
-All RAM is shared between main and sub CPU, except for sound RAM which is
-shared between main and sound CPU; the portion of object RAM that is overlapped
-by sound RAM is used exclusively by the sub CPU.
-
-MAIN CPU:
-
-Address             Dir Data     Name      Description
-------------------- --- -------- --------- -----------------------
-000x xxxx xxxx xxxx R/W xxxxxxxx SCROLL0   tilemap 0/1 RAM (shared with sub CPU)
-001x xxxx xxxx xxxx R/W xxxxxxxx SCROLL1   tilemap 2/3 RAM (shared with sub CPU)
-0100 00xx xxxx xxxx R/W xxxxxxxx SOUND     sound RAM (through CUS30, shared with MCU)
-0100 0000 xxxx xxxx R/W xxxxxxxx           portion holding the sound wave data
-0100 0001 00xx xxxx R/W xxxxxxxx           portion holding the sound registers
-010x xxxx xxxx xxxx R/W xxxxxxxx OBJECT    work RAM (shared with sub CPU) [1]
-0101 1xxx xxxx xxxx R/W xxxxxxxx           portion holding sprite registers
-011x xxxx xxxx xxxx R   xxxxxxxx ROM 9D    program ROM (banked) [2]
-1xxx xxxx xxxx xxxx R   xxxxxxxx ROM 9C    program ROM
-1000 00-- ---- ----   W --------           watchdog reset (RES generated by CUS47)
-1000 01-- ---- ----   W --------           main CPU irq acknowledge (IRQ generated by CUS47)
-1000 1x-- ---- ----   W -------- BANK      tile gfx bank select (data is in A10) (latch in CUS47)
-1001 00-- ---- -x0x   W xxxxxxxx LATCH0    tilemap 0/1 X scroll + priority
-1001 00-- ---- -x10   W xxxxxxxx LATCH0    tilemap 0/1 Y scroll
-1001 00-- ---- --11   W ------xx BAMNKM    ROM 9D bank select
-1001 01-- ---- -x0x   W xxxxxxxx LATCH1    tilemap 2/3 X scroll + priority
-1001 01-- ---- -x10   W xxxxxxxx LATCH1    tilemap 2/3 Y scroll
-1001 01-- ---- --11   W ------xx BAMNKS    ROM 12D bank select
-1100 00-- ---- ----   W xxxxxxxx BACKCOLOR background color
-
-[1] Note that this is partially overlapped by sound RAM
-[2] In Rolling Thunder and others, replaced by the ROM/voice expansion board
-
-
-SUB CPU:
-
-Address             Dir Data     Name      Description
-------------------- --- -------- --------- -----------------------
-000x xxxx xxxx xxxx R/W xxxxxxxx SUBOBJ    work RAM (shared with main CPU)
-0001 1xxx xxxx xxxx R/W xxxxxxxx           portion holding sprite registers
-001x xxxx xxxx xxxx R/W xxxxxxxx SUBSCR0   tilemap 0/1 RAM (shared with main CPU)
-010x xxxx xxxx xxxx R/W xxxxxxxx SUBSCR1   tilemap 2/3 RAM (shared with main CPU)
-011x xxxx xxxx xxxx R   xxxxxxxx ROM 12D   program ROM (banked) [1]
-1xxx xxxx xxxx xxxx R   xxxxxxxx ROM 12C   program ROM
-1000 0--- ---- ----   W --------           watchdog reset (MRESET generated by CUS41)
-1000 1--- ---- ----   W --------           main CPU irq acknowledge (generated by CUS41)
-1101 0--- ---- -x0x   W xxxxxxxx LATCH0    tilemap 0/1 X scroll + priority
-1101 0--- ---- -x10   W xxxxxxxx LATCH0    tilemap 0/1 Y scroll
-1101 0--- ---- --11   W ------xx BAMNKM    ROM 9D bank select
-1101 1--- ---- -x0x   W xxxxxxxx LATCH1    tilemap 2/3 X scroll + priority
-1101 1--- ---- -x10   W xxxxxxxx LATCH1    tilemap 2/3 Y scroll
-1101 1--- ---- --11   W ------xx BAMNKS    ROM 12D bank select
-
-[1] Only used by Rolling Thunder
-
-
-MCU:
-
-Address             Dir Data     Name      Description
-------------------- --- -------- --------- -----------------------
-0000 0000 xxxx xxxx                        MCU internal registers, timers, ports and RAM
-0001 xxxx xxxx xxxx R/W xxxxxxxx RAM 3F    sound RAM (through CUS30, partially shared with main CPU)
-0001 0000 xxxx xxxx R/W xxxxxxxx           portion holding the sound wave data
-0001 0001 00xx xxxx R/W xxxxxxxx           portion holding the sound registers
-0010 0--- --00 ---x R/W xxxxxxxx YMCS      YM2151
-0010 0--- --01 ----                        n.c.
-0010 0--- --10 ---- R   xxxxxxxx PORTA     switch inputs
-0010 0--- --11 ---- R   xxxxxxxx PORTB     dip switches
-01xx xxxx xxxx xxxx R   xxxxxxxx ROM 6B    program ROM (lower half)
-10xx xxxx xxxx xxxx R   xxxxxxxx ROM 6B    program ROM (upper half)
-1011 0--- ---- ----   W                    unknown (CUS41)
-1011 1--- ---- ----   W                    unknown (CUS41)
-1111 xxxx xxxx xxxx R   xxxxxxxx           MCU internal ROM
-
-
-Notes:
------
-- we are using an unusually high CPU interleave factor (800) to avoid hangs
-  in rthunder. The two 6809 in this game synchronize using a semaphore at
-  5606/5607 (CPU1) 1606/1607 (CPU2). CPU1 clears 5606, does some quick things,
-  and then increments 5606. While it does its quick things (which require
-  about 40 clock cycles) it expects CPU2 to clear 5607.
-  Raising the interleave factor to 1000 makes wndrmomo crash during attract
-  mode. I haven't investigated on the cause.
-
-- There are two watchdogs, one per CPU (or maybe three). Handling them
-  separately is necessary to allow entering service mode without manually
-  resetting in rthunder and genpeitd: only one of the CPUs stops writing to
-  the watchdog.
-
-- The sprite hardware buffers spriteram: the program writes the sprite list to
-  offsets 4-9 of every 16-byte block, then at the end writes to offset 0x1ff2 of
-  sprite RAM to signal the chip that the list is complete. The chip will copy
-  the list from 4-9 to 10-15 and use it from there. This has not been verified
-  on the real hardware, but it is the most logical way of doing it.
-  Emulating this behaviour and not using an external buffer is important in
-  rthunder: when you insert a coin, the whole sprite RAM is cleared, but 0x1ff2
-  is not written to. If we buffered spriteram to an external buffer, this would
-  cause dangling sprites because the buffer would not be updated.
-
-- spriteram buffering fixes sprite lag, but causes a glitch in rthunder when
-  entering a door. The *closed* door is made of tiles, but the *moving* door is
-  made of sprites. Since sprites are delayed by 1 frame, when you enter a door
-  there is one frame where neither the tile-based closed door nor the
-  sprite-based moving door is shown, so it flickers. This behavior has been
-  confirmed on a real PCB.
-
-TODO:
-----
-- The two unknown writes for the MCU are probably watchdog reset and irq acknowledge,
-  but they don't seem to work as expected. During the first few frames they are
-  written out of order and hooking them up in the usual way causes the MCU to
-  stop receiving interrupts.
-
-#endif
-