From fe687d30f335b7e7fbe22767b3cef2681fae2934 Mon Sep 17 00:00:00 2001
From: zeromus <zeromus@users.sf.net>
Date: Wed, 16 Sep 2015 22:01:33 +0000
Subject: [PATCH] winport - fix memory of custom palettes (part of #711)

---
 trunk/src/drivers/win/config.cpp  |  1 +
 trunk/src/drivers/win/main.cpp    | 10 +++++-----
 trunk/src/drivers/win/main.h      |  1 +
 trunk/src/drivers/win/palette.cpp |  4 +++-
 4 files changed, 10 insertions(+), 6 deletions(-)

diff --git a/trunk/src/drivers/win/config.cpp b/trunk/src/drivers/win/config.cpp
index 87cbd7d4..4f571c04 100644
--- a/trunk/src/drivers/win/config.cpp
+++ b/trunk/src/drivers/win/config.cpp
@@ -227,6 +227,7 @@ static CFGSTRUCT fceuconfig[] =
 	AC(goptions),
 	NAC("eoptions",eoptions),
 	NACA("cpalette",cpalette),
+	NAC("cpalette_count",cpalette_count),
 
 	NACA("InputType",InputType),
 
diff --git a/trunk/src/drivers/win/main.cpp b/trunk/src/drivers/win/main.cpp
index 5a5286b7..bcc1140d 100644
--- a/trunk/src/drivers/win/main.cpp
+++ b/trunk/src/drivers/win/main.cpp
@@ -683,11 +683,11 @@ int main(int argc,char *argv[])
 	DoVideoConfigFix();
 	DoTimingConfigFix();
 
-	//TODO - how can this do anything? we havent set a palette yet
-	//if(eoptions & EO_CPALETTE)
-	//{
-	//	FCEUI_SetUserPalette(cpalette);
-	//}
+	//restore the last user-set palette (cpalette and cpalette_count are preserved in the config file)
+	if(eoptions & EO_CPALETTE)
+	{
+		FCEUI_SetUserPalette(cpalette,cpalette_count);
+	}
 
 	if(!t)
 	{
diff --git a/trunk/src/drivers/win/main.h b/trunk/src/drivers/win/main.h
index c8c40e9e..e4764950 100644
--- a/trunk/src/drivers/win/main.h
+++ b/trunk/src/drivers/win/main.h
@@ -107,6 +107,7 @@ extern int soundquality;
 extern bool muteTurbo;
 extern bool swapDuty;
 
+extern int cpalette_count;
 extern uint8 cpalette[64*8*3];
 extern int srendlinen;
 extern int erendlinen;
diff --git a/trunk/src/drivers/win/palette.cpp b/trunk/src/drivers/win/palette.cpp
index 726be71d..cd7159cd 100644
--- a/trunk/src/drivers/win/palette.cpp
+++ b/trunk/src/drivers/win/palette.cpp
@@ -4,6 +4,7 @@
 #include "window.h"
 #include "gui.h"
 
+int cpalette_count = 0;
 u8 cpalette[64*8*3] = {0};
 extern int  palhue;
 extern bool palhdtv;
@@ -17,7 +18,8 @@ bool SetPalette(const char* nameo)
 	{
 		int readed = fread(cpalette, 1, sizeof(cpalette), fp);
 		fclose(fp);
-		FCEUI_SetUserPalette(cpalette,readed/3);
+		cpalette_count = readed/3;
+		FCEUI_SetUserPalette(cpalette,cpalette_count);
 		eoptions |= EO_CPALETTE;
 		return true;
 	}