/*
 * CGA.C -- A collection of CGA screen manipulation routines, as used
 *          by A2B.
 */

/* INCLUDES */

#include <stdio.h>
#include <alloc.h>
#include <mem.h>
#include <dos.h>

#include "cga.h"




/* GLOBALS */

static long int   sadr[200];	/* screen addresses of each line */




/* FUNCTIONS */

void mode(WORD vmode)
{
 _AH = 0;
 _AL = (UBYTE)vmode;

 geninterrupt(0x10);
}



void cls(void)
{
 register int line, byte;


 for(line=0;line<200;line++)
  for(byte=0;byte<80;byte++)
   *((UBYTE far *)(sadr[line]+byte)) = 0x00;
}



void init_cgfx(UBYTE vmode)
{
 int	i;
 long int tmp;


 for (i = 0; i < 200; i++)
  {
  if (i % 2 == 0)
   tmp = ((i / 2) * 0x50);
  else
   tmp = (((i / 2) * 0x50) + 0x2000);

  sadr[i] = (long int)(0xB8000000L + (long int)tmp);
  }

 mode(vmode);
}



void put_pixel(int x, int y, int color)
{
 UBYTE far *mem_addr, clr[] = { 0x00, 0x55, 0xAA, 0xFF };
 int   mask;


 mem_addr = (UBYTE far *)(sadr[y] + (ULONG)x/4L);

 mask = 0xC0 >> ((x % 4) * 2);

 *mem_addr = (clr[color] & mask) | (*mem_addr & ~mask);
}



void save_pic(const char *name)
{
 FILE *fh;
 UBYTE far *data;
 UWORD dseg, doff;


 data = (UBYTE far *)calloc(16384, 1);

 dseg = FP_SEG(data);
 doff = FP_OFF(data);

 movedata(0xB800, 0x0000, dseg, doff, 16384);

 if((fh=fopen(name,"wb")) != NULL)
  {
  fprintf(fh,"%c%c%c%c%c%c%c",0xFD,0x00,0xB8,0x00,0x00,0x00,0x40);

  fwrite((void *)data, 1, 16384, fh);

  fclose(fh);

  free((void *)data);
  }
 else
  printf("ERROR:  Unable to open %s\n",name);
}



void fload_pic(const char *name)
{
 register int i;
 UBYTE    *s, *tmp, far *pic = (UBYTE far *)MK_FP(0xB800,0x0000);
 FILE     *fh;


 if((fh=fopen(name, "rb")) != NULL)
  {
  tmp = s = (UBYTE *)calloc(16392, 1);

  fseek(fh, 8, SEEK_SET);

  fread(s,1,16377,fh);
  fclose(fh);

  for(i=0;i<16378;i++)
   *pic++ = *tmp++;

  free((void *)s);
  }
 else
  printf("ERROR:  Unable to open %s\n", name);
}
