#include <stdio.h>

#include <concorde.h>
#include "ysmaze2.h"
#include "mzedit.h"
#include "ysgui.h"


void InsertWall(MAZEMAP *mz,int bx,int by,int dir,int wal,int pas)
{
	int p;
	int lx,ly;

	p= bx+(mz->lx)*by;
	lx=(mz->lx);
	ly=(mz->ly);
	if(pas)pas=1;

	switch(dir)
	{
	case 0:
		if(0<=bx && bx<lx && 0<=by && by<ly)
		{
			mz->map[p] = (mz->map[p] & 0xfffc) | wal;
			mz->map[p] = (mz->map[p] & 0xffef) | (pas * 16);
		}
		else if(ly==by)
		{
			InsertWall(mz,bx,0,dir,wal,pas);
		}
		break;
	case 1:
		if(0<=bx && bx<lx && 0<=by && by<ly)
		{
			mz->map[p] = (mz->map[p] & 0xfff3) | (wal*4);
			mz->map[p] = (mz->map[p] & 0xffdf) | (pas * 32);
		}
		else if(lx==bx)
		{
			InsertWall(mz,0,by,dir,wal,pas);
		}
		break;
	case 2:
		if(by==ly-1)InsertWall(mz,bx,0   ,0,wal,pas);
		       else InsertWall(mz,bx,by+1,0,wal,pas);
		break;
	case 3:
		if(bx==lx-1)InsertWall(mz,0   ,by,1,wal,pas);
		       else InsertWall(mz,bx+1,by,1,wal,pas);
		break;
	}
}

void ClearMaze(MAZEMAP *mz)
{
	int i;
	mz->bl=MAZE_BLOCK_LEN;
	mz->bh=MAZE_BLOCK_HEI;
	mz->lx=MAZE_SIZE_X;
	mz->ly=MAZE_SIZE_Y;
	for(i=0; i<MAZE_SIZE_X*MAZE_SIZE_Y; i++)
	{
		mz->map[i]=0;
	}
}

void SetFloor(MAZEMAP *mz,int bx,int by)
{
	int p;
	p=((mz->lx)*by)+bx;
	mz->map[p] |= 64;
}

void ResetFloor(MAZEMAP *mz,int bx,int by)
{
	int p;
	p=((mz->lx)*by)+bx;
	mz->map[p] &= ~64;
}

void SetCeiling(MAZEMAP *mz,int bx,int by)
{
	int p;
	p=((mz->lx)*by)+bx;
	mz->map[p] |= 128;
}

void ResetCeiling(MAZEMAP *mz,int bx,int by)
{
	int p;
	p=((mz->lx)*by)+bx;
	mz->map[p] &= ~128;
}

void SetNumber(MAZEMAP *mz,int bx,int by,int n)
{
	int p;
	p=(mz->lx)*by+bx;
	mz->map[p] = (mz->map[p] & ~0xff00)+n*256;
}


void ResizeMaze(MAZEMAP *mz,int nx,int ny)
{
	int i,x,y,ox,oy;
	short old[MAZE_SIZE_X_MAX*MAZE_SIZE_Y_MAX];

	ox=mz->lx;
	oy=mz->ly;
	for(i=0; i<ox*oy; i++)
	{
		old[i]=mz->map[i];
	}

	mz->lx =nx;
	mz->ly =ny;
	for(y=0; y<ny; y++)
	{
		for(x=0; x<nx; x++)
		{
			if(x>=ox || y>=oy)
			{
				mz->map[y*nx+x]=0;
			}
			else
			{
				mz->map[y*nx+x]=old[y*ox+x];
			}
		}
	}
}
