/* wmputs.c (emx+gcc) -- Copyright (c) 1987-2000 by Eberhard Mattes */

#include <string.h>
#include <sys/winmgr.h>
#include "winmgr2.h"

static void _wm_puts1 (wm_handle wh, const char *p, int len)
{
  int max, cnt, i, px, py, mx, my;
  char *mem;

  while (len > 0)
    {
      max = wh->width-wh->x;
      if (len < max)
        cnt = len;
      else
        cnt = max;
      if (cnt > 0)
        {
          px = wh->x+wh->ax;
          py = wh->y+wh->ay;
          i = px+py*wh->bwidth;
          mem = &wh->data[2*i];
          _wm_puts2 (mem, p, cnt, wh->wattr);           /* Copy to memory */
          if (wh->display)            /* Copy from memory to video buffer */
            {
              mx = wh->x+wh->x0;
              my = wh->y+wh->y0;
              if (wh->visible)
                _wm_move2 (mem, my, mx, mx+cnt-1, 1);
              else
                _wm_line2 (&wh->mask[i], mem, my, mx, mx+cnt-1);
            }
          else
            wh->update_req = TRUE;
          if (cnt == max)
            {
              if (wh->wrap)
                {
                  wh->x = 0;
                  ++wh->y;
                  if (wh->y >= wh->height)
                    {
                      --wh->y;
                      wm_scroll (wh, 1);
                    }
                }
              else
                {
                  wh->x = wh->width - 1;
                  break;
                }
            }
          else
            wh->x += cnt;
        }
      len -= cnt;
      p += cnt;
    }
}


void wm_putsn (wm_handle wh, const char *p, int len)
{
  const char *q;
  int n;

  do
    {
      q = memchr (p, '\n', (size_t)len);
      if (q == NULL)
        _wm_puts1 (wh, p, len);
      else
        {
          n = q - p;
          _wm_puts1 (wh, p, n);
          wm_putc (wh, '\n');
          p = q + 1;
          len -= n + 1;
        }
    } while (q != NULL);
}


void wm_puts (wm_handle wh, const char *p)
{
  wm_putsn (wh, p, (int)strlen (p));
  _wm_cursor1 ();
}
