/*
	getstr.C

	Copyright (C) 1993, Geoff Friesen B.Sc.
	All rights reserved.
*/

#define	INCL_GETSTR

#ifndef INCL_KFETCH
#include "kfetch.C"
#endif

#ifndef INCL_STRLEN
#include "strlen.C"
#endif

#ifndef INCL_VCPUTS
#include "vcputs.C"
#endif

#ifndef INCL_VGETMODE
#include "vgetmode.C"
#endif

#ifndef INCL_VGETSHAPE
#include "vgetshap.C"
#endif

#ifndef INCL_VGOTOXY
#include "vgotoxy.C"
#endif

#ifndef INCL_VPUTCH
#include "vputch.C"
#endif

#ifndef INCL_VSCREEN
#include "vscreen.C"
#endif

#ifndef INCL_VSETSHAPE
#include "vsetshap.C"
#endif

#ifndef INCL_VWHEREX
#include "vwherex.C"
#endif

#ifndef INCL_VWHEREY
#include "vwherey.C"
#endif

int getstr (char *buffer, unsigned char maxlen)
{
   char cell [2];
   unsigned char length;
   int curx, i, key, oldshape, oldx, oldy;

   if (!maxlen)
       return ESC;

   length = (unsigned char) strlen (buffer);

   if (length > maxlen)
       buffer [length = maxlen] = '\0';

   oldx = v_wherex ();
   oldy = v_wherey ();

   oldshape = v_getshape ();
   v_setshape ((v_getmode () == MONO) ? 0x0c0d: 0x0607);

   v_cputs (buffer);
   curx = v_wherex ();
   v_putch (' ', maxlen+1-length);
   v_gotoxy (curx, oldy);

   do
   {
      if ((key = k_fetch ()) > 255)
	  continue;

      if (key == CR)
      {
	  for (i = oldx; i < curx; i++)
	  {
	       v_screen (SCREEN_SAVE, i, oldy, 1, 1, cell);
	       buffer [i-oldx] = cell [0];
	  }
	  buffer [i-oldx] = '\0';
	  break;
      }

      if (key == ESC)
	  break;

      if (key == BS)
      {
	  if (curx == oldx)
	      continue;

	  v_gotoxy (curx-1, oldy);
	  v_putch (' ', 1);
	  v_gotoxy (--curx, oldy);
	  length--;
	  continue;
      }

      if (key < ' ' || key > '~' || length == maxlen)
	  continue;

      v_putch (key, 1);
      curx++;
      length++;
   }
   while (1);

   v_setshape (oldshape);
   v_gotoxy (oldx, oldy);

   return key;
}