/**********************************************************************/
#include <exec/types.h>
#include <exec/nodes.h>
#include <exec/lists.h>
#include <exec/memory.h>
#include "devices/printer.h"
#include "devices/prtbase.h"
#include <functions.h>

extern struct PrinterData *PD;

/* for the Tektronix 4695 */
long Render(ct,x,y,status)
register ULONG ct;	/* was UBYTE for Lattice compiler */
register ULONG x,y;	/* was UWORD for Lattice compiler */
ULONG status;	/* was UBYTE for Lattice compiler */
{
	static UWORD ROWSIZE;
	static UWORD COLORSIZE;
	static UWORD BUFSIZE;
	static UWORD colors[4];
	static BYTE huns,tens,ones;
	static UWORD bufptr;
	register struct PrinterData *pp = PD;
	register UBYTE *ptr;
	UWORD i;
	BYTE err; 

	switch((UBYTE)status) {

		case 0:	/* alloc memory for printer buffer (uses dbl buf) */
			ROWSIZE = ((UWORD)x+7)/8;
			huns = ROWSIZE/100;
			tens = (ROWSIZE - huns*100)/10;
			ones = (ROWSIZE - huns*100 - tens*10);
			ROWSIZE += 6;
			COLORSIZE = ROWSIZE*4;
			BUFSIZE = COLORSIZE*4+2;
			colors[0] = 6;
			colors[1] = COLORSIZE*2+6;
			colors[2] = COLORSIZE+6;
			colors[3] = COLORSIZE*3+6;
			pp->pd_PrintBuf = (UBYTE *)
				AllocMem((long)BUFSIZE*2,(long)MEMF_PUBLIC);
			if(err = (pp->pd_PrintBuf==0)) 
				return(err);
			if(err = (*(pp->pd_PWrite))("\0334",2L)) 
				return(err);
			if(err = PWait(1L,0L)) 
				return(err);
			bufptr = 0;
			return(0);
			break;

		case 1:	/* put pixel in buffer (called a max of 16384 
			 * times per print cycle */
			i = bufptr+(UWORD)x/8+((UWORD)y&3)*ROWSIZE+colors[(UBYTE)ct];
			pp->pd_PrintBuf[i] |= (1 << (7-((UWORD)x&7)));
			return(0);
			break;

		case 2: /* dump buffer to printer */
			if (err = (*(pp->pd_PWrite))(&pp->pd_PrintBuf[bufptr],
								(long)BUFSIZE))
				return (err);
			bufptr = BUFSIZE - bufptr;
			return(0);
			break;

		case 3: /* clear and init buffer */
			ptr = &pp->pd_PrintBuf[bufptr];
			i = BUFSIZE;
			while(i--) 
				*ptr++ = 0;
			for (i = 0; i < 16; i++) {
				ptr = &pp->pd_PrintBuf[bufptr+i*ROWSIZE];
				*ptr++ = 27;
				*ptr++ = 'I';
				*ptr++ = i+'0';
				*ptr++ = huns+'0';
				*ptr++ = tens+'0';
				*ptr++ = ones+'0';
			}
			pp->pd_PrintBuf[bufptr+BUFSIZE-2] = 27;
			pp->pd_PrintBuf[bufptr+BUFSIZE-1] = 'A';
			return(0);
			break;

		case 4:	/* free the print buffer memory */
			err = (*(pp->pd_PBothReady))();
			FreeMem(pp->pd_PrintBuf,(long)BUFSIZE*2L);
			return(err);
			break;

		default:
			return(0);
	}
}
