#include "gl.h"
#include "gldevice.h"
#include "defines.h"
#include "struct.h"
#include "protos.h"

char *vgets(char *banner,char *prompt,int numchars,unsigned int drawcolor)
{
  long cdmode = 0;
  int done = 0;
  int blink=0;
  long rval;
  short val;
  static char buffer[256];
  static int inputfont = -1;
  int index=0;

  cdmode = getdrawmode();
  clear_normal();
  buffer[0] = 0;
  if(inputfont < 0) inputfont = openvecfont(40,25,0.7);

  qdevice(KEYBD);
  qdevice(ESCKEY);
  qdevice(RETKEY);
  qdevice(BACKSPACEKEY);
  qdevice(DELKEY);
  qenter(REDRAW,1);
  while(!done) {
    switch(rval = qread(&val)) {
      case RETKEY:
      case ESCKEY:
	if(!val) done = 1;
	break;
      case WINQUIT:
      case WINSHUT:
	done = 1;
	break;
      case REDRAW:
      case INPUTCHANGE:
	reshapeviewport();
	update_overlay(OLAY_CLEAR);
	drawmode(PUPDRAW);
	mapcolor(1,(drawcolor&0xff),(drawcolor>>8)&0xff,(drawcolor>>16)&0xff);
	gflush();
      case BACKSPACEKEY:
      case DELKEY:
      case KEYBD:

	color(0); /* Erase any old text */
	vmov2(inputfont,0.0,0.0);
	buffer[index] = '_';
	buffer[index+1] = 0;
	vcprint(inputfont,buffer);
	buffer[index] = 0;

	/* Update the string */

	if((rval == BACKSPACEKEY || rval == DELKEY) && val)
	  buffer[index = MAX(0,index-1)] = 0;

	if(rval == KEYBD) switch(val) {

	  default:
	    val = tolower(val);
	    if(isprint(val) && index<numchars) {
	      buffer[index++] = val;
	      buffer[index] = 0;
	    } else if(val == DELKEY) {
	      buffer[--index] = 0;
	    }
	    break;
	} else if(rval == REDRAW || rval == INPUTCHANGE) {
		 /* Redraw the screen */
		 /* This is done at least one 'cause qenter REDRAW */
	  color(0);
	  clear();
	  color(1);
	  vmov2(inputfont,0,0.5);
	  vcprint(inputfont,banner);
	  vmovrel2(inputfont,0,1);
	  vcprint(inputfont,prompt);
	  vmov2(inputfont,0.0,0.0);
	}
	color(1); /* Draw the new text */
	vmov2(inputfont,0.0,0.0);
	buffer[index] = '_'; /* Underbar cursor */
	buffer[index+1] = 0;
	vcprint(inputfont,buffer);
	buffer[index] = 0;
	break;

      default:
	printf("Unknown return val %d from input routine\n",rval);
    }
  }
  drawmode(cdmode);

  unqdevice(KEYBD);
  unqdevice(RETKEY);
/*   unqdevice(ESCKEY); */
  unqdevice(BACKSPACEKEY);
  unqdevice(DELKEY);

  return buffer;
}
