From 22724803c1f335c6203bf1b7e45161d124261309 Mon Sep 17 00:00:00 2001
From: Leandro Nini <drfiemost@users.noreply.github.com>
Date: Mon, 22 Mar 2021 17:57:30 +0100
Subject: [PATCH 1/2] Do not switch bank if outside the range [1,31]

---
 gme/Gbs_Emu.cpp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/gme/Gbs_Emu.cpp b/gme/Gbs_Emu.cpp
index 9f751e5..542be4a 100644
--- a/gme/Gbs_Emu.cpp
+++ b/gme/Gbs_Emu.cpp
@@ -147,6 +147,9 @@ void Gbs_Emu::set_voice( int i, Blip_Buffer* c, Blip_Buffer* l, Blip_Buffer* r )
 
 void Gbs_Emu::set_bank( int n )
 {
+	if ((n<1) || (n>31))
+		return;
+
 	blargg_long addr = rom.mask_addr( n * (blargg_long) bank_size );
 	if ( addr == 0 && rom.size() > bank_size )
 	{
-- 
2.10.5


From 5a51d491618a2a50fd5a0790eb7a1b05abf9546c Mon Sep 17 00:00:00 2001
From: Leandro Nini <drfiemost@users.noreply.github.com>
Date: Tue, 23 Mar 2021 13:30:26 +0100
Subject: [PATCH 2/2] Rework bank switching, fixes #39

---
 gme/Gbs_Emu.cpp | 20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)

diff --git a/gme/Gbs_Emu.cpp b/gme/Gbs_Emu.cpp
index 542be4a..dc19215 100644
--- a/gme/Gbs_Emu.cpp
+++ b/gme/Gbs_Emu.cpp
@@ -147,19 +147,19 @@ void Gbs_Emu::set_voice( int i, Blip_Buffer* c, Blip_Buffer* l, Blip_Buffer* r )
 
 void Gbs_Emu::set_bank( int n )
 {
-	if ((n<1) || (n>31))
-		return;
-
-	blargg_long addr = rom.mask_addr( n * (blargg_long) bank_size );
-	if ( addr == 0 && rom.size() > bank_size )
+	// Only valid for MBC1 cartridges, but hopefully shouldn't hurt
+	n &= 0x1f;
+	if (n == 0)
+	{
+		n = 1;
+	}
+	
+	blargg_long addr = n * (blargg_long) bank_size;
+	if (addr > rom.size())
 	{
-		// TODO: what is the correct behavior? Current Game & Watch Gallery
-		// rip requires that this have no effect or set to bank 1.
-		//debug_printf( "Selected ROM bank 0\n" );
 		return;
-		//n = 1;
 	}
-	cpu::map_code( bank_size, bank_size, rom.at_addr( addr ) );
+	cpu::map_code( bank_size, bank_size, rom.at_addr( rom.mask_addr( addr ) ) );
 }
 
 void Gbs_Emu::update_timer()
-- 
2.10.5

