#include <dos.h>

#include "misc.hpp"
#include "brdsize.hpp"
#include "charui.hpp"

CHARUSERIFACE CharUI;

CHARUSERIFACE::CHARUSERIFACE(void)
  {
    union REGS r;

    // get cursor mode
    r.h.ah = 3;
    r.h.bh = 0;
    int86(0x10, &r, &r);
    cursorMode = r.x.cx;

    // clear screen
    r.h.ah = 0;
    r.h.al = 3;
    int86(0x10, &r, &r);

    // clear cursor
    r.h.ah = 1;
    r.h.ch = 0x20;
    r.h.cl = 0;
    int86(0x10, &r, &r);

    return;
  }

CHARUSERIFACE::~CHARUSERIFACE(void)
  {
    union REGS r;

    // clear screen
    r.h.ah = 0;
    r.h.al = 3;
    int86(0x10, &r, &r);

    // restore cursor mode
    r.h.ah = 1;
    r.x.cx = cursorMode;
    int86(0x10, &r, &r);
    cursorMode = r.x.cx;

    return;
  }

void CHARUSERIFACE::showChar(int row, int col, char c, BOOL inverse)
  {
    union REGS r;

    // position cursor
    r.h.ah = 2;
    r.h.bh = 0;
    r.h.dh = (unsigned char) row;
    r.h.dl = (unsigned char) col;
    int86(0x10, &r, &r);

    // write character 
    r.h.ah = 9;
    r.h.bh = 0;
    r.x.cx = 1;
    r.h.al = (unsigned char) c;
    r.h.bl = (unsigned char) (inverse ? 0x70 : 0x07);
    int86(0x10, &r, &r);

    return;
  }

uint CHARUSERIFACE::readKey(void)
  {
    union REGS r;

    // read a key
    r.h.ah = 0;
    int86(0x16, &r, &r);
    if (r.h.al)
      r.h.ah = 0;
    return(r.x.ax);
  }
