/* Welcome2L ANSI display merging code
 * Copyright (c) 2002 Jim Peters <jim@uazu.net>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "ansi.h"
#include "scr.h"
#include "stdlib.h"

//
//	Keep an ANSI screen in memory, and allow merging of images on
//	it.
//

uchar *screen;
int scr_sx, scr_sy;

//
//	Initialise the internal screen to the given size
//

void
scr_init(int sx, int sy) {
  if (screen) free(screen);
  screen= malloc(sx * sy * 2);
  if (!screen) exit(1);
  scr_sx= sx;
  scr_sy= sy;
}

//
//	Draw a given chunk of data to the internal screen at the given
//	position.  Full clipping is performed, so the position
//	coordinates may be negative.  Any '?' character in the data is
//	taken to be a transparent character, and the original data
//	shows through.  The data should start with two bytes giving
//	the width and height of the image.
//

void 
scr_draw(int ox, int oy, uchar *data) {
  int sx= *data++;
  int sy= *data++;
  int xx, yy;
  int x, y;
  uchar *p;

  for (yy= 0; yy<sy; yy++) {
    y= yy + oy;
    if (y < 0 || y >= scr_sy) { 
      data += 2 * sx;
      continue;
    }
    for (xx= 0; xx<sx; xx++) {
      x= xx + ox;
      if (x < 0 || x >= scr_sx || data[0] == '?') {
	data += 2;
	continue;
      }
      p= screen + 2 * (x + scr_sx * y);
      *p++= *data++;
      *p++= *data++;
    }
  }
}

//
//	Dump the screen out to the ANSI routines ready for output
//

void   
scr_dump() {
  int x, y;
  uchar *p= screen;

  for (y= 0; y<scr_sy; y++) {
    if (y) ANSI_do_char('\n');
    for (x= 0; x<scr_sx; x++) {
      ANSI_do_color(p[1]);
      ANSI_do_char(p[0]);
      p += 2;
    }
  }
}

// END //
