/*                      QBCC Project

This source file is licensed under the GNU Lesser Public Licence which should be 
included with the distribution of this source.

*/

#include <stdio.h>
#include <malloc.h>
#include "allegro.h"
#include "allegro/aintern.h"
#include "GfxLib.h"

#define MAXMEM_SIZE	4096;


int UseBuffer = FALSE;
BITMAP *MyBuffer = NULL;
int ScreenWidth = 320;
int ScreenHeight = 200;

int *IntMemBlock = NULL;				// So POINT can return a pointer
int BlockNum = 0;


///////////////////
// Set Drawing Type
void DrawToBuffer(int *d2b)
{
	UseBuffer = *d2b;
}

///////////////////
// Draw buffer to screen
void DrawBufferToScreen(void)
{
	if(UseBuffer && MyBuffer)
		blit(MyBuffer,screen,0,0,0,0,ScreenWidth,ScreenHeight);
}

///////////////////
// LINE
void LINE(int *x1,int *y1,int *x2,int *y2,int *colour,int *type)
{
	if(*type == LINE_NORMAL)	
		line(UseBuffer ? MyBuffer : screen,*x1,*y1,*x2,*y2,*colour);
	if(*type == LINE_B)
		rect(UseBuffer ? MyBuffer : screen,*x1,*y1,*x2,*y2,*colour);
	if(*type == LINE_BF)
		rectfill(UseBuffer ? MyBuffer : screen,*x1,*y1,*x2,*y2,*colour);
}


///////////////////
// SCREEN
void SCREEN(int *mode)
{
	int AllocateMemBlock = FALSE;

	// Mode 13h only supported so far
	switch(*mode)
	{
		case 13:
			set_color_depth(8);
			set_gfx_mode(GFX_AUTODETECT,320,200,0,0);
			ScreenWidth = 320;
			ScreenHeight = 200;
			MyBuffer = create_bitmap(ScreenWidth,ScreenHeight);
			UseBuffer = FALSE;
			AllocateMemBlock = TRUE;
			break;
		case -1:
			AllocateMemBlock = FALSE;
			UseBuffer = FALSE;
			destroy_bitmap(MyBuffer);
			break;
	}

	if(AllocateMemBlock)
	{
		IntMemBlock = (int *)malloc(sizeof(int) * MAXMEM_SIZE);
		BlockNum = 0;
	}
	else
	{
		BlockNum = MAXMEM_SIZE;
		free(IntMemBlock);
	}
}

///////////////////
// PSET
void PSET_(int *x,int *y,int *colour)
{
	putpixel(UseBuffer ? MyBuffer : screen,*x,*y,*colour);
}

///////////////////
// POINT
int *POINT(int *x,int *y)
{
	int *intptr = IntMemBlock + BlockNum++;
	*intptr = getpixel(UseBuffer ? MyBuffer : screen,*x,*y);

	return intptr;
}

///////////////////
// PAINT
void PAINT(int *x,int *y,int *colour,int *bordercol,int *backgcol)
{
	floodfill(UseBuffer ? MyBuffer : screen,*x,*y,*colour);
}

///////////////////
// CLS
void CLS(void)
{
	clear(UseBuffer ? MyBuffer : screen);
}

///////////////////
// GET
void GET(int *x1,int *y1,int *x2,int *y2,signed short *array)
{
	int temp = 0;
	int x,y;

	array[0] = (signed short)(*x2-*x1);
	array[1] = (signed short)(*y2-*y1);

	temp = 2;

	for (y=*y1;y != *y2 + 1; y++)
		for (x=*x1;x != *x2 + 1; x++)		
			array[temp++] = (signed short)(*POINT(&x, &y));
}

///////////////////
// PUT
void PUT(int *x,int *y,signed short *array,int *type)
{
	int tempx = *x,tempy = *y,height,width,count;
	int tx,ty;

	tx = *x;ty = *y;

	width = array[0];
	height = array[1];
	count=2;

	for(ty=tempy;ty<=tempy+height;ty++)
		for(tx=tempx;tx<=tempx+width;tx++,count++)
			PSET_(&tx, &ty, array + count);
}