#include <stdio.h>
#include <concorde.h>
#include <ysmaze2.h>


int MazeWall(MAZEMAP *mz,int bx,int by,int dir)
{
	switch(dir)
	{
	default:
		return -1;
	case 0:
		return (mz->map[by*(mz->lx)+bx]    ) & 3;
	case 1:
		return (mz->map[by*(mz->lx)+bx] / 4) & 3;
	case 2:
		if((++by)==(mz->ly))by=0;
		return (mz->map[by*(mz->lx)+bx]    ) & 3;
	case 3:
		if((++bx)==(mz->lx))bx=0;
		return (mz->map[by*(mz->lx)+bx] / 4) & 3;
	}
}



int MazePass(MAZEMAP *mz,int bx,int by,int dir)
{
	int p;
	int lx,ly;

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

	switch(dir)
	{
	default:
		return -1;
	case 2:
		if(by==ly-1)return MazePass(mz,bx,0   ,0);
		       else return MazePass(mz,bx,by+1,0);
	case 3:
		if(bx==lx-1)return MazePass(mz,0   ,by,1);
		       else return MazePass(mz,bx+1,by,1);
	case 0:
		return (mz->map[p] / 16) & 1;
	case 1:
		return (mz->map[p] / 32) & 1;
	}
}

void MazeSetWall(MAZEMAP *mz,int bx,int by,int sid,int wal,int pas)
{
	int p,block;
	int lx,ly;

	wal &= 3;
	pas &= 1;
	lx=mz->lx;
	ly=mz->ly;

	while(bx<  0)bx+=lx;
	while(bx>=lx)bx-=lx;
	while(by<  0)by+=ly;
	while(by>=ly)by-=ly;
	p =by*(mz->lx) + bx;

	switch(sid)
	{
	case 2:
		if(by==ly-1)MazeSetWall(mz,bx,0   ,0,wal,pas);
		       else MazeSetWall(mz,bx,by+1,0,wal,pas);
		break;
	case 3:
		if(bx==lx-1)MazeSetWall(mz,0   ,by,1,wal,pas);
		       else MazeSetWall(mz,bx+1,by,1,wal,pas);
		break;
	case 0:
		block=mz->map[p];
		block &= ~0x13;
		block |= ((pas<<4) + (wal<<0));
		mz->map[p] = block;
		break;
	case 1:
		block=mz->map[p];
		block &= ~0x2c;
		block |= ((pas<<5) + (wal<<2));
		mz->map[p] = block;
		break;
	}
}
