// Copyright (C) 2003 Dolphin Project.

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2.0.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License 2.0 for more details.

// A copy of the GPL 2.0 should have been included with the program.
// If not, see http://www.gnu.org/licenses/

// Official SVN repository and contact information can be found at
// http://code.google.com/p/dolphin-emu/

#include "Sram.h"
#include "../ConfigManager.h"
// english
SRAM sram_dump = {{
	0x04, 0x6B,
	0xFB, 0x91,
	0x00, 0x00, 0x00, 0x00,
	0x00, 0x00, 0x00, 0x00,
	0xFF, 0xFF, 0xFF, 0x40,
	0x05,
	0x00,
	0x00,
	0x2C,
	0x44, 0x4F, 0x4C, 0x50, 0x48, 0x49, 0x4E, 0x53, 0x4C, 0x4F, 0x54, 0x41,
	0x44, 0x4F, 0x4C, 0x50, 0x48, 0x49, 0x4E, 0x53, 0x4C, 0x4F, 0x54, 0x42,
	0x00, 0x00, 0x00, 0x00,
	0x00, 0x00,
	0x00, 0x00,
	0x00, 0x00,
	0x00, 0x00,
	0x00,
	0x00,
	0x6E, 0x6D,
	0x00, 0x00,
	0x00, 0x00
}};

#if 0
// german
SRAM sram_dump_german = {{ 
	0x1F, 0x66,
	0xE0, 0x96,
	0x00, 0x00, 0x00, 0x00,
	0x00, 0x00, 0x00, 0x00,
	0x04, 0xEA, 0x19, 0x40,
	0x00,
	0x00,
	0x01,
	0x3C,
	0x12, 0xD5,	0xEA, 0xD3,	0x00, 0xFA,	0x2D, 0x33, 0x13, 0x41, 0x26, 0x03,
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
	0x00, 0x00, 0x00, 0x00,
	0x00, 0x00,
	0x00, 0x00,
	0x00, 0x00,
	0x00, 0x00,
	0x00,
	0x00,
	0x84, 0xFF,
	0x00, 0x00,
	0x00, 0x00
}};
#endif

void initSRAM()
{
	File::IOFile file(SConfig::GetInstance().m_LocalCoreStartupParameter.m_strSRAM, "rb");
	if (file)
	{
		if (!file.ReadArray(&g_SRAM, 1))
		{
			ERROR_LOG(EXPANSIONINTERFACE,  "EXI IPL-DEV: Could not read all of SRAM");
			g_SRAM = sram_dump;
		}
	}
	else
	{
		g_SRAM = sram_dump;
	}
}

void SetCardFlashID(u8* buffer, u8 card_index)
{
	u64 rand = Common::swap64( *(u64*)&(buffer[12]));
	u8 csum=0;
	for(int i = 0; i < 12; i++)
	{
		rand = (((rand * (u64)0x0000000041c64e6dULL) + (u64)0x0000000000003039ULL) >> 16);
		csum += g_SRAM.flash_id[card_index][i] = buffer[i] - ((u8)rand&0xff);
		rand = (((rand * (u64)0x0000000041c64e6dULL) + (u64)0x0000000000003039ULL) >> 16);	
		rand &= (u64)0x0000000000007fffULL;
	}
	g_SRAM.flashID_chksum[card_index] = csum^0xFF;
}

