Import Upstream version 1.23
[debian-dgen.git] / md-joe.cpp
blob47f4779705eda11554354786f283be6cd800c875
1 // DGen/SDL v1.15+
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include "md.h"
7 #include "decode.h"
9 // These are my (Joe's) functions added to the md class.
11 // This takes a comma or whitespace-separated list of Game Genie and/or hex
12 // codes to patch the ROM with.
13 void md::patch(const char *list)
15 static const char delims[] = " \t\n,";
16 char *worklist, *tok;
17 struct patch p;
19 // Copy the given list to a working list so we can strtok it
20 worklist = (char*)malloc(strlen(list)+1);
21 strcpy(worklist, list);
23 for(tok = strtok(worklist, delims); tok; tok = strtok(NULL, delims))
25 // If it's empty, toss it
26 if(*tok == '\0') continue;
27 // Decode it
28 decode(tok, &p);
29 // Discard it if it was bad code
30 if((signed)p.addr == -1) {
31 printf("Bad patch \"%s\"\n", tok);
32 continue;
34 // Put it into the ROM (remember byteswapping)
35 printf("Patch \"%s\" -> %06X:%04X\n", tok, p.addr, p.data);
36 rom[p.addr] = (char)(p.data & 0xFF);
37 rom[p.addr+1] = (char)((p.data & 0xFF00) >> 8);
39 // Done!
40 free(worklist);
41 return;
44 // Get/put saveram from/to FILE*'s
45 void md::get_save_ram(FILE *from)
47 // Pretty simple, just read the saveram raw
48 fread((void*)saveram, 1, save_len, from);
51 void md::put_save_ram(FILE *into)
53 // Just the opposite of the above :)
54 fwrite((void*)saveram, 1, save_len, into);
57 // Dave: This is my code, but I thought it belonged here
58 // Joe: Thanks Dave! No problem ;)
59 static unsigned short calculate_checksum(unsigned char *rom,int len)
61 unsigned short checksum=0;
62 int i;
63 for (i=512;i<=(len-2);i+=2)
65 checksum+=(rom[i+1]<<8);
66 checksum+=rom[i+0];
68 return checksum;
71 void md::fix_rom_checksum()
73 unsigned short cs; cs=calculate_checksum(rom,romlen);
74 if (romlen>=0x190) { rom[0x18f]=cs>>8; rom[0x18e]=cs&255; }