private void loadiNes(string filename)
{
FileStream fs = File.OpenRead(filename);
StreamReader r = new StreamReader(fs);
// Check header
byte[] buffer = new byte[4];
fs.Read(buffer, 0, 4);
if ((buffer[0] != 0x4E) || (buffer[1] != 0x45) || (buffer[2] != 0x53) || (buffer[3] != 0x1A))
throw new FileLoadException("Unsupported file format!");
// Datas!
byte numPRG = (byte)fs.ReadByte();
byte numCHR = (byte)fs.ReadByte();
byte control1 = (byte)fs.ReadByte();
byte control2 = (byte)fs.ReadByte();
byte numRAM = (byte)fs.ReadByte();
buffer = new byte[7];
fs.Read(buffer, 0, 7); // blank.
// Sanity check, 16byte header?
if (fs.Position != 16)
throw new FileLoadException("We did it wrong!");
// Process!
numRAM = (numRAM == 0) ? (byte)1 : numRAM;
Cartridge = new Cartridge(this, numPRG, numCHR, numRAM);
// Control 1
PPU.Mirroring = ((control1 & 1) > 0) ? Mirroring.Vertical : Mirroring.Horizontal; // Bit 0 - Type of mirroring
Cartridge.SRAM = ((control1 & 2) > 0) ? true : false; // Bit 1 - Presence of SRAM
Cartridge.HasTrainer = ((control1 & 4) > 0) ? true : false; // Bit 2 - Presence of Trainer
if ((control1 & 8) > 0) // Bit 3 - If set, overrides bit 0 to indicate 4-screen mirroring
PPU.Mirroring = Mirroring.None;
Cartridge.MapperNumer = (control1 & 0xF0) >> 4; // Bit 4-7 - 4 lower bits of mapper number
// Control 2
Cartridge.MapperNumer |= (control2 & 0xF0); // Bit 4-7 - 4 upper bits of mapper number
// Trainer
if (Cartridge.HasTrainer)
fs.Read(Cartridge.Trainer, 0, Cartridge.TrainerLength);
// Load PRG-ROM
for (int i = 0; i < numPRG; i++)
{
Cartridge.PRGROMBanks[i] = new byte[Cartridge.PRGLength];
fs.Read(Cartridge.PRGROMBanks[i], 0, Cartridge.PRGLength);
}
// Load CHR-ROM
for (int i = 0; i < numCHR; i++)
{
Cartridge.CHRBanks[i] = new byte[Cartridge.CHRLength];
fs.Read(Cartridge.CHRBanks[i], 0, Cartridge.CHRLength);
}
}