/* conio.c: Console I/O routines for Palmos/Pilot
 * (c) 1995, 1997 Dionne & Associates
 * (c) 1995 DKG Technologies
 *
 * This code is free software, under the LGPL v2
 */

#include <stdio.h>
#include <Common.h>
#include <System/SysAll.h>
#include <UI/UIAll.h>

#define XB 3
#define YB 16
#define XE 157
#define YE 157
#define YINC 11

#define XMAX 32
#define YMAX 14

static char fb[XMAX * YMAX];

static int xc;
static int yc;
static int xpos = XB;
static int ypos = YB;

static inline int DRAWLN(int LN) 
{
  FntSetFont(stdFont);
  WinDrawChars(&fb[LN * XMAX], StrLen(&fb[LN * XMAX]), XB, YB + YINC*(LN));
  return 0;
}

static void scroll()
{
  int i;
  RectangleType r = { XB, YB, XE - XB, YE - YB };
  RectangleType v;

  WinScrollRectangle(&r, up, YINC, &v);
  WinEraseRectangle(&v, 0);
}

#define MaxPrev 60
static char prev[MaxPrev];

int putchar (unsigned int buf)
{
  char c;
  int cxwidth;			/* character x width */
  static int lastwidth = 0;	/* index for width of previous character */

  c = (char)buf;

  if (c == 8) {			/* backspace */
    if (lastwidth != 0) {
      RectangleType r = { xpos - prev[lastwidth - 1],
			    ypos, prev[lastwidth - 1], YINC };
      WinEraseRectangle(&r, 0);
      xpos -= prev[lastwidth - 1];
      lastwidth--;
    }
    return 0;
  }

  if (c == '\r') {
    xpos = XB;
    lastwidth = 0;
    return 0;
  }

  if (c == ' ') {		/* special - make spaces wider */
    cxwidth = 4;
  } else {
    cxwidth = FntCharWidth(c);
  }
				/* check for end of line */
  if (c == '\n' || (xpos + cxwidth > XE)) {
    xpos = XB;
    ypos += YINC;
    lastwidth = 0;
  }
				/* check for y scroll */
  if (ypos + YINC > YE) {
    scroll();
    ypos -= YINC;
  }
  if (c != '\n') {	/* render the char */
    WinDrawChars(&c, 1, xpos, ypos);
    xpos += cxwidth;
  }
  if (lastwidth < MaxPrev) {
    prev[lastwidth] = cxwidth;
    lastwidth++;
  }
  
  return 0;
}

int puts (unsigned char *string)
{
  int i;

  for (i=0;i<StrLen(string);i++) {
    putchar(string[i]);
  }
  putchar('\n');
  return 0;
}
