#include "stdafx.h"
#include "MapConverter.h"
#include "MapMakerMap.h"
#include <stdio.h>

MapMakerMap::MapMakerMap(void)
{
	m_bInit   = FALSE;
	m_dwWidth = 0;
	m_dwHeight= 0;
}

MapMakerMap::~MapMakerMap()
{
	if (m_bInit)
	{
		m_bInit= FALSE;
		if (m_pMap)
		{
			free (m_pMap);
			m_pMap = NULL;
		}
	}
}

BOOL MapMakerMap::Create(const char *szFilename)
{
	// Load a MapMaker map from file.

	FILE *f;

	f= fopen(szFilename, "rb");

	// Read size and Magic bytes to check if this is a 
	// valid file

	DWORD size=0;
	
	fread(&size, sizeof(DWORD), 1, f);
	if (size != 0x0134)
	{
		fclose(f);
		return FALSE;
	}

	DWORD magic;
	fread(&magic, sizeof(DWORD), 1, f);
	if (magic !=  0x0050414d) // magic != (4d,41,50,00 = "MAP\0") (Intel byte ordering!)
	{
		fclose(f);
		return FALSE;
	}

	// Check version, only 1.1 supported
	WORD version;
	fread(&version, sizeof(WORD), 1,f);
	if (version != 0x0101)
	{
		fclose(f);
		return FALSE;
	}

	// skip the next two bytes
	fseek(f, 2, SEEK_CUR);

	// Read width and height
	DWORD width, height;
	fread(&width , sizeof(DWORD), 1, f);
	fread(&height, sizeof(DWORD), 1, f);

	// Skip the rest of the header, and go to the data 
	fseek(f, 0x0134, SEEK_SET);

	// Now, let's create an array large enough to hold all the data...
	MapMakerCell* map;
	map = (MapMakerCell*) malloc( width * height * sizeof(MapMakerCell));
	if (!map)
	{
		// No memory
		fclose(f);
		return NULL;
	}
	LONG cur =0;
	//char buff[200];
	WORD tmp;

	for (int y=0; y< height; y++)
	{
		for (int x=0; x<width; x++)
		{
			for (int act_layer=0; act_layer <4; act_layer++)
			{
				
				fread(&tmp, sizeof(WORD), 1, f);
				map[cur].layer[act_layer] = tmp;
			}

			fread(&(map[cur].walkability), 1, 1, f);
			fread(&(map[cur].walkspecial), 1, 1, f);
			fread(&(map[cur].flags      ), 4, 1, f);
			fread(&tmp                   , 2, 1, f);
			fread(&(map[cur].special    ), 4, 1, f);
			cur++;
		}
	}
	fclose(f);

	m_dwWidth  = width;
	m_dwHeight = height;
	m_pMap     = map;

	m_bInit = TRUE;

	return TRUE;
}

//inline
MapMakerCell *MapMakerMap::GetAt(DWORD x, DWORD y)
{
	return &(m_pMap[x + y*m_dwWidth]);
}

//inline
WORD MapMakerMap::GetTileAt(DWORD x, DWORD y, DWORD layer)
{
	return (m_pMap[x + y*m_dwWidth]).layer[layer];
}

//inline
DWORD MapMakerMap::GetWidth(void)
{
	return m_dwWidth;
}

//inline
DWORD MapMakerMap::GetHeight(void)
{
	return m_dwHeight;
}


