/* vinit.c (emx+gcc) -- Copyright (c) 1987-1995 by Eberhard Mattes */

#include <stdlib.h>
#include <sys/video.h>
#include "video2.h"
#include "video3.h"
#if defined (__EMX__)
#include <sys/hw.h>
#include <os2thunk.h>
#else
extern void _scrsize (int *dst);
#endif

#if defined (IF_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

int _v_width = 0;
int _v_height = 0;
int _v_x = 0;
int _v_y = 0;
int _v_attr = 0x07;
char *_v_mem = NULL;

static void _v_getxy (int *x, int *y)
{
#if defined (IF_WIN32)
  IF_WIN32
    {
      CONSOLE_SCREEN_BUFFER_INFO scbi;

      GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &scbi);
      *x = scbi.dwCursorPosition.X;
      *y = scbi.dwCursorPosition.Y;
    }
#endif
#if defined (IF_DOS)
  IF_DOS
    {
      union REGS r;

      r.h.ah = 0x03;
      r.h.bh = 0x00;
      _int86 (0x10, &r, &r);
      *x = r.h.dl; *y = r.h.dh;
    }
#endif
}

#ifdef __RSXNT__
int _v_rsxnt = 0;
#endif

int v_init (void)
{
  int two[2];

#ifdef __RSXNT__
#define RUN_RSX 0x1000
  if (_emx_env & RUN_RSX)
    if ((_emx_rev >> 16) == 2)
      _v_rsxnt = 1;
#endif

  _scrsize (two);
  _v_width = two[0];
  _v_height = two[1];
  _v_getxy (&_v_x, &_v_y);
  _v_mem = NULL;

#if defined (IF_WIN32)
  IF_WIN32
    {
      CONSOLE_SCREEN_BUFFER_INFO scbi;

      GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &scbi);
      _v_attr = scbi.wAttributes;

      /* or set;
      SetConsoleTextAttribute(0x07);
      */
    }
#endif
#if defined (IF_DOS)
  IF_DOS
    {
      unsigned addr, end_addr;
      union REGS r;

      r.h.ah = 0x0f;
      _int86 (0x10, &r, &r);
      if (r.h.al == 7 || r.h.al < 4)
	{
	  _int86 (0x11, &r, &r);
	  if ((r.h.al & 0x30) == 0x30)
	    addr = 0xb0000;
	  else
	    addr = 0xb8000;
	  end_addr = (addr + _v_height * _v_width * 2 - 1) | 0xfff;
	  _v_mem = _memaccess (addr, end_addr, 1);
	}
    }
#endif
  return 1;
}
