/*	VGR.c    -  Routines that access the BIOS or are otherwise
	            related to video, but not board specific.
*/


#define ALLOCATE
#include "lib.h"
#include "vgr.h"


/*	VGR_GET_BOARD

	Partly by Dan Laurence, 
	from MicroEMACS, IBMPC.C, page 5 
	Hercules test by Larry Fogg, 
	from MicroC, jan-feb '88, page 26.

	It's difficult for me to test this...
	My ATI EGA Wonder is basically either a
	HERC or EGA board... Besides that, there's
	no perfect algorithm available for this 
	problem...
*/

int vgr_get_board()
{
	int i;
	REGS r;

	/* Check for MONO */
	sysint( 0x11, &r, &r );
	if ( ( (r.ax >> 4) & 0x03 ) == 0x03 )
	{  for ( i=0; i < 0x1000; i++ )
	      if ( inportb( 0x3ba ) & 0x80 )
	         return TYPE_HERC;
	   return TYPE_MDA;
	};

	/* Check for EGA
	*/
	r.ax = 0x1200;
	r.bx = 0xff10;
	sysint( 0x10, &r, &r );
	if ( !(r.bx & (~0x0103)) )    /* might be EGA...   */
	   return TYPE_EGA;
	else return TYPE_CGA; /* should be CGA, but...  */
}


int vgr_mode( mode )
unsigned char mode;
{
	REGS r;

	r.ax = mode;
	sysint( 0x10, &r, &r );

	return OK;
}


/*	adapted from jan/feb microcornucopia, page 85
	by Gary Entsminger. Gary's ref: Bresenham's algorithm,
	from Advanced Turbo C by Herbert Schildt.
*/

void vgr_line( x1, y1, x2, y2, color )
int x1, x2, y1, y2, color;
{
	int t, distance, xerr, yerr, dx, dy, ix, iy;

	ix = (dx = x2-x1) < 0 ? (dx = -dx, -1) : !!dx;
	iy = (dy = y2-y1) < 0 ? (dy = -dy, -1) : !!dy;

	distance = dx > dy ? dx : dy;

	xerr = yerr = 0;
	for ( t = -2; t < distance; t++ )
	{  VGR_SET( x1, y1, color );

	   xerr += dx;
	   yerr += dy;

	   if ( xerr > distance )
	   {  xerr -= distance;
	      x1   += ix;
	   };

	   if ( yerr > distance )
	   {  yerr -= distance;
	      y1   += iy;
	   };
	};
}


void vgr_rectangle( x1, y1, x2, y2, color )
int x1, x2, y1, y2, color;
{
	vgr_line( x1, y1, x1, y2, color );
	vgr_line( x1, y2, x2, y2, color );
	vgr_line( x2, y2, x2, y1, color );
	vgr_line( x2, y1, x1, y1, color );
}


void vgr_point( x2, y2, color )
int x2, y2, color;
{
	static int x1=0, y1=0;

	if ( color != -1 )
	   vgr_line( x1, y1, x2, y2, color );

	x1 = x2;
	y1 = y2;
	return;
}

