// TestMemory.cpp: implementation of the TestMemory class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "archimedes.h"
#include "TestMemory.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CTestMemory::CTestMemory(uint32 aSize)
{
	TRACE("construct CTestMemory \n");

	// allocate buffer
	size = aSize;
	TRACE("size being declared = 0x%x\n", size);
	memory = new uint8[size];
}

CTestMemory::~CTestMemory()
{
	delete []memory;
}

BOOL CTestMemory::readWord(uint32 address, uint32 &location)
{
	if(address < size)
	{
		uint32 data;
		data = memory[address];
		data |= memory[address+1]<<8;
		data |= memory[address+2]<<16;
		data |= memory[address+3]<<24;
		location = data;
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

BOOL CTestMemory::readByte(uint32 address, uint8 &location)
{
	if(address < size)
	{
		location = memory[address];
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

BOOL CTestMemory::writeWord(uint32 address, uint32 value)
{
	if(address < size)
	{
		memory[address] = value && 0xff;
		memory[address+1] = (value >> 8) & 0xff;
		memory[address+2] = (value >> 16) & 0xff;
		memory[address+3] = (value >> 24) & 0xff;
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

BOOL CTestMemory::writeByte(uint32 address, uint8 value)
{
	if(address < size)
	{
		memory[address] = value;
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

//
// specify a file and an address and the number of bytes to load
// into the memory space at that address (or -1 to load the whole file)
// returns TRUE if successful
//

BOOL CTestMemory::loadIntoMemory(CString fileName, uint32 address, uint32 numberOfBytes)
{
	CFile loadFile;
	if( loadFile.Open(fileName, CFile::modeRead) )
	{
		// if -1 then load entire file
		if(numberOfBytes == -1)
			numberOfBytes = loadFile.GetLength();

		// check size of my buffer and limit it to max possible
		if(numberOfBytes > (size-address) )
		{
			numberOfBytes = size - address;
			TRACE("ERROR: couldn't load entire file into memory");
		}

		uint bytesRead = loadFile.Read(memory + address, numberOfBytes);
		
		loadFile.Close();


		// ??? debugging
		for(uint counter = 0; counter<bytesRead; counter+=4)
		{
			uint32 data;
			readWord(address+counter, data);
			TRACE("0x%x \n", data);
		}

		return TRUE;
	}
	else
	{
		// file not found
		return FALSE;
	}
}
