//==============================================================================
//
// Snake
// -----
// http://www.masterspace.biz/andreschnabel/
// 2006 by André Schnabel (thefrogs@web.de)
//
//==============================================================================

// map.c

#include "map.h"
#include "utils.h"

int map[MAP_HEIGHT][MAP_WIDTH];

void ClearMap()
{
	int k, l;
	
	for(k=0; k<MAP_HEIGHT; k++)
		for(l=0; l<MAP_WIDTH; l++)
			map[k][l] = 0;
}

void LoadMap(const char *filename)
{
	FILE *fp;
	char c;
	int i=0, j=0;
	char fullFname[100];
	
	ClearMap();
	
	strcpy(fullFname, "maps/");
	strcat(fullFname, filename);
	
	fp = fopen(fullFname, "r");
	if(!fp)
		Error("Can't load map!");

	while(!feof(fp))
	{
		c = fgetc(fp);
		
		if(c >= '0' && c <= '9')
		{
			if(i == MAP_HEIGHT || j == MAP_WIDTH)
			{
				printf("i= %d, j= %d!\n", i, j);
				Error("Mapfile to huge!");
			}
			
			map[i][j] = c - '0';
			
			if(j < MAP_WIDTH-1)
				j++;
			else
			{
				i++;
				j = 0;
			}
		}
		else
			continue;
	}
	
	fclose(fp);
}

void SaveMap(const char *filename)
{
	FILE *fp;
	char fullFname[100];
	int i, j;
	char c;
	
	strcpy(fullFname, "maps/");
	strcat(fullFname, filename);
	
	fp = fopen(fullFname, "w");
	
	for(i=0; i<MAP_HEIGHT; i++)
	{
		for(j=0; j<MAP_WIDTH; j++)
		{
			c = map[i][j] + '0';
			fputc(c, fp);
		}
	}
	
	fclose(fp);
}

void DrawMap(void)
{
	int i, j;
	static SDL_Rect rect;
	
	rect.w = BLOCK_W;
	rect.h = BLOCK_H;
	
	for(i=0; i<MAP_HEIGHT; i++)
	{
		for(j=0; j<MAP_WIDTH; j++)
		{
			if(map[i][j] == 1)
			{
				rect.x = j * rect.w;
				rect.y = i * rect.h;
				SDL_BlitSurface(tileImg, NULL, screen, &rect);
			}
		}
	}
}

boolean TileOnPos(int x, int y)
{
	if(x < 0 || y < 0 || x >= SCR_W || y >= SCR_H)
		return false;
	
	return (map[(int)(y/BLOCK_W)][(int)(x/BLOCK_H)] == 1);
}
