/* input.c -- routines to gather input for the monitor
 * copyright (c) 1984  American Information Systems Corporation
 *  Dock Williams
 *  October, 1984
 *
 */

#include "monitor.h"
#include "ascii.h"
#include "vctype.h"



    char
getinput(inpbuf,bufsiz,oflag)
    register char *inpbuf;
    int bufsiz,oflag;
/*
 * read input line from console 
 * inpbuf is an allocated buffer, bufsiz is its size and oflag
 * signifies whether this is a open or command line input fetch
 */
{
    register int i;
    register char c;

    for (i=0; i<bufsiz; i++)
	inpbuf[i] = '\0';		/* clear buffer */

    for (i=0; i<=bufsiz; i++) {

#ifdef AUTOP
	if ((cflags & CF_AUTOP) && (*autoptr != '\0'))
	    /* read input characters from buffer */
	    c = *autoptr++;
	else
#endif
	    /* read input characters from terminal */
	    c = INCHR();

	c = tolower(c);		/* map upper to lower case */
	inpbuf[i] =  c;		/* store in buffer */

	switch( c ) {
	case RUBOUT:
	case '\b':
	    if(i-->0) {
		i--;
		printf("\b \b");
	    }
	    break;
	case ESC:
	    OUTCHR('\n');
	    return('\0');
	case '$':		/* change output base */
	case '\`':		/* open byte */
	case '\\':		/* open word */
	case '/':		/* open double */
	    OUTCHR(c);
	    inpbuf[i] = '\0';
	    return(c);
	case '=':
	    OUTCHR(c);
	    if(oflag) break;
	    else {
		inpbuf[i] = '\0';
	    	return(c);
	    }
	case CR:
	case LF:
	    if(oflag) {
		inpbuf[i] = '\0';
		return(c);
	    } else {
		OUTCHR('\n');
		if (i>=1) {
		    lastcmd = inpbuf [i-1];
		    if(inpbuf[i-2] != ' ' && inpbuf[i-2] != '\t') {
			inpbuf[i+1] = inpbuf[i];
			inpbuf[i] = inpbuf[i-1];
			inpbuf[i-1] = ' ';
		    }
		}
		strncpy(lastinp,inpbuf,MAXINP);
		return(i>=1 ? lastcmd : '\0');
	    }
	case '!':
	    OUTCHR(c);
	    if (i>=1 || oflag) break;
	    else {
		for (i=0;i<MAXINP;i++) {
		    if (lastinp[i]) OUTCHR(lastinp[i]);
		    inpbuf[i] = lastinp[i];
		}
		OUTCHR('\n');
		return(lastcmd);
	    }
	case '@':
	case '+':
	case '-':
	case '^':
	    OUTCHR(c);
	    if(oflag){
		inpbuf[i] = '\0';
		return(c);
	    }
	    break;
	case ',':
	case '<':
	    OUTCHR(c);
	    if(!oflag) {
		return(c);
	    }
	    break;
	case CTRL_V:
	    printf("^V");
	    prtsee(inpbuf[i] = INCHR());
	    break;
	default:
	    OUTCHR(c);
	    break;
	}
    }
    printf("input overflow\n");
}



mkargv(s,argv)
    register char *s;
    register char *argv[];
/*
 * find the number of arguments for a debugger command
 */
{
    register int cnt,i;
    register int flag;

    cnt = 0;
    flag = 1;
    for (i=0; ; i++) {
	switch (s[i]) {
	case '\t':
	case ' ':
	    if(!flag) {
		s[i] = '\0';
		flag++;
	    }
	    break;
	case '\n':
	case '\r':
	case '\0':
	    return(cnt);
	default:
	    if(flag) {
		argv[cnt] = &(s[i]);
		cnt++;
		flag = 0;
	    }
	    break;
	}
    } 
}

