/*
 * Graphics primitives for a chess board.
 * We measure from row 0 to row 7 down, GNUChess the other way round.
 * The macro 'tognurow' converts.
 */
#include <exec/types.h>
#include <intuition/intuition.h>
#include <proto/graphics.h>
#include "display.h"
#include "draw.h"
#include "pieces.h"

extern struct RastPort *rp;

#define odd(n) (n%2)
#define even(n) (odd(n) ? 0 : 1)
#define tognurow(row) ((row) = 7-(row))

/* prototypes for static functions */
static UWORD SquareColor(UWORD row, UWORD col);

static UWORD
SquareColor(UWORD row, UWORD col)
{
	if (even(row) ^ odd(col))
		return WHITESQUARE_PEN;
	else
		return BLACKSQUARE_PEN;
}

void
AmiDrawCoords(int off, int reverse)
{
	/* NB: font dependent (needs topaz 8) */
	char s[2];
	int i, r, c;

	s[0] = ' ';	/* for 'off' */
	s[1] = '\0';

	SetAPen(rp, OUTLINE_PEN);
	if (off)
		SetDrMd(rp, JAM2);

	for (i = 0; i < 8; i++)
	{
	    /* a b c d e f g h */
		c = reverse ? 7-i : i;
		if (!off)
			s[0] = i + 'a';
		Move(rp, SQUARE_LHS(0,c)+1+16, SQUARE_BOTTOM(7,0)+9);
		Text(rp, s, 1);

	    /* 1 2 3 4 5 6 7 8 */
		r = reverse ? i : 7-i;
		if (!off)
			s[0] = i + '1';
		Move(rp, 1, SQUARE_BOTTOM(r,0)-1-6);
		Text(rp, s, 1);
	}

	SetDrMd(rp, JAM1);
}

void
AmiDrawGrid()
{
	UWORD i;

	Move(rp, LEFT_OFFSET, TOP_OFFSET);

	SetAPen(rp, OUTLINE_PEN);
	for (i = 0; i < 9; i++)
	{
         /*=*/	Move(rp, LEFT_OFFSET, TOP_OFFSET+SQUARE_HEIGHT*i);
		Draw(rp, LEFT_OFFSET+SQUARE_WIDTH*8, TOP_OFFSET+SQUARE_HEIGHT*i);

         /*||*/	Move(rp, LEFT_OFFSET+SQUARE_WIDTH*i, TOP_OFFSET);
		Draw(rp, LEFT_OFFSET+SQUARE_WIDTH*i, TOP_OFFSET+SQUARE_HEIGHT*8);
	}
}

void
AmiToggleSquare(UWORD row, UWORD col)
{
	tognurow(row);
	SetDrMd(rp, COMPLEMENT);
	SetAPen(rp, ~2);
	RectFill(rp, 	SQUARE_LHS(row,col), SQUARE_TOP(row,col),
			SQUARE_RHS(row,col), SQUARE_BOTTOM(row,col));
	SetDrMd(rp, JAM1);
}

void
AmiFlashSquare(UWORD row, UWORD col)
{
	int i;
	for (i = 0; i < 6; i++)
	{
		AmiToggleSquare(row, col);
		if (i != 5)
			Delay(2);
	}
	SetDrMd(rp, JAM1);
}

void
AmiDrawSquare(UWORD row, UWORD col)
{
	tognurow(row);
	SetAPen(rp, SquareColor(row,col));
	RectFill(rp, 	SQUARE_LHS(row,col), SQUARE_TOP(row,col),
			SQUARE_RHS(row,col), SQUARE_BOTTOM(row,col));
}

void
AmiDrawPiece(UWORD piece, UWORD pccolor, UWORD row, UWORD col)
{
	UWORD sqcolor;

	tognurow(row);
	if (SquareColor(row, col) == WHITESQUARE_PEN)
		sqcolor = WHITE;
	else
		sqcolor = BLACK;

	DrawImage(rp, 	pieceimage[sqcolor][pccolor][piece],
			SQUARE_LHS(row,col), SQUARE_TOP(row,col));
}
