]> Shamusworld >> Repos - apple2/blob - src/apple2.cpp
e1cde1704eb8a655e75129e099072b8bb7e73d72
[apple2] / src / apple2.cpp
1 //
2 // Apple 2 SDL Portable Apple Emulator
3 //
4 // by James L. Hammons
5 // (C) 2005 Underground Software
6 //
7 // Loosely based on AppleWin by Tom Charlesworth which was based on AppleWin by
8 // Oliver Schmidt which was based on AppleWin by Michael O'Brien. :-) Parts are
9 // also derived from ApplePC. Too bad it was closed source--it could have been
10 // *the* premier Apple II emulator out there.
11 //
12 // JLH = James L. Hammons <jlhamm@acm.org>
13 //
14 // WHO  WHEN        WHAT
15 // ---  ----------  ------------------------------------------------------------
16 // JLH  11/12/2005  Initial port to SDL
17 // JLH  11/18/2005  Wired up graphic soft switches
18 // JLH  12/02/2005  Setup timer subsystem for more accurate time keeping
19 // JLH  12/12/2005  Added preliminary state saving support
20 //
21
22 // STILL TO DO:
23 //
24 // - Port to SDL [DONE]
25 // - GUI goodies
26 // - Weed out unneeded functions [DONE]
27 // - Disk I/O [DONE]
28 // - 128K IIe related stuff
29 // - State loading/saving
30 //
31
32 #include "apple2.h"
33
34 #include <SDL2/SDL.h>
35 #include <fstream>
36 #include <string>
37 #include <iomanip>
38 #include <iostream>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <time.h>
42 #include "log.h"
43 #include "video.h"
44 #include "sound.h"
45 #include "settings.h"
46 #include "v65c02.h"
47 #include "applevideo.h"
48 #include "timing.h"
49 #include "floppy.h"
50 #include "firmware.h"
51
52 #include "gui/gui.h"
53 #include "gui/window.h"
54 #include "gui/draggablewindow2.h"
55 #include "gui/textedit.h"
56
57 // Debug and misc. defines
58
59 #define THREADED_65C02
60 #define CPU_THREAD_OVERFLOW_COMPENSATION
61 #define DEBUG_LC
62 //#define CPU_CLOCK_CHECKING
63 //#define THREAD_DEBUGGING
64 #define SOFT_SWITCH_DEBUGGING
65
66 // Global variables
67
68 uint8_t ram[0x10000], rom[0x10000];                             // RAM & ROM spaces
69 uint8_t ram2[0x10000];                                                  // Auxillary RAM
70 uint8_t diskRom[0x100];                                                 // Disk ROM space
71 V65C02REGS mainCPU;                                                             // v65C02 execution context
72 uint8_t appleType = APPLE_TYPE_IIE;
73 FloppyDrive floppyDrive;
74
75 // Local variables
76
77 static uint8_t lastKeyPressed = 0;
78 static bool keyDown = false;
79 static bool openAppleDown = false;
80 static bool closedAppleDown = false;
81 static bool store80Mode = false;
82 static bool vbl = false;
83 static bool slotCXROM = false;
84 static bool slotC3ROM = false;
85 static bool ramrd = false;
86 static bool ramwrt = false;
87 static bool altzp = false;
88 static bool ioudis = true;
89 bool dhires = false;
90
91 //static FloppyDrive floppyDrive;
92
93 enum { LC_BANK_1, LC_BANK_2 };
94
95 static uint8_t visibleBank = LC_BANK_1;
96 static bool readRAM = false;
97 static bool writeRAM = false;
98
99 static bool running = true;                                             // Machine running state flag...
100 static uint32_t startTicks;
101 static bool pauseMode = false;
102
103 static GUI * gui = NULL;
104
105 // Local functions (technically, they're global...)
106
107 bool LoadImg(char * filename, uint8_t * ram, int size);
108 uint8_t RdMem(uint16_t addr);
109 void WrMem(uint16_t addr, uint8_t b);
110 static void SaveApple2State(const char * filename);
111 static bool LoadApple2State(const char * filename);
112
113 // Local timer callback functions
114
115 static void FrameCallback(void);
116 static void BlinkTimer(void);
117
118 #ifdef THREADED_65C02
119 // Test of threaded execution of 6502
120 static SDL_Thread * cpuThread = NULL;
121 //static SDL_mutex * cpuMutex = NULL;
122 static SDL_cond * cpuCond = NULL;
123 static SDL_sem * mainSem = NULL;
124 static bool cpuFinished = false;
125 static bool cpuSleep = false;
126
127
128 // NB: Apple //e Manual sez 6502 is running @ 1,022,727 Hz
129
130 // Let's try a thread...
131 /*
132 Here's how it works: Execute 1 frame's worth, then sleep.
133 Other stuff wakes it up
134 */
135 int CPUThreadFunc(void * data)
136 {
137         // Mutex must be locked for conditional to work...
138         // Also, must be created in the thread that uses it...
139         SDL_mutex * cpuMutex = SDL_CreateMutex();
140
141 // decrement mainSem...
142 //SDL_SemWait(mainSem);
143 #ifdef CPU_THREAD_OVERFLOW_COMPENSATION
144         float overflow = 0.0;
145 #endif
146
147         do
148         {
149                 if (cpuSleep)
150                         SDL_CondWait(cpuCond, cpuMutex);
151
152 // decrement mainSem...
153 #ifdef THREAD_DEBUGGING
154 WriteLog("CPU: SDL_SemWait(mainSem);\n");
155 #endif
156 SDL_SemWait(mainSem);
157
158 // There are exactly 800 slices of 21.333 cycles per frame, so it works out
159 // evenly.
160 #if 0
161                 uint32_t cycles = 17066;
162 #ifdef CPU_THREAD_OVERFLOW_COMPENSATION
163 // ODD! It's closer *without* this overflow compensation. ??? WHY ???
164                 overflow += 0.666666667;
165
166                 if (overflow > 1.0)
167                 {
168                         overflow -= 1.0;
169                         cycles++;
170                 }
171 #endif
172
173 #ifdef THREAD_DEBUGGING
174 WriteLog("CPU: Execute65C02(&mainCPU, cycles);\n");
175 #endif
176                 Execute65C02(&mainCPU, cycles); // how much? 1 frame (after 1 s, off by 40 cycles) not any more--it's off by as much as 240 now!
177
178                 // Adjust the sound routine's last cycle toggled time base
179                 // Also, since we're finished executing, .clock is now valid
180 #ifdef THREAD_DEBUGGING
181 WriteLog("CPU: AdjustLastToggleCycles(mainCPU.clock);\n");
182 #endif
183                 AdjustLastToggleCycles(mainCPU.clock);
184 #else
185 #ifdef THREAD_DEBUGGING
186 WriteLog("CPU: Execute65C02(&mainCPU, cycles);\n");
187 #endif
188                 for(int i=0; i<800; i++)
189                 {
190                         uint32_t cycles = 21;
191                         overflow += 0.333333334;
192
193                         if (overflow > 1.0)
194                         {
195                                 cycles++;
196                                 overflow -= 1.0;
197                         }
198
199                         Execute65C02(&mainCPU, cycles);
200                         WriteSampleToBuffer();
201
202                         // Dunno if this is correct (seems to be close enough)...
203                         vbl = (i < 670 ? true : false);
204                 }
205 #endif
206
207 //WriteLog("CPUThread: Supposedly end of frame...\n");
208
209 #ifdef THREAD_DEBUGGING
210 WriteLog("CPU: SDL_mutexP(cpuMutex);\n");
211 #endif
212                 SDL_mutexP(cpuMutex);
213 #if 0
214                 if (SDL_CondWait(cpuCond, cpuMutex) != 0)
215                 {
216                         printf("SDL_CondWait != 0! (Error: '%s')\n", SDL_GetError());
217                         exit(-1);
218                 }
219 #else
220 // increment mainSem...
221 #ifdef THREAD_DEBUGGING
222 WriteLog("CPU: SDL_SemPost(mainSem);\n");
223 #endif
224 SDL_SemPost(mainSem);
225 //              SDL_CondSignal(mainCond);       // In case something is waiting on us...
226
227 #ifdef THREAD_DEBUGGING
228 WriteLog("CPU: SDL_CondWait(cpuCond, cpuMutex);\n");
229 #endif
230                 SDL_CondWait(cpuCond, cpuMutex);
231
232 #endif
233 #ifdef THREAD_DEBUGGING
234 WriteLog("CPU: SDL_mutexV(cpuMutex);\n");
235 #endif
236                 SDL_mutexV(cpuMutex);
237         }
238         while (!cpuFinished);
239
240         SDL_DestroyMutex(cpuMutex);
241
242         return 0;
243 }
244 #endif
245
246
247 // Test GUI function
248
249 Element * TestWindow(void)
250 {
251         Element * win = new DraggableWindow2(10, 10, 128, 128);
252 //      ((DraggableWindow *)win)->AddElement(new TextEdit(4, 16, 92, 0, "u2prog.dsk", win));
253
254         return win;
255 }
256
257
258 Element * QuitEmulator(void)
259 {
260         gui->Stop();
261         running = false;
262
263         return NULL;
264 }
265
266
267 /*
268  Small Apple II memory map:
269
270 $C010 - Clear bit 7 of keyboard data ($C000)
271 $C030 - Toggle speaker diaphragm
272 $C051 - Display text
273 $C054 - Select page 1
274 $C056 - Select lo-res
275 $C058 - Set annuciator-0 output to 0
276 $C05A - Set annuciator-0 output to 0
277 $C05D - Set annuciator-0 output to 1
278 $C05F - Set annuciator-0 output to 1
279 $C0E0 - Disk control stepper ($C0E0-7)
280 $C0E9 - Disk control motor (on)
281 $C0EA - Disk enable (drive 1)
282 $C0EC - Disk R/W
283 $C0EE - Disk set read mode
284 */
285
286 //
287 // V65C02 read/write memory functions
288 //
289
290 uint8_t RdMem(uint16_t addr)
291 {
292         uint8_t b;
293
294 #if 0
295 if (addr >= 0xC000 && addr <= 0xC0FF)
296         WriteLog("\n*** Read at I/O address %04X\n", addr);
297 #endif
298 #if 0
299 if (addr >= 0xC080 && addr <= 0xC08F)
300         WriteLog("\n*** Read at I/O address %04X\n", addr);
301 #endif
302
303         if ((addr & 0xFFF0) == 0xC000)                  // Read $C000-$C00F
304         {
305                 return lastKeyPressed | (keyDown ? 0x80 : 0x00);
306         }
307 //      else if ((addr & 0xFFF8) == 0xC010)             // Read $C010-$C01F
308         else if (addr == 0xC010)
309         {
310 //This is bogus: keyDown is set to false, so return val NEVER is set...
311 //Fixed...
312 //Also, this is IIe/IIc only...!
313                 uint8_t retVal = lastKeyPressed | (keyDown ? 0x80 : 0x00);
314                 keyDown = false;
315                 return retVal;
316         }
317         // These are //e locations
318         else if (addr == 0xC011)
319         {
320 #ifdef SOFT_SWITCH_DEBUGGING
321 WriteLog("RDBANK2 (read)\n");
322 #endif
323                 return (visibleBank == LC_BANK_2 ? 0x80 : 0x00);
324         }
325         else if (addr == 0xC012)
326         {
327 #ifdef SOFT_SWITCH_DEBUGGING
328 WriteLog("RDLCRAM (read)\n");
329 #endif
330                 return (readRAM ? 0x80 : 0x00);
331         }
332         else if (addr == 0xC013)
333         {
334 #ifdef SOFT_SWITCH_DEBUGGING
335 WriteLog("RAMRD (read)\n");
336 #endif
337                 return (ramrd ? 0x80 : 0x00);
338         }
339         else if (addr == 0xC014)
340         {
341 #ifdef SOFT_SWITCH_DEBUGGING
342 WriteLog("RAMWRT (read)\n");
343 #endif
344                 return (ramwrt ? 0x80 : 0x00);
345         }
346         else if (addr == 0xC015)
347         {
348 #ifdef SOFT_SWITCH_DEBUGGING
349 WriteLog("SLOTCXROM (read)\n");
350 #endif
351                 return (slotCXROM ? 0x80 : 0x00);
352         }
353         else if (addr == 0xC016)
354         {
355 #ifdef SOFT_SWITCH_DEBUGGING
356 WriteLog("ALTZP (read)\n");
357 #endif
358                 return (altzp ? 0x80 : 0x00);
359         }
360         else if (addr == 0xC017)
361         {
362 #ifdef SOFT_SWITCH_DEBUGGING
363 WriteLog("SLOTC3ROM (read)\n");
364 #endif
365                 return (slotC3ROM ? 0x80 : 0x00);
366         }
367         else if (addr == 0xC018)
368         {
369 #ifdef SOFT_SWITCH_DEBUGGING
370 WriteLog("80STORE (read)\n");
371 #endif
372                 return (store80Mode ? 0x80 : 0x00);
373         }
374         else if (addr == 0xC019)
375         {
376 #ifdef SOFT_SWITCH_DEBUGGING
377 WriteLog("VBL (read)\n");
378 #endif
379 // NB: The doco suggests that this signal goes LOW when in the VBI.
380 // Which means that we need to control this by counting lines somewhere.
381                 return (vbl ? 0x80 : 0x00);
382         }
383         else if (addr == 0xC01A)
384         {
385 #ifdef SOFT_SWITCH_DEBUGGING
386 WriteLog("TEXT (read)\n");
387 #endif
388                 return (textMode ? 0x80 : 0x00);
389         }
390         else if (addr == 0xC01B)
391         {
392 #ifdef SOFT_SWITCH_DEBUGGING
393 WriteLog("MIXED (read)\n");
394 #endif
395                 return (mixedMode ? 0x80 : 0x00);
396         }
397         else if (addr == 0xC01C)
398         {
399 #ifdef SOFT_SWITCH_DEBUGGING
400 WriteLog("PAGE2 (read)\n");
401 #endif
402                 return (displayPage2 ? 0x80 : 0x00);
403         }
404         else if (addr == 0xC01D)
405         {
406 #ifdef SOFT_SWITCH_DEBUGGING
407 WriteLog("HIRES (read)\n");
408 #endif
409                 return (hiRes ? 0x80 : 0x00);
410         }
411         else if (addr == 0xC01E)
412         {
413 #ifdef SOFT_SWITCH_DEBUGGING
414 WriteLog("ALTCHARSET (read)\n");
415 #endif
416                 return (alternateCharset ? 0x80 : 0x00);
417         }
418         else if (addr == 0xC01F)
419         {
420 #ifdef SOFT_SWITCH_DEBUGGING
421 WriteLog("80COL (read)\n");
422 #endif
423                 return (col80Mode ? 0x80 : 0x00);
424         }
425         else if ((addr & 0xFFF0) == 0xC030)             // Read $C030-$C03F
426         {
427                 ToggleSpeaker();
428 //should it return something else here???
429                 return 0x00;
430         }
431         else if (addr == 0xC050)                                // Read $C050
432         {
433 #ifdef SOFT_SWITCH_DEBUGGING
434 WriteLog("TEXT off (read)\n");
435 #endif
436                 textMode = false;
437         }
438         else if (addr == 0xC051)                                // Read $C051
439         {
440 #ifdef SOFT_SWITCH_DEBUGGING
441 WriteLog("TEXT on (read)\n");
442 #endif
443                 textMode = true;
444         }
445         else if (addr == 0xC052)                                // Read $C052
446         {
447 #ifdef SOFT_SWITCH_DEBUGGING
448 WriteLog("MIXED off (read)\n");
449 #endif
450                 mixedMode = false;
451         }
452         else if (addr == 0xC053)                                // Read $C053
453         {
454 #ifdef SOFT_SWITCH_DEBUGGING
455 WriteLog("MIXED on (read)\n");
456 #endif
457                 mixedMode = true;
458         }
459         else if (addr == 0xC054)                                // Read $C054
460         {
461 #ifdef SOFT_SWITCH_DEBUGGING
462 WriteLog("PAGE2 off (read)\n");
463 #endif
464                 displayPage2 = false;
465         }
466         else if (addr == 0xC055)                                // Read $C055
467         {
468 #ifdef SOFT_SWITCH_DEBUGGING
469 WriteLog("PAGE2 on (read)\n");
470 #endif
471                 displayPage2 = true;
472         }
473         else if (addr == 0xC056)                                // Read $C056
474         {
475 #ifdef SOFT_SWITCH_DEBUGGING
476 WriteLog("HIRES off (read)\n");
477 #endif
478                 hiRes = false;
479         }
480         else if (addr == 0xC057)                                // Read $C057
481         {
482 #ifdef SOFT_SWITCH_DEBUGGING
483 WriteLog("HIRES on (read)\n");
484 #endif
485                 hiRes = true;
486         }
487         else if (addr == 0xC05E)
488         {
489 #ifdef SOFT_SWITCH_DEBUGGING
490 WriteLog("DHIRES on (read)\n");
491 #endif
492                 if (ioudis)
493                         dhires = true;
494         }
495         else if (addr == 0xC05F)
496         {
497 #ifdef SOFT_SWITCH_DEBUGGING
498 WriteLog("DHIRES off (read)\n");
499 #endif
500                 if (ioudis)
501                         dhires = false;
502         }
503         else if (addr == 0xC061)                                // Read $C061
504         {
505                 // Open Apple key (or push button 0)
506                 return (openAppleDown ? 0x80 : 0x00);
507         }
508         else if (addr == 0xC062)                                // Read $C062
509         {
510                 // Open Apple key (or push button 0)
511                 return (closedAppleDown ? 0x80 : 0x00);
512         }
513         // The way the paddles work is that a strobe is written (or read) to $C070,
514         // then software counts down the time that it takes for the paddle outputs
515         // to have bit 7 return to 0. If there are no paddles connected, bit 7
516         // stays at 1.
517         else if (addr == 0xC064)        // Paddles 0-3
518         {
519                 return 0xFF;
520         }
521         else if (addr == 0xC065)
522         {
523                 return 0xFF;
524         }
525         else if (addr == 0xC066)
526         {
527                 return 0xFF;
528         }
529         else if (addr == 0xC067)
530         {
531                 return 0xFF;
532         }
533         else if (addr == 0xC07E)
534         {
535 #ifdef SOFT_SWITCH_DEBUGGING
536 WriteLog("IOUDIS (read)\n");
537 #endif
538                 return (ioudis ? 0x80 : 0x00);
539         }
540         else if (addr == 0xC07F)
541         {
542 #ifdef SOFT_SWITCH_DEBUGGING
543 WriteLog("DHIRES (read)\n");
544 #endif
545                 return (dhires ? 0x80 : 0x00);
546         }
547
548 //Note that this is a kludge: The $D000-$DFFF 4K space is shared (since $C000-$CFFF is
549 //memory mapped) between TWO banks, and that that $E000-$FFFF RAM space is a single bank.
550 //[SHOULD BE FIXED NOW]
551 //OK! This switch selects bank 2 of the 4K bank at $D000-$DFFF. One access makes it
552 //visible, two makes it R/W.
553
554 /*
555 301  LDA $E000
556 304  PHA
557 305  LDA $C081
558 308  PLA
559 309  PHA
560 30A  CMP $E000
561 30D  BNE $332
562 30F  LDA $C083
563 312  LDA $C083
564 315  LDA #$A5
565 317  STA $D000
566 31A  CMP $D000
567 31D  BNE $332
568 31F  LSR A
569 320  STA $D000
570 323  CMP $D000
571 326  BNE $332
572 328  LDA $C081
573 32B  LDA $C081
574 32E  LDA #$01
575 330  BNE $334
576 332  LDA #$00
577 334  STA $300
578 337  PLA
579 338  CMP $E000
580 33B  BEQ $340
581 33D  LDA $C080
582 340  RTS
583
584 A = PEEK($C082)
585 */
586
587         else if ((addr & 0xFFFB) == 0xC080)
588         {
589 #ifdef DEBUG_LC
590 WriteLog("LC(R): $C080 49280 OECG R Read RAM bank 2; no write\n");
591 #endif
592 //$C080 49280              OECG  R   Read RAM bank 2; no write
593                 visibleBank = LC_BANK_2;
594                 readRAM = true;
595                 writeRAM = false;
596         }
597         else if ((addr & 0xFFFB) == 0xC081)
598         {
599 #ifdef DEBUG_LC
600 WriteLog("LC(R): $C081 49281 OECG RR Read ROM; write RAM bank 2\n");
601 #endif
602 //$C081 49281 ROMIN        OECG  RR  Read ROM; write RAM bank 2
603                 visibleBank = LC_BANK_2;
604                 readRAM = false;
605                 writeRAM = true;
606         }
607         else if ((addr & 0xFFFB) == 0xC082)
608         {
609 #ifdef DEBUG_LC
610 WriteLog("LC(R): $C082 49282 OECG R Read ROM; no write\n");
611 #endif
612 //$C082 49282              OECG  R   Read ROM; no write
613                 visibleBank = LC_BANK_2;
614                 readRAM = false;
615                 writeRAM = false;
616         }
617         else if ((addr & 0xFFFB) == 0xC083)
618         {
619 #ifdef DEBUG_LC
620 WriteLog("LC(R): $C083 49283 OECG RR Read/Write RAM bank 2\n");
621 #endif
622 //$C083 49283 LCBANK2      OECG  RR  Read/write RAM bank 2
623                 visibleBank = LC_BANK_2;
624                 readRAM = true;
625                 writeRAM = true;
626         }
627         else if ((addr & 0xFFFB) == 0xC088)
628         {
629 #ifdef DEBUG_LC
630 WriteLog("LC(R): $%04X 49288 OECG R Read RAM bank 1; no write\n", addr);
631 #endif
632 //$C088 49288              OECG  R   Read RAM bank 1; no write
633                 visibleBank = LC_BANK_1;
634                 readRAM = true;
635                 writeRAM = false;
636 //Hm. Some stuff seems to want this.
637 //nope, was looking at $C0E8... return 0xFF;
638         }
639         else if ((addr & 0xFFFB) == 0xC089)
640         {
641 #ifdef DEBUG_LC
642 WriteLog("LC(R): $C089 49289 OECG RR Read ROM; write RAM bank 1\n");
643 #endif
644 //$C089 49289              OECG  RR  Read ROM; write RAM bank 1
645                 visibleBank = LC_BANK_1;
646                 readRAM = false;
647                 writeRAM = true;
648         }
649         else if ((addr & 0xFFFB) == 0xC08A)
650         {
651 #ifdef DEBUG_LC
652 WriteLog("LC(R): $C08A 49290 OECG R Read ROM; no write\n");
653 #endif
654 //$C08A 49290              OECG  R   Read ROM; no write
655                 visibleBank = LC_BANK_1;
656                 readRAM = false;
657                 writeRAM = false;
658         }
659         else if ((addr & 0xFFFB) == 0xC08B)
660         {
661 #ifdef DEBUG_LC
662 WriteLog("LC(R): $C08B 49291 OECG RR Read/Write RAM bank 1\n");
663 #endif
664 //$C08B 49291              OECG  RR  Read/write RAM bank 1
665                 visibleBank = LC_BANK_1;
666                 readRAM = true;
667                 writeRAM = true;
668         }
669         else if ((addr & 0xFFF8) == 0xC0E0)
670         {
671                 floppyDrive.ControlStepper(addr & 0x07);
672         }
673         else if ((addr & 0xFFFE) == 0xC0E8)
674         {
675                 floppyDrive.ControlMotor(addr & 0x01);
676         }
677         else if ((addr & 0xFFFE) == 0xC0EA)
678         {
679                 floppyDrive.DriveEnable(addr & 0x01);
680         }
681         else if (addr == 0xC0EC)
682         {
683                 return floppyDrive.ReadWrite();
684         }
685         else if (addr == 0xC0ED)
686         {
687                 return floppyDrive.GetLatchValue();
688         }
689         else if (addr == 0xC0EE)
690         {
691                 floppyDrive.SetReadMode();
692         }
693         else if (addr == 0xC0EF)
694         {
695                 floppyDrive.SetWriteMode();
696         }
697
698 //#define LC_DEBUGGING
699 #ifdef LC_DEBUGGING
700 bool showpath = false;
701 if (addr >= 0xD000 && addr <= 0xD00F)
702         showpath = true;
703 #endif
704 //This sux...
705         if (addr >= 0xC100 && addr <= 0xC7FF)   // The $C000-$CFFF block is *never* RAM
706         {
707 // Looks like the ][e ref manual got this one wrong: slotCXROM set should mean
708 // use internal ROM, NOT slot ROM. :-/
709 // (fixed now, by setting the switch correctly in the write mem section :-P)
710                 if (!slotCXROM)
711 //              if (slotCXROM)
712                         b = rom[addr];
713                 else
714                 {
715                         if (addr >= 0xC100 && addr <= 0xC1FF)
716                                 b = parallelROM[addr & 0xFF];
717                         else if (addr >= 0xC600 && addr <= 0xC6FF)
718                                 b = diskROM[addr & 0xFF];
719                         else if (addr >= 0xC300 && addr <= 0xC3FF && !slotC3ROM)
720                                 b = rom[addr];
721                         else
722                                 b = 0xFF;
723 //                              b = rom[addr];
724                 }
725 #ifdef LC_DEBUGGING
726 if (showpath)
727         WriteLog("b is from $C100-$CFFF block...\n");
728 #endif
729         }
730         else if (addr >= 0xC800 && addr <= 0xCFFF)      // 2K peripheral or OS ROM
731         {
732                 b = rom[addr];
733         }
734         else if (addr >= 0xD000)
735         {
736                 if (readRAM)
737                 {
738                         if (addr <= 0xDFFF && visibleBank == LC_BANK_1)
739 #ifdef LC_DEBUGGING
740                         {
741 #endif
742 //                              b = ram[addr - 0x1000];
743                                 b = (altzp ? ram2[addr - 0x1000] : ram[addr - 0x1000]);
744 #ifdef LC_DEBUGGING
745 if (showpath)
746         WriteLog("b is from LC bank #1 (ram[addr - 0x1000])...\n");
747                         }
748 #endif
749                         else
750 #ifdef LC_DEBUGGING
751                         {
752 #endif
753 //                              b = ram[addr];
754                                 b = (altzp ? ram2[addr] : ram[addr]);
755 #ifdef LC_DEBUGGING
756 if (showpath)
757         WriteLog("b is from LC bank #2 (ram[addr])...\n");
758                         }
759 #endif
760                 }
761                 else
762 #ifdef LC_DEBUGGING
763                 {
764 #endif
765                         b = rom[addr];
766 #ifdef LC_DEBUGGING
767 if (showpath)
768         WriteLog("b is from LC ROM (rom[addr])...\n");
769                 }
770 #endif
771         }
772         else
773         {
774 // 80STORE only works for WRITING, not READING!
775 #if 0
776                 // Check for 80STORE mode (STORE80 takes precedence over RAMRD/WRT)...
777                 if ((((addr >= 0x0400) && (addr <= 0x07FF)) || ((addr >= 0x2000) && (addr <= 0x3FFF))) && store80Mode)
778                 {
779                         if (displayPage2)
780                                 b = ram2[addr];
781                         else
782                                 b = ram[addr];
783
784                         return b;
785                 }
786 #endif
787
788                 // Finally, check for auxillary/altzp write switches
789                 if (addr < 0x0200)
790                         b = (altzp ? ram2[addr] : ram[addr]);
791                 else
792                         b = (ramrd ? ram2[addr] : ram[addr]);
793 #ifdef LC_DEBUGGING
794 if (showpath)
795         WriteLog("b is from ram[addr]...\n");
796 #endif
797         }
798
799 #ifdef LC_DEBUGGING
800 if (addr >= 0xD000 && addr <= 0xD00F)
801 {
802         WriteLog("*** Read from $%04X: $%02X (readRAM=%s, PC=%04X, ram$D000=%02X)\n", addr, b, (readRAM ? "T" : "F"), mainCPU.pc, ram[0xC000]);
803 }
804 #endif
805
806         return b;
807 }
808
809 /*
810 A-9 (Mockingboard)
811 APPENDIX F Assembly Language Program Listings
812
813         1       *PRIMARY ROUTINES
814         2       *FOR SLOT 4
815         3       *
816         4                       ORG     $9000
817         5       *                               ;ADDRESSES FOR FIRST 6522
818         6       ORB             EQU     $C400           ;PORT B
819         7       ORA             EQU     $C401           ;PORT A
820         8       DDRB            EQU     $C402           ;DATA DIRECTION REGISTER (A)
821         9       DDRA            EQU     $C403           ;DATA DIRECTION REGISTER (B)
822         10      *                                       ;ADDRESSES FOR SECOND 6522
823         11      ORB2            EQU     $C480           ;PORT B
824         12      ORA2            EQU     $C481           ;PORT A
825         13      DDRB2   EQU     $C482           ;DATA DIRECTION REGISTER (B)
826         14      DDRA2   EQU     $C483           ;DATA DIRECTION REGISTER (A)
827 */
828 void WrMem(uint16_t addr, uint8_t b)
829 {
830 //temp...
831 //extern V6809REGS regs;
832 //if (addr >= 0xC800 && addr <= 0xCBFE)
833 //if (addr == 0xC80F || addr == 0xC80D)
834 //      WriteLog("WrMem: Writing address %04X with %02X [PC=%04X, $CB00=%02X]\n", addr, b, regs.pc, gram[0xCB00]);//*/
835
836 #if 0
837 if (addr >= 0xC000 && addr <= 0xC0FF)
838         WriteLog("\n*** Write at I/O address %04X\n", addr);
839 #endif
840 /*
841 Check the BIKO version on Asimov to see if it's been cracked or not...
842
843 7F3D: 29 07          AND   #$07       [PC=7F3F, SP=01EA, CC=---B-I--, A=01, X=4B, Y=00]
844 7F3F: C9 06          CMP   #$06       [PC=7F41, SP=01EA, CC=N--B-I--, A=01, X=4B, Y=00]
845 7F41: 90 03          BCC   $7F46      [PC=7F46, SP=01EA, CC=N--B-I--, A=01, X=4B, Y=00]
846 [7F43: 4C 83 7E      JMP   $7E83] <- Skipped over... (Prints "THANK YOU VERY MUCH!")
847 7F46: AA             TAX              [PC=7F47, SP=01EA, CC=---B-I--, A=01, X=01, Y=00]
848
849 ; INX here *ensures* 1 - 6!!! BUG!!!
850 ; Or is it? Could this be part of a braindead copy protection scheme? It's
851 ; awfully close to NOP ($EA)...
852 ; Nothing else touches it once it's been written... Hmm...
853
854 7F47: E8             INX              [PC=7F48, SP=01EA, CC=---B-I--, A=01, X=02, Y=00]
855 7F48: F8             SED              [PC=7F49, SP=01EA, CC=---BDI--, A=01, X=02, Y=00]
856 7F49: 18             CLC              [PC=7F4A, SP=01EA, CC=---BDI--, A=01, X=02, Y=00]
857 7F4A: BD 15 4E       LDA   $4E15,X    [PC=7F4D, SP=01EA, CC=---BDI--, A=15, X=02, Y=00]
858
859 ; 4E13: 03 00
860 ; 4E15: 25 25 15 15 10 20
861 ; 4E1B: 03 41 99 99 01 00 12
862 ; 4E22: 99 70
863
864 7F4D: 65 FC          ADC   $FC        [PC=7F4F, SP=01EA, CC=---BDI--, A=16, X=02, Y=00]
865 7F4F: 65 FC          ADC   $FC        [PC=7F51, SP=01EA, CC=---BDI--, A=17, X=02, Y=00]
866 7F51: 65 FC          ADC   $FC        [PC=7F53, SP=01EA, CC=---BDI--, A=18, X=02, Y=00]
867 7F53: 65 FC          ADC   $FC        [PC=7F55, SP=01EA, CC=---BDI--, A=19, X=02, Y=00]
868
869 ; NO checking is done on the raised stat! Aarrrgggghhhhh!
870
871 7F55: 9D 15 4E       STA   $4E15,X    [PC=7F58, SP=01EA, CC=---BDI--, A=19, X=02, Y=00]
872 7F58: D8             CLD              [PC=7F59, SP=01EA, CC=---B-I--, A=19, X=02, Y=00]
873
874 ; Print "ALAKAZAM!" and so on...
875
876 7F59: 20 2C 40       JSR   $402C      [PC=402C, SP=01E8, CC=---B-I--, A=19, X=02, Y=00]
877 */
878 #if 0
879 if (addr == 0x7F47)
880         WriteLog("\n*** Byte %02X written at address %04X\n", b, addr);
881 #endif
882 /*
883 I think this is IIc/IIe only...
884
885 CLR80STORE=$C000 ;80STORE Off- disable 80-column memory mapping (Write)
886 SET80STORE=$C001 ;80STORE On- enable 80-column memory mapping (WR-only)
887
888 CLRAUXRD = $C002 ;read from main 48K (WR-only)
889 SETAUXRD = $C003 ;read from aux/alt 48K (WR-only)
890
891 CLRAUXWR = $C004 ;write to main 48K (WR-only)
892 SETAUXWR = $C005 ;write to aux/alt 48K (WR-only)
893
894 CLRCXROM = $C006 ;use ROM on cards (WR-only)
895 SETCXROM = $C007 ;use internal ROM (WR-only)
896
897 CLRAUXZP = $C008 ;use main zero page, stack, & LC (WR-only)
898 SETAUXZP = $C009 ;use alt zero page, stack, & LC (WR-only)
899
900 CLRC3ROM = $C00A ;use internal Slot 3 ROM (WR-only)
901 SETC3ROM = $C00B ;use external Slot 3 ROM (WR-only)
902
903 CLR80VID = $C00C ;disable 80-column display mode (WR-only)
904 SET80VID = $C00D ;enable 80-column display mode (WR-only)
905
906 CLRALTCH = $C00E ;use main char set- norm LC, Flash UC (WR-only)
907 SETALTCH = $C00F ;use alt char set- norm inverse, LC; no Flash (WR-only)
908 */
909         if (addr == 0xC000)
910         {
911 #ifdef SOFT_SWITCH_DEBUGGING
912 WriteLog("80STORE off (write)\n");
913 #endif
914                 store80Mode = false;
915         }
916         else if (addr == 0xC001)
917         {
918 #ifdef SOFT_SWITCH_DEBUGGING
919 WriteLog("80STORE on (write)\n");
920 #endif
921                 store80Mode = true;
922         }
923         else if (addr == 0xC002)
924         {
925 #ifdef SOFT_SWITCH_DEBUGGING
926 WriteLog("RAMRD off (write)\n");
927 #endif
928                 ramrd = false;
929         }
930         else if (addr == 0xC003)
931         {
932 #ifdef SOFT_SWITCH_DEBUGGING
933 WriteLog("RAMRD on (write)\n");
934 #endif
935                 ramrd = true;
936         }
937         else if (addr == 0xC004)
938         {
939 #ifdef SOFT_SWITCH_DEBUGGING
940 WriteLog("RAMWRT off (write)\n");
941 #endif
942                 ramwrt = false;
943         }
944         else if (addr == 0xC005)
945         {
946 #ifdef SOFT_SWITCH_DEBUGGING
947 WriteLog("RAMWRT on (write)\n");
948 #endif
949                 ramwrt = true;
950         }
951         else if (addr == 0xC006)
952         {
953                 // This is the only soft switch that breaks the usual convention.
954 #ifdef SOFT_SWITCH_DEBUGGING
955 WriteLog("SLOTCXROM on (write)\n");
956 #endif
957                 slotCXROM = true;
958         }
959         else if (addr == 0xC007)
960         {
961 #ifdef SOFT_SWITCH_DEBUGGING
962 WriteLog("SLOTCXROM off (write)\n");
963 #endif
964                 slotCXROM = false;
965         }
966         else if (addr == 0xC008)
967         {
968 #ifdef SOFT_SWITCH_DEBUGGING
969 WriteLog("ALTZP off (write)\n");
970 #endif
971                 altzp = false;
972         }
973         else if (addr == 0xC009)
974         {
975 #ifdef SOFT_SWITCH_DEBUGGING
976 WriteLog("ALTZP on (write)\n");
977 #endif
978                 altzp = true;
979         }
980         else if (addr == 0xC00A)
981         {
982 #ifdef SOFT_SWITCH_DEBUGGING
983 WriteLog("SLOTC3ROM off (write)\n");
984 #endif
985                 slotC3ROM = false;
986         }
987         else if (addr == 0xC00B)
988         {
989 #ifdef SOFT_SWITCH_DEBUGGING
990 WriteLog("SLOTC3ROM on (write)\n");
991 #endif
992                 slotC3ROM = true;
993         }
994         else if (addr == 0xC00C)
995         {
996 #ifdef SOFT_SWITCH_DEBUGGING
997 WriteLog("80COL off (write)\n");
998 #endif
999                 col80Mode = false;
1000         }
1001         else if (addr == 0xC00D)
1002         {
1003 #ifdef SOFT_SWITCH_DEBUGGING
1004 WriteLog("80COL on (write)\n");
1005 #endif
1006                 col80Mode = true;
1007         }
1008         else if (addr == 0xC00E)
1009         {
1010 #ifdef SOFT_SWITCH_DEBUGGING
1011 WriteLog("ALTCHARSET off (write)\n");
1012 #endif
1013                 alternateCharset = false;
1014         }
1015         else if (addr == 0xC00F)
1016         {
1017 #ifdef SOFT_SWITCH_DEBUGGING
1018 WriteLog("ALTCHARSET on (write)\n");
1019 #endif
1020                 alternateCharset = true;
1021         }
1022         else if ((addr & 0xFFF0) == 0xC010)             // Keyboard strobe
1023         {
1024 //Actually, according to the A2 ref, this should do nothing since a write
1025 //is immediately preceded by a read leaving it in the same state it was...
1026 //But leaving this out seems to fuck up the key handling of some games...
1027                 keyDown = false;
1028         }
1029         else if ((addr & 0xFFF0) == 0xC030)             // Read $C030-$C03F
1030         {
1031 //Likewise, the speaker is supposed to do nothing if you write to it, and
1032 //for the same reason. But without this, you get no sound in David's
1033 //Midnight Magic...
1034                 ToggleSpeaker();
1035         }
1036         else if (addr == 0xC050)
1037         {
1038 #ifdef SOFT_SWITCH_DEBUGGING
1039 WriteLog("TEXT off (write)\n");
1040 #endif
1041                 textMode = false;
1042         }
1043         else if (addr == 0xC051)
1044         {
1045 #ifdef SOFT_SWITCH_DEBUGGING
1046 WriteLog("TEXT on (write)\n");
1047 #endif
1048                 textMode = true;
1049         }
1050         else if (addr == 0xC052)
1051         {
1052 #ifdef SOFT_SWITCH_DEBUGGING
1053 WriteLog("MIXED off (write)\n");
1054 #endif
1055                 mixedMode = false;
1056         }
1057         else if (addr == 0xC053)
1058         {
1059 #ifdef SOFT_SWITCH_DEBUGGING
1060 WriteLog("MIXED on (write)\n");
1061 #endif
1062                 mixedMode = true;
1063         }
1064         else if (addr == 0xC054)
1065         {
1066 #ifdef SOFT_SWITCH_DEBUGGING
1067 WriteLog("PAGE2 off (write)\n");
1068 #endif
1069                 displayPage2 = false;
1070         }
1071         else if (addr == 0xC055)
1072         {
1073 #ifdef SOFT_SWITCH_DEBUGGING
1074 WriteLog("PAGE2 on (write)\n");
1075 #endif
1076                 displayPage2 = true;
1077         }
1078         else if (addr == 0xC056)
1079         {
1080 #ifdef SOFT_SWITCH_DEBUGGING
1081 WriteLog("HIRES off (write)\n");
1082 #endif
1083                 hiRes = false;
1084         }
1085         else if (addr == 0xC057)
1086         {
1087 #ifdef SOFT_SWITCH_DEBUGGING
1088 WriteLog("HIRES on (write)\n");
1089 #endif
1090                 hiRes = true;
1091         }
1092         else if (addr == 0xC05E)
1093         {
1094 #ifdef SOFT_SWITCH_DEBUGGING
1095 WriteLog("DHIRES on (write)\n");
1096 #endif
1097                 if (ioudis)
1098                         dhires = true;
1099
1100 //static int goDumpDis = 0;
1101 //goDumpDis++;
1102 //if (goDumpDis == 2)
1103 //      dumpDis = true;
1104         }
1105         else if (addr == 0xC05F)
1106         {
1107 #ifdef SOFT_SWITCH_DEBUGGING
1108 WriteLog("DHIRES off (write)\n");
1109 #endif
1110                 if (ioudis)
1111                         dhires = false;
1112         }
1113         else if (addr == 0xC07E)
1114         {
1115 #ifdef SOFT_SWITCH_DEBUGGING
1116 WriteLog("IOUDIS on (write)\n");
1117 #endif
1118                 ioudis = true;
1119         }
1120         else if (addr == 0xC07F)
1121         {
1122 #ifdef SOFT_SWITCH_DEBUGGING
1123 WriteLog("IOUDIS off (write)\n");
1124 #endif
1125                 ioudis = false;
1126         }
1127         else if ((addr & 0xFFFB) == 0xC080)
1128         {
1129 #ifdef DEBUG_LC
1130 WriteLog("LC(R): $C080 49280 OECG R Read RAM bank 2; no write\n");
1131 #endif
1132 //$C080 49280              OECG  R   Read RAM bank 2; no write
1133                 visibleBank = LC_BANK_2;
1134                 readRAM = true;
1135                 writeRAM = false;
1136         }
1137         else if ((addr & 0xFFFB) == 0xC081)
1138         {
1139 #ifdef DEBUG_LC
1140 WriteLog("LC(R): $C081 49281 OECG RR Read ROM; write RAM bank 2\n");
1141 #endif
1142 //$C081 49281 ROMIN        OECG  RR  Read ROM; write RAM bank 2
1143                 visibleBank = LC_BANK_2;
1144                 readRAM = false;
1145                 writeRAM = true;
1146         }
1147         else if ((addr & 0xFFFB) == 0xC082)
1148         {
1149 #ifdef DEBUG_LC
1150 WriteLog("LC(R): $C082 49282 OECG R Read ROM; no write\n");
1151 #endif
1152 //$C082 49282              OECG  R   Read ROM; no write
1153                 visibleBank = LC_BANK_2;
1154                 readRAM = false;
1155                 writeRAM = false;
1156         }
1157         else if ((addr & 0xFFFB) == 0xC083)
1158         {
1159 #ifdef DEBUG_LC
1160 WriteLog("LC(R): $C083 49283 OECG RR Read/Write RAM bank 2\n");
1161 #endif
1162 //$C083 49283 LCBANK2      OECG  RR  Read/write RAM bank 2
1163                 visibleBank = LC_BANK_2;
1164                 readRAM = true;
1165                 writeRAM = true;
1166         }
1167         else if ((addr & 0xFFFB) == 0xC088)
1168         {
1169 #ifdef DEBUG_LC
1170 WriteLog("LC(R): $C088 49288 OECG R Read RAM bank 1; no write\n");
1171 #endif
1172 //$C088 49288              OECG  R   Read RAM bank 1; no write
1173                 visibleBank = LC_BANK_1;
1174                 readRAM = true;
1175                 writeRAM = false;
1176         }
1177         else if ((addr & 0xFFFB) == 0xC089)
1178         {
1179 #ifdef DEBUG_LC
1180 WriteLog("LC(R): $C089 49289 OECG RR Read ROM; write RAM bank 1\n");
1181 #endif
1182 //$C089 49289              OECG  RR  Read ROM; write RAM bank 1
1183                 visibleBank = LC_BANK_1;
1184                 readRAM = false;
1185                 writeRAM = true;
1186         }
1187         else if ((addr & 0xFFFB) == 0xC08A)
1188         {
1189 #ifdef DEBUG_LC
1190 WriteLog("LC(R): $C08A 49290 OECG R Read ROM; no write\n");
1191 #endif
1192 //$C08A 49290              OECG  R   Read ROM; no write
1193                 visibleBank = LC_BANK_1;
1194                 readRAM = false;
1195                 writeRAM = false;
1196         }
1197         else if ((addr & 0xFFFB) == 0xC08B)
1198         {
1199 #ifdef DEBUG_LC
1200 WriteLog("LC(R): $C08B 49291 OECG RR Read/Write RAM bank 1\n");
1201 #endif
1202 //$C08B 49291              OECG  RR  Read/write RAM bank 1
1203                 visibleBank = LC_BANK_1;
1204                 readRAM = true;
1205                 writeRAM = true;
1206         }
1207 //This is determined by which slot it is in--this assumes slot 6. !!! FIX !!!
1208         else if ((addr & 0xFFF8) == 0xC0E0)
1209         {
1210                 floppyDrive.ControlStepper(addr & 0x07);
1211         }
1212         else if ((addr & 0xFFFE) == 0xC0E8)
1213         {
1214                 floppyDrive.ControlMotor(addr & 0x01);
1215         }
1216         else if ((addr & 0xFFFE) == 0xC0EA)
1217         {
1218                 floppyDrive.DriveEnable(addr & 0x01);
1219         }
1220         else if (addr == 0xC0EC)
1221         {
1222 //change this to Write()? (and the other to Read()?) Dunno. Seems to work OK, but still...
1223 //or DoIO
1224                 floppyDrive.ReadWrite();
1225         }
1226         else if (addr == 0xC0ED)
1227         {
1228                 floppyDrive.SetLatchValue(b);
1229         }
1230         else if (addr == 0xC0EE)
1231         {
1232                 floppyDrive.SetReadMode();
1233         }
1234         else if (addr == 0xC0EF)
1235         {
1236                 floppyDrive.SetWriteMode();
1237         }
1238 //Still need to add missing I/O switches here...
1239
1240 //DEEE: BD 10 BF       LDA   $BF10,X    [PC=DEF1, SP=01F4, CC=--.B-IZ-, A=00, X=0C, Y=07]
1241 #if 0
1242 if (addr >= 0xD000 && addr <= 0xD00F)
1243 {
1244         WriteLog("*** Write to $%04X: $%02X (writeRAM=%s, PC=%04X, ram$D000=%02X)\n", addr, b, (writeRAM ? "T" : "F"), mainCPU.pc, ram[0xC000]);
1245 }
1246 #endif
1247         if (addr >= 0xC000 && addr <= 0xCFFF)
1248                 return; // Protect LC bank #1 from being written to!
1249
1250         if (addr >= 0xD000)
1251         {
1252                 if (writeRAM)
1253                 {
1254 #if 0
1255                         if (addr <= 0xDFFF && visibleBank == LC_BANK_1)
1256                                 ram[addr - 0x1000] = b;
1257                         else
1258                                 ram[addr] = b;
1259 #else
1260                         if (addr <= 0xDFFF && visibleBank == LC_BANK_1)
1261                         {
1262                                 if (altzp)
1263                                         ram2[addr - 0x1000] = b;
1264                                 else
1265                                         ram[addr - 0x1000] = b;
1266                         }
1267                         else
1268                         {
1269                                 if (altzp)
1270                                         ram2[addr] = b;
1271                                 else
1272                                         ram[addr] = b;
1273                         }
1274 #endif
1275                 }
1276
1277                 return;
1278         }
1279
1280         // Check for 80STORE mode (STORE80 takes precedence over RAMRD/WRT)...
1281         if ((((addr >= 0x0400) && (addr <= 0x07FF)) || ((addr >= 0x2000) && (addr <= 0x3FFF))) && store80Mode)
1282         {
1283                 if (displayPage2)
1284                         ram2[addr] = b;
1285                 else
1286                         ram[addr] = b;
1287
1288                 return;
1289         }
1290
1291         // Finally, check for auxillary/altzp write switches
1292 #if 0
1293         if (ramwrt)
1294                 ram2[addr] = b;
1295         else
1296         {
1297                 if (altzp)
1298                         ram2[addr] = b;
1299                 else
1300                         ram[addr] = b;
1301         }
1302 #else
1303         if (addr < 0x0200)
1304 //      if (addr < 0x0200 || addr >= 0xD000)
1305         {
1306 #if 0
1307 if (addr == 0x38)
1308         WriteLog("Write $38: $%02X\n", b);
1309 else if (addr == 0x39)
1310         WriteLog("Write $39: $%02X\n", b);
1311 #endif
1312                 if (altzp)
1313                         ram2[addr] = b;
1314                 else
1315                         ram[addr] = b;
1316         }
1317         else
1318         {
1319                 if (ramwrt)
1320                         ram2[addr] = b;
1321                 else
1322                         ram[addr] = b;
1323         }
1324 #endif
1325 }
1326
1327
1328 //
1329 // Load a file into RAM/ROM image space
1330 //
1331 bool LoadImg(char * filename, uint8_t * ram, int size)
1332 {
1333         FILE * fp = fopen(filename, "rb");
1334
1335         if (fp == NULL)
1336                 return false;
1337
1338         fread(ram, 1, size, fp);
1339         fclose(fp);
1340
1341         return true;
1342 }
1343
1344
1345 static void SaveApple2State(const char * filename)
1346 {
1347 }
1348
1349
1350 static bool LoadApple2State(const char * filename)
1351 {
1352         return false;
1353 }
1354
1355
1356 #ifdef CPU_CLOCK_CHECKING
1357 uint8_t counter = 0;
1358 uint32_t totalCPU = 0;
1359 uint64_t lastClock = 0;
1360 #endif
1361 //
1362 // Main loop
1363 //
1364 int main(int /*argc*/, char * /*argv*/[])
1365 {
1366         InitLog("./apple2.log");
1367         LoadSettings();
1368         srand(time(NULL));                                                                      // Initialize RNG
1369
1370         // Zero out memory
1371         memset(ram, 0, 0x10000);
1372         memset(rom, 0, 0x10000);
1373         memset(ram2, 0, 0x10000);
1374
1375         // Set up V65C02 execution context
1376         memset(&mainCPU, 0, sizeof(V65C02REGS));
1377         mainCPU.RdMem = RdMem;
1378         mainCPU.WrMem = WrMem;
1379         mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
1380
1381 //      alternateCharset = true;
1382 //      if (!LoadImg(settings.BIOSPath, rom + 0xD000, 0x3000))
1383         if (!LoadImg(settings.BIOSPath, rom + 0xC000, 0x4000))
1384         {
1385                 WriteLog("Could not open file '%s'!\n", settings.BIOSPath);
1386                 return -1;
1387         }
1388
1389 //This is now included...
1390 /*      if (!LoadImg(settings.diskPath, diskRom, 0x100))
1391         {
1392                 WriteLog("Could not open file '%s'!\nDisk II will be unavailable!\n", settings.diskPath);
1393 //              return -1;
1394         }//*/
1395
1396 //Load up disk image from config file (for now)...
1397         floppyDrive.LoadImage(settings.diskImagePath1, 0);
1398         floppyDrive.LoadImage(settings.diskImagePath2, 1);
1399 //      floppyDrive.LoadImage("./disks/temp.nib", 1);   // Load temp .nib file into second drive...
1400
1401 //Kill the DOS ROM in slot 6 for now...
1402 //not
1403 //      memcpy(rom + 0xC600, diskROM, 0x100);
1404 //      memcpy(rom + 0xC700, diskROM, 0x100);   // Slot 7???
1405
1406         WriteLog("About to initialize video...\n");
1407
1408         if (!InitVideo())
1409         {
1410                 std::cout << "Aborting!" << std::endl;
1411                 return -1;
1412         }
1413
1414         // Have to do this *after* video init but *before* sound init...!
1415 //Shouldn't be necessary since we're not doing emulation in the ISR...
1416         if (settings.autoStateSaving)
1417         {
1418                 // Load last state from file...
1419                 if (!LoadApple2State(settings.autoStatePath))
1420                         WriteLog("Unable to use Apple2 state file \"%s\"!\n", settings.autoStatePath);
1421         }
1422
1423
1424 #if 0
1425 // State loading!
1426 if (!LoadImg("./BT1_6502_RAM_SPACE.bin", ram, 0x10000))
1427 {
1428         cout << "Couldn't load state file!" << endl;
1429         cout << "Aborting!!" << endl;
1430         return -1;
1431 }
1432
1433 //A  P  Y  X  S     PC
1434 //-- -- -- -- ----- -----
1435 //00 75 3B 53 FD 01 41 44
1436
1437 mainCPU.cpuFlags = 0;
1438 mainCPU.a = 0x00;
1439 mainCPU.x = 0x53;
1440 mainCPU.y = 0x3B;
1441 mainCPU.cc = 0x75;
1442 mainCPU.sp = 0xFD;
1443 mainCPU.pc = 0x4441;
1444
1445 textMode = false;
1446 mixedMode = false;
1447 displayPage2 = false;
1448 hiRes = true;
1449
1450 //kludge...
1451 readHiRam = true;
1452 //dumpDis=true;
1453 //kludge II...
1454 memcpy(ram + 0xD000, ram + 0xC000, 0x1000);
1455 #endif
1456
1457         WriteLog("About to initialize audio...\n");
1458         SoundInit();
1459 //nope  SDL_EnableUNICODE(1);                                           // Needed to do key translation shit
1460
1461 //      gui = new GUI(surface);                                         // Set up the GUI system object...
1462 //      gui = new GUI(mainSurface);                                     // Set up the GUI system object...
1463 // SDL 2... this will likely cause Apple 2 to crash
1464 //      gui = new GUI(NULL);                                    // Set up the GUI system object...
1465 #if 0
1466         gui->AddMenuTitle("Apple2");
1467         gui->AddMenuItem("Test!", TestWindow/*, hotkey*/);
1468         gui->AddMenuItem("");
1469         gui->AddMenuItem("Quit", QuitEmulator, SDLK_q);
1470         gui->CommitItemsToMenu();
1471 #endif
1472
1473         SetupBlurTable();                                                       // Set up the color TV emulation blur table
1474         running = true;                                                         // Set running status...
1475
1476         InitializeEventList();                                          // Clear the event list before we use it...
1477         SetCallbackTime(FrameCallback, 16666.66666667); // Set frame to fire at 1/60 s interval
1478         SetCallbackTime(BlinkTimer, 250000);            // Set up blinking at 1/4 s intervals
1479         startTicks = SDL_GetTicks();
1480
1481 #ifdef THREADED_65C02
1482         cpuCond = SDL_CreateCond();
1483         mainSem = SDL_CreateSemaphore(1);
1484         cpuThread = SDL_CreateThread(CPUThreadFunc, NULL, NULL);
1485 //Hmm... CPU does POST (+1), wait, then WAIT (-1)
1486 //      SDL_sem * mainMutex = SDL_CreateMutex();
1487 #endif
1488
1489         WriteLog("Entering main loop...\n");
1490         while (running)
1491         {
1492                 double timeToNextEvent = GetTimeToNextEvent();
1493 #ifndef THREADED_65C02
1494                 Execute65C02(&mainCPU, USEC_TO_M6502_CYCLES(timeToNextEvent));
1495 #endif
1496 //We MUST remove a frame's worth of time in order for the CPU to function... !!! FIX !!!
1497 //(Fix so that this is not a requirement!)
1498 //Fixed, but mainCPU.clock is destroyed in the bargain. Oh well.
1499 //              mainCPU.clock -= USEC_TO_M6502_CYCLES(timeToNextEvent);
1500
1501 #ifdef CPU_CLOCK_CHECKING
1502 #ifndef THREADED_65C02
1503 totalCPU += USEC_TO_M6502_CYCLES(timeToNextEvent);
1504 #endif
1505 #endif
1506                 // Handle CPU time delta for sound...
1507 //Don't need this anymore now that we use absolute time...
1508 //              AddToSoundTimeBase(USEC_TO_M6502_CYCLES(timeToNextEvent));
1509                 HandleNextEvent();
1510         }
1511
1512 #ifdef THREADED_65C02
1513 WriteLog("Main: cpuFinished = true;\n");
1514 cpuFinished = true;
1515 //#warning "If sound thread is behind, CPU thread will never wake up... !!! FIX !!!" [DONE]
1516 //What to do? How do you know when the CPU is sleeping???
1517 //USE A CONDITIONAL!!! OF COURSE!!!!!!11!11!11!!!1!
1518 #if 0
1519 SDL_mutexP(mainMutex);
1520 SDL_CondWait(mainCond, mainMutex);      // Wait for CPU thread to get to signal point...
1521 SDL_mutexV(mainMutex);
1522 #else
1523 //Nope, use a semaphore...
1524 WriteLog("Main: SDL_SemWait(mainSem);\n");
1525 SDL_SemWait(mainSem);//should lock until CPU thread is waiting...
1526 #endif
1527
1528 WriteLog("Main: SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up\n");
1529 SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up
1530 WriteLog("Main: SDL_WaitThread(cpuThread, NULL);\n");
1531 SDL_WaitThread(cpuThread, NULL);
1532 //nowok:SDL_WaitThread(CPUThreadFunc, NULL);
1533 WriteLog("Main: SDL_DestroyCond(cpuCond);\n");
1534 SDL_DestroyCond(cpuCond);
1535
1536 //SDL_DestroyMutex(mainMutex);
1537 SDL_DestroySemaphore(mainSem);
1538 #endif
1539
1540         if (settings.autoStateSaving)
1541         {
1542                 // Save state here...
1543                 SaveApple2State(settings.autoStatePath);
1544         }
1545 floppyDrive.SaveImage();
1546
1547         SoundDone();
1548         VideoDone();
1549         SaveSettings();
1550         LogDone();
1551
1552         return 0;
1553 }
1554
1555
1556 /*
1557 Apple II keycodes
1558 -----------------
1559
1560 Key     Aln CTL SHF BTH
1561 -----------------------
1562 space   $A0     $A0     $A0 $A0         No xlation
1563 RETURN  $8D     $8D     $8D     $8D             No xlation
1564 0               $B0     $B0     $B0     $B0             Need to screen shift+0 (?)
1565 1!              $B1 $B1 $A1 $A1         No xlation
1566 2"              $B2     $B2     $A2     $A2             No xlation
1567 3#              $B3     $B3     $A3     $A3             No xlation
1568 4$              $B4     $B4     $A4     $A4             No xlation
1569 5%              $B5     $B5     $A5     $A5             No xlation
1570 6&              $B6     $B6     $A6     $A6             No xlation
1571 7'              $B7     $B7     $A7     $A7             No xlation
1572 8(              $B8     $B8     $A8     $A8             No xlation
1573 9)              $B9     $B9     $A9     $A9             No xlation
1574 :*              $BA     $BA     $AA     $AA             No xlation
1575 ;+              $BB     $BB     $AB     $AB             No xlation
1576 ,<              $AC     $AC     $BC     $BC             No xlation
1577 -=              $AD     $AD     $BD     $BD             No xlation
1578 .>              $AE     $AE     $BE     $BE             No xlation
1579 /?              $AF     $AF     $BF     $BF             No xlation
1580 A               $C1     $81     $C1     $81
1581 B               $C2     $82     $C2     $82
1582 C               $C3     $83     $C3     $83
1583 D               $C4     $84     $C4     $84
1584 E               $C5     $85     $C5     $85
1585 F               $C6     $86     $C6     $86
1586 G               $C7     $87     $C7     $87
1587 H               $C8     $88     $C8     $88
1588 I               $C9     $89     $C9     $89
1589 J               $CA     $8A     $CA     $8A
1590 K               $CB     $8B     $CB     $8B
1591 L               $CC     $8C     $CC     $8C
1592 M               $CD     $8D     $DD     $9D             -> ODD
1593 N^              $CE     $8E     $DE     $9E             -> ODD
1594 O               $CF     $8F     $CF     $8F
1595 P@              $D0     $90     $C0     $80             Need to xlate CTL+SHFT+P & SHFT+P (?)
1596 Q               $D1     $91     $D1     $91
1597 R               $D2     $92     $D2     $92
1598 S               $D3     $93     $D3     $93
1599 T               $D4     $94     $D4     $94
1600 U               $D5     $95     $D5     $95
1601 V               $D6     $96     $D6     $96
1602 W               $D7     $97     $D7     $97
1603 X               $D8     $98     $D8     $98
1604 Y               $D9     $99     $D9     $99
1605 Z               $DA     $9A     $DA     $9A
1606 <-              $88     $88     $88     $88
1607 ->              $95     $95     $95     $95
1608 ESC             $9B     $9B     $9B     $9B             No xlation
1609
1610 */
1611 //static uint64_t lastCPUCycles = 0;
1612 static uint32_t frameCount = 0;
1613 static void FrameCallback(void)
1614 {
1615         SDL_Event event;
1616
1617         while (SDL_PollEvent(&event))
1618         {
1619                 switch (event.type)
1620                 {
1621                 case SDL_TEXTINPUT:
1622 //Need to do some key translation here, and screen out non-apple keys as well...
1623 //(really, could do it all in SDL_KEYDOWN, would just have to get symbols &
1624 // everything else done separately. this is slightly easier. :-P)
1625 //                      if (event.key.keysym.sym == SDLK_TAB)   // Prelim key screening...
1626                         if (event.edit.text[0] == '\t') // Prelim key screening...
1627                                 break;
1628
1629                         lastKeyPressed = event.edit.text[0];
1630                         keyDown = true;
1631
1632                         //kludge: should have a caps lock thingy here...
1633                         //or all uppercase for ][+...
1634 //                      if (lastKeyPressed >= 'a' && lastKeyPressed <='z')
1635 //                              lastKeyPressed &= 0xDF;         // Convert to upper case...
1636
1637                         break;
1638                 case SDL_KEYDOWN:
1639                         // CTRL+RESET key emulation (mapped to CTRL+`)
1640 // This doesn't work...
1641 //                      if (event.key.keysym.sym == SDLK_BREAK && (event.key.keysym.mod & KMOD_CTRL))
1642 //                      if (event.key.keysym.sym == SDLK_PAUSE && (event.key.keysym.mod & KMOD_CTRL))
1643                         if (event.key.keysym.sym == SDLK_BACKQUOTE && (event.key.keysym.mod & KMOD_CTRL))
1644 //NOTE that this shouldn't take place until the key is lifted... !!! FIX !!!
1645 //ALSO it seems to leave the machine in an inconsistent state vis-a-vis the language card...
1646                                 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
1647
1648                         if (event.key.keysym.sym == SDLK_RIGHT)
1649                                 lastKeyPressed = 0x15, keyDown = true;
1650                         else if (event.key.keysym.sym == SDLK_LEFT)
1651                                 lastKeyPressed = 0x08, keyDown = true;
1652                         else if (event.key.keysym.sym == SDLK_UP)
1653                                 lastKeyPressed = 0x0B, keyDown = true;
1654                         else if (event.key.keysym.sym == SDLK_DOWN)
1655                                 lastKeyPressed = 0x0A, keyDown = true;
1656                         else if (event.key.keysym.sym == SDLK_RETURN)
1657                                 lastKeyPressed = 0x0D, keyDown = true;
1658                         else if (event.key.keysym.sym == SDLK_ESCAPE)
1659                                 lastKeyPressed = 0x1B, keyDown = true;
1660                         else if (event.key.keysym.sym == SDLK_BACKSPACE)
1661                                 lastKeyPressed = 0x7F, keyDown = true;
1662
1663                         // Fix CTRL+key combo...
1664                         if (event.key.keysym.mod & KMOD_CTRL)
1665                         {
1666                                 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
1667                                 {
1668                                         lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 1;
1669                                         keyDown = true;
1670 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
1671                                 }
1672                         }
1673
1674                         // Use ALT+Q to exit, as well as the usual window decoration method
1675                         if (event.key.keysym.sym == SDLK_q && (event.key.keysym.mod & KMOD_ALT))
1676                                 running = false;
1677
1678                         if (event.key.keysym.sym == SDLK_PAUSE)
1679                         {
1680                                 pauseMode = !pauseMode;
1681
1682                                 if (pauseMode)
1683                                 {
1684                                         SoundPause();
1685                                         SpawnMessage("*** PAUSED ***");
1686                                 }
1687                                 else
1688                                 {
1689                                         SoundResume();
1690                                         SpawnMessage("*** RESUME ***");
1691                                 }
1692                         }
1693
1694                         // Paddle buttons 0 & 1
1695                         if (event.key.keysym.sym == SDLK_INSERT)
1696                                 openAppleDown = true;
1697                         if (event.key.keysym.sym == SDLK_PAGEUP)
1698                                 closedAppleDown = true;
1699
1700                         if (event.key.keysym.sym == SDLK_F11)
1701                                 dumpDis = !dumpDis;                             // Toggle the disassembly process
1702 //                      else if (event.key.keysym.sym == SDLK_F11)
1703 //                              floppyDrive.LoadImage("./disks/bt1_char.dsk");//Kludge to load char disk...
1704 else if (event.key.keysym.sym == SDLK_F9)
1705 {
1706         floppyDrive.CreateBlankImage();
1707 //      SpawnMessage("Image cleared...");
1708 }//*/
1709 else if (event.key.keysym.sym == SDLK_F10)
1710 {
1711         floppyDrive.SwapImages();
1712 //      SpawnMessage("Image swapped...");
1713 }//*/
1714
1715                         if (event.key.keysym.sym == SDLK_F2)// Toggle the palette
1716                                 TogglePalette();
1717                         else if (event.key.keysym.sym == SDLK_F3)// Cycle through screen types
1718                                 CycleScreenTypes();
1719
1720 //                      if (event.key.keysym.sym == SDLK_F5)    // Temp GUI launch key
1721                         if (event.key.keysym.sym == SDLK_F1)    // GUI launch key
1722 //NOTE: Should parse the output to determine whether or not the user requested
1723 //      to quit completely... !!! FIX !!!
1724                                 gui->Run();
1725
1726                         if (event.key.keysym.sym == SDLK_F5)
1727                         {
1728                                 VolumeDown();
1729                                 char volStr[19] = "[****************]";
1730 //                              volStr[GetVolume()] = 0;
1731                                 for(int i=GetVolume(); i<16; i++)
1732                                         volStr[1 + i] = '-';
1733                                 SpawnMessage("Volume: %s", volStr);
1734                         }
1735                         else if (event.key.keysym.sym == SDLK_F6)
1736                         {
1737                                 VolumeUp();
1738                                 char volStr[19] = "[****************]";
1739 //                              volStr[GetVolume()] = 0;
1740                                 for(int i=GetVolume(); i<16; i++)
1741                                         volStr[1 + i] = '-';
1742                                 SpawnMessage("Volume: %s", volStr);
1743                         }
1744
1745                         static bool fullscreenDebounce = false;
1746
1747                         if (event.key.keysym.sym == SDLK_F12)
1748                         {
1749                                 if (!fullscreenDebounce)
1750                                 {
1751                                         ToggleFullScreen();
1752                                         fullscreenDebounce = true;
1753                                 }
1754                         }
1755 //                      else
1756
1757                         break;
1758                 case SDL_KEYUP:
1759                         if (event.key.keysym.sym == SDLK_F12)
1760                                 fullscreenDebounce = false;
1761
1762                         // Paddle buttons 0 & 1
1763                         if (event.key.keysym.sym == SDLK_INSERT)
1764                                 openAppleDown = false;
1765                         if (event.key.keysym.sym == SDLK_PAGEUP)
1766                                 closedAppleDown = false;
1767
1768 //                      if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
1769 //                              keyDown = false;
1770
1771                         break;
1772                 case SDL_QUIT:
1773                         running = false;
1774                 }
1775         }
1776
1777 //#warning "!!! Taking MAJOR time hit with the video frame rendering !!!"
1778         RenderVideoFrame();
1779         SetCallbackTime(FrameCallback, 16666.66666667);
1780
1781 #ifdef CPU_CLOCK_CHECKING
1782 //We know it's stopped, so we can get away with this...
1783 counter++;
1784 if (counter == 60)
1785 {
1786         uint64_t clock = GetCurrentV65C02Clock();
1787 //totalCPU += (uint32_t)(clock - lastClock);
1788
1789         printf("Executed %u cycles...\n", (uint32_t)(clock - lastClock));
1790         lastClock = clock;
1791 //      totalCPU = 0;
1792         counter = 0;
1793 }
1794 #endif
1795 //Instead of this, we should yield remaining time to other processes... !!! FIX !!! [DONE]
1796 //lessee...
1797 //nope.
1798 //Actually, slows things down too much...
1799 //SDL_Delay(10);
1800 //      while (SDL_GetTicks() - startTicks < 16);       // Wait for next frame...
1801
1802 // This is the problem: If you set the interval to 16, it runs faster than
1803 // 1/60s per frame. If you set it to 17, it runs slower. What we need is to
1804 // have it do 16 for one frame, then 17 for two others. Then it should average
1805 // out to 1/60s per frame every 3 frames.
1806         frameCount = (frameCount + 1) % 3;
1807
1808         uint32_t waitFrameTime = 17 - (frameCount == 0 ? 1 : 0);
1809
1810         while (SDL_GetTicks() - startTicks < waitFrameTime)
1811                 SDL_Delay(1);                                                   // Wait for next frame...
1812
1813         startTicks = SDL_GetTicks();
1814 #if 0
1815         uint64_t cpuCycles = GetCurrentV65C02Clock();
1816         uint32_t cyclesBurned = (uint32_t)(cpuCycles - lastCPUCycles);
1817         WriteLog("FrameCallback: used %i cycles\n", cyclesBurned);
1818         lastCPUCycles = cpuCycles;
1819 #endif
1820
1821 //let's wait, then signal...
1822 //works longer, but then still falls behind...
1823 #ifdef THREADED_65C02
1824         if (!pauseMode)
1825                 SDL_CondSignal(cpuCond);//OK, let the CPU go another frame...
1826 #endif
1827 }
1828
1829
1830 static void BlinkTimer(void)
1831 {
1832         flash = !flash;
1833         SetCallbackTime(BlinkTimer, 250000);            // Set up blinking at 1/4 sec intervals
1834 }
1835
1836
1837 /*
1838 Next problem is this: How to have events occur and synchronize with the rest
1839 of the threads?
1840
1841   o Have the CPU thread manage the timer mechanism? (need to have a method of carrying
1842     remainder CPU cycles over...)
1843
1844 One way would be to use a fractional accumulator, then subtract 1 every
1845 time it overflows. Like so:
1846
1847 double overflow = 0;
1848 uint32_t time = 20;
1849 while (!done)
1850 {
1851         Execute6808(&soundCPU, time);
1852         overflow += 0.289115646;
1853         if (overflow > 1.0)
1854         {
1855                 overflow -= 1.0;
1856                 time = 21;
1857         }
1858         else
1859                 time = 20;
1860 }
1861 */