#include <zlib.h>

#include "io.h"
#include "menu.h"
#include "gbcore/gb.h"

uLong sram_crc;

int io_save_sram(byte *buf,int size)
{
	int ret=1;
	const int sram_tbl[]={1,1,1,4,16,8};
	int sram_size = 0x2000 * sram_tbl[size];

	if (rom_get_info()->cart_type>=0x0f && rom_get_info()->cart_type<=0x13){
		int tmp = renderer_get_timer_state();
		memcpy(buf+sram_size, &tmp, sizeof(int));
		sram_size += sizeof(int);
	}

	uLong crc = crc32(0L, Z_NULL, 0);
	crc = crc32(crc, buf, sram_size);
	if (sram_crc == crc)
		return 1;
	
	sprintf(SavePath, "%s/%s.save", SRAM_FOLDER, RomName);
	
	cheat_decreate_cheat_map();
	ret = io_file_write(SavePath, buf, sram_size);
	cheat_create_cheat_map();
	
	if(ret)
		sram_crc = crc;
	
	return ret;
}

int io_load_sram(byte *buf, int bufsize)
{	
	int ramsize;
	memset(buf, 0, bufsize);
	sram_crc = crc32(0L, Z_NULL, 0);
	
	sprintf(SavePath, "%s/%s.save", SRAM_FOLDER, RomName);
	
	ramsize = io_file_read(SavePath, buf, bufsize);
	
	if(ramsize & 4)
		renderer_set_timer_state(*(int*)(buf+ramsize-4));
	
	sram_crc = crc32(sram_crc, buf, ramsize);
	
	return ramsize;
}
