#include "stdafx.h"
#define CDXINCLUDEALL
#include <cdx.h>
#include "Map_Load.h"

BOOL LoadMap( char *str, CDXMap **&Map, CDXTile **&Tiles, int *&WalkBits, char TileSet[2][21], int ctr, CDXScreen *Screen )
{
	int i;
	sMapHeader MapHeader;
	FILE *fptr = fopen( str, "rb" );
	if( fptr == NULL ) return FALSE;

	fseek( fptr, -(int)sizeof( MapHeader ), SEEK_END );
	fread( &MapHeader, sizeof( MapHeader ), 1, fptr );

	DELETEARRAY( WalkBits );
	for( i=0; i<ctr; i++ )
		SAFEDELETE( Map[i] );

	if( strncmp( MapHeader.Id, "EXT", 3 ) )
	{
		if( Tiles[0] )
		{
			Map[0] = new CDXMap(Tiles[0], Screen);
			fseek( fptr, 0, SEEK_SET );
			Map[0]->Load( fptr );
			Tiles[0]->LoadAnim( fptr );

			WalkBits = new int[Map[0]->GetMapSize()];
			ZeroMemory( WalkBits, Map[0]->GetMapSize() );
		}
	}
	else
	{
		sLayerInfo *LayerInfo = new sLayerInfo[MapHeader.gfxLayers];
		fseek( fptr, -(int)(sizeof( MapHeader )+MapHeader.gfxLayers*sizeof( sLayerInfo )), SEEK_END );
		fread( LayerInfo, sizeof( sLayerInfo), MapHeader.gfxLayers, fptr );

		for( i=0; i<MapHeader.gfxLayers; i++ )
		{
			if( LayerInfo[i].offset != -1 )
			{
				if( LayerInfo[i].TileSet[0] )
				{
					SAFEDELETE( Tiles[i] );
					Tiles[i] = new CDXTile();
					Tiles[i]->Create(Screen, LayerInfo[i].TileSet, 32, 32, 0);
					strcpy( TileSet[i], LayerInfo[i].TileSet );
				}

				if( Tiles[i] )
				{
					Map[i] = new CDXMap(Tiles[i], Screen);
					fseek( fptr, LayerInfo[i].offset, SEEK_SET );
					Map[i]->Load( fptr );
					Tiles[i]->LoadAnim( fptr );
				}
			}
		}

		if( MapHeader.WalkBitsOffset>0 )
		{
			fseek( fptr, MapHeader.WalkBitsOffset, SEEK_SET );
			WalkBits = new int[Map[0]->GetMapSize()];
			fread( WalkBits, sizeof( int ), Map[0]->GetMapSize(), fptr );
		}
		DELETEARRAY( LayerInfo );
	}

	fclose( fptr );
	return TRUE;    
}

BOOL SaveMap( char *str, CDXMap **Map, CDXTile **Tiles, int *&WalkBits, char TileSet[2][21], int ctr )
{
	int i;
	sMapHeader MapHeader;
	ZeroMemory( &MapHeader, sizeof( MapHeader ) );
	memcpy( MapHeader.Id, "EXT", 3 );

	FILE *fptr = fopen( str, "wb" );
	if( fptr == NULL ) return FALSE;

	sLayerInfo *LayerInfo = new sLayerInfo[ctr];
	ZeroMemory( LayerInfo, sizeof( sLayerInfo )*ctr );
	MapHeader.gfxLayers=ctr;
			
	for( i=0; i<ctr; i++ )
	{
		if( Map[i] )
		{	
			LayerInfo[i].offset=ftell( fptr );
			Map[i]->Save( fptr );
			Tiles[i]->SaveAnim( fptr );
		}
		else LayerInfo[i].offset=-1;
		strncpy( LayerInfo[i].TileSet, TileSet[i], 20 );
	}

//	MapHeader.WalkBitsOffset=ftell( fptr );
//	fwrite( WalkBits, sizeof(int), Map[0]->SIZE, fptr );

	MapHeader.LayerInfoOffset=ftell( fptr );
	fwrite( LayerInfo, sizeof( sLayerInfo ), ctr, fptr );
	DELETEARRAY( LayerInfo );

	fwrite( &MapHeader, sizeof( MapHeader ), 1, fptr );
	fclose( fptr );

	return TRUE;
}