#include <exec/types.h>
#include <exec/memory.h>

#include <intuition/intuition.h>
#include <intuition/screens.h>

#include <graphics/gfx.h>
#include <dos/dos.h>

#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#include <clib/intuition_protos.h>
#include <clib/graphics_protos.h>
#include <clib/alib_protos.h>

#include "Puzzle.h"
#include "/defs.h"
#include "/utility.h"

struct pPrefObject {
	ULONG Horiz, Vert;
};

extern	struct	pPrefObject	nP;
extern		ULONG	Mode, Depth;
extern		UBYTE	*prefData;

#define UP	0
#define DOWN	1
#define LEFT	2
#define RIGHT	3

WORD getNewDir( WORD x, WORD y, WORD xmax, WORD ymax, WORD olddir )
{
	WORD dir, a1[] = { UP, DOWN, LEFT, RIGHT }, a2[] = { DOWN, UP, RIGHT, LEFT };

	dir = RangeRand(4 );
	if( !x && dir == RIGHT ) dir = LEFT;
	if( !y && dir == DOWN ) dir = UP;
	if( x > xmax && dir == LEFT ) dir = RIGHT;
	if( y > ymax && dir == UP ) dir = DOWN;
	while( a1[dir] == a2[olddir] ) {
		dir = RangeRand( 4 );
		if( !x && dir == RIGHT ) dir = LEFT;
		if( !y && dir == DOWN ) dir = UP;
		if( x > xmax && dir == LEFT ) dir = RIGHT;
		if( y > ymax && dir == UP ) dir = DOWN;
	}
	return( dir );
}

VOID blank( VOID )
{
	struct	pPrefObject	*pP;
	struct	Screen		*PScr;
	struct	RastPort	*Rast;
		Point		c = { 0, 0 }, n = { 0, 0 };
		WORD		i, dir = UP, xmax, ymax, wid, hei;

	if( PuzzleWnd ) pP = &nP;
	else pP = ( struct pPrefObject * )prefData;

	if( PScr = cloneTopScreen() ) {

		Rast = &( PScr->RastPort );
		wid = PScr->Width / pP->Horiz;
		hei = PScr->Height / pP->Vert;

		SetAPen( Rast, 2 );
		for( i = 0; i < PScr->Width; i += wid ) {
			Move( Rast, i, 0 );
			Draw( Rast, i, PScr->Height-1 );
		}
		for( i = 0; i < PScr->Height; i += hei ) {
			Move( Rast, 0, i );
			Draw( Rast, PScr->Width-1, i );
		}

		SetAPen( Rast, 1 );
		for( i = wid-1; i < PScr->Width; i += wid ) {
			Move( Rast, i, 0 );
			Draw( Rast, i, PScr->Height-1 );
		}
		for( i = hei-1; i < PScr->Height; i += hei ) {
			Move( Rast, 0, i );
			Draw( Rast, PScr->Width-1, i );
		}

		xmax = PScr->Width - 2*wid;
		ymax = PScr->Height - 2*hei;

		SetAPen( Rast, 3 );

		BlankMousePointer();

		while(!( SetSignal( 0L, 0L ) & SIGBREAKF_CTRL_C )) {
			switch( dir = getNewDir( c.x, c.y, xmax, ymax, dir )) {
			case UP: n.y += hei; break;
			case DOWN: n.y -= hei; break;
			case LEFT: n.x += wid; break;
			case RIGHT: n.x -= wid; break;
			}
			BltBitMap( Rast->BitMap, n.x+1, n.y+1, Rast->BitMap, c.x+1, c.y+1, wid-2, hei-2, 0xC0, 0xFF, NULL );
			RectFill( Rast, n.x+1, n.y+1, n.x + wid - 2, n.y + hei - 2 );
			c = n;
			WaitTOF();
		}
		SetSignal( 0L, SIGBREAKF_CTRL_C );

		UnblankMousePointer();
		closeTopScreen( PScr );
	}
}
