/* vputmask.c (emx+gcc) -- Copyright (c) 1987-1994 by Eberhard Mattes */

#include <stdlib.h>
#include <sys/video.h>
#include "video2.h"
#include "video3.h"

#if defined (IF_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#ifdef __GNUC__
#include <alloca.h>
#else
#include <malloc.h>
#endif
#endif

void v_putmask (const char *src, const char *mask, int x, int y, int count)
{
  int i, off;
  char *dst;

  if (_v_mem != NULL)
    {
      off = (y * _v_width + x) * 2;
      dst = _v_mem + off;
      for (i = 0; i < count; ++i)
        {
          if (*mask++)
            {
              dst[0] = src[0];
              dst[1] = src[1];
            }
          dst += 2; src += 2;
        }
    }
  else
    {
#if defined (IF_WIN32)
      IF_WIN32
        {
          int i;
          unsigned short * attr = alloca (count * sizeof(unsigned short));
          unsigned char * chars = alloca (count * sizeof(unsigned char));
          unsigned long r;
          COORD cc;
          int flag, len;
          
          cc.Y = y;
          cc.X = x;

          ReadConsoleOutputAttribute(
              GetStdHandle(STD_OUTPUT_HANDLE),
                        attr, count, cc, &r);
          ReadConsoleOutputCharacter(
              GetStdHandle(STD_OUTPUT_HANDLE),
                        chars, count, cc, &r);

          for (i = 0; i < count; ++i) {
              if (*mask++)
              {
                chars[i] = src[i*2];
                attr[i] = src[i*2+1];
              }
          }

          WriteConsoleOutputAttribute(
            GetStdHandle(STD_OUTPUT_HANDLE),
            attr,count,cc,&r);
          WriteConsoleOutputCharacter(
            GetStdHandle(STD_OUTPUT_HANDLE),
            chars,count,cc,&r);
        }
#endif
#if defined (IF_DOS)
      IF_DOS
        {
          union REGS r;

          for (i = 0; i < count; ++i)
            {
              if (*mask++)
                {
                  r.h.ah = 0x02;
                  r.h.bh = 0;
                  r.h.dl = x + i;
                  r.h.dh = y;
                  _int86 (0x10, &r, &r);
                  r.h.ah = 0x09;
                  r.h.bh = 0;
                  r.h.al = src[0];
                  r.h.bl = src[1];
                  r.x.cx = 1;
                  _int86 (0x10, &r, &r);

                }
              src += 2;
            }
          r.h.ah = 0x02;
          r.h.bh = 0;
          r.h.dl = (unsigned char)_v_x;
          r.h.dh = (unsigned char)_v_y;
          _int86 (0x10, &r, &r);
        }
#endif
    }
}
