/*
 * |-----------------------------------------------------------|
 * | Copyright (c) 1990 MIPS Computer Systems, Inc.            |
 * | All Rights Reserved                                       |
 * |-----------------------------------------------------------|
 * |          Restricted Rights Legend                         |
 * | Use, duplication, or disclosure by the Government is      |
 * | subject to restrictions as set forth in                   |
 * | subparagraph (c)(1)(ii) of the Rights in Technical        |
 * | Data and Computer Software Clause of DFARS 52.227-7013.   |
 * |         MIPS Computer Systems, Inc.                       |
 * |         928 Arques Avenue                                 |
 * |         Sunnyvale, CA 94086                               |
 * |-----------------------------------------------------------|
 */
#ident	"$Header: doscan.c,v 1.2.2.1 92/06/24 14:10:28 marker Exp $"

/*	Copyright (c) 1984 AT&T	*/
/*	  All Rights Reserved  	*/

/*	THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T	*/
/*	The copyright notice above does not evidence any   	*/
/*	actual or intended publication of such source code.	*/

/* This module is modified for MNLS on Sep.03.86 */

#ident	"@(#)libc-port:stdio/doscan.c	2.18"
/*LINTLIBRARY*/

#include <stdio.h>
#include <ctype.h>
#include <varargs.h>
#include <values.h>
#include <errno.h>
#include "lldefs.h"

#define BITS_PER_LONGLONG 64
#define LONGLONG_CHAR 'm'	/* dummy character to mark 'll' */

#define NCHARS	(1 << BITSPERBYTE)
#define locgetc()	(chcount+=1,getc(iop))
#define locungetc(x)	(chcount-=1,ungetc(x,iop))

/*	start for MNLS by UNIX Pacific on Sep.03.86	*/
#include <widec.h>
#include "pcode.h"
extern int _cswidth[];
/*	end for MNLS	*/

extern double atof();
extern char *memset();
static int chcount,flag_eof;

int
_doscan(iop, fmt, va_alist)
register FILE *iop;
register unsigned char *fmt;
va_list va_alist;
{
	extern unsigned char *setup();
	char tab[NCHARS];
	register int ch;
	int nmatch = 0, len, inchar, stow, size;

	chcount=0; flag_eof=0;

	/*******************************************************
	 * Main loop: reads format to determine a pattern,
	 *		and then goes to read input stream
	 *		in attempt to match the pattern.
	 *******************************************************/
	for ( ; ; ) 
	{
		if ( (ch = *fmt++) == '\0')
			return(nmatch); /* end of format */
		if (isspace(ch)) 
		{
		  	if (!flag_eof) 
			{
			   while (isspace(inchar = locgetc()))
	 		        ;
			   if (locungetc(inchar) == EOF)
				flag_eof = 1;
		        }
		  continue;
                }
		if (ch != '%' || (ch = *fmt++) == '%') 
                {
			if ( (inchar = locgetc()) == ch )
				continue;
			if (locungetc(inchar) != EOF)
				return(nmatch); /* failed to match input */
			break;
		}
		if (ch == '*') 
		{
			stow = 0;
			ch = *fmt++;
		}
		else
			stow = 1;

		for (len = 0; isdigit(ch); ch = *fmt++)
			len = len * 10 + ch - '0';
		if (len == 0)
			len = MAXINT;
/*	start for MNLS by UNIX Pacific on Sep.03.86	*/
/*		if ((size = ch) == 'l' || (size == 'h'))*/
		if ((size = ch) == 'l' || (size == 'h') || (size == 'w'))
/*	end for MNLS	*/
			ch = *fmt++;
		if (size == 'l' && ch == 'l') {
			/* is long long */
			size = LONGLONG_CHAR;
			ch = *fmt++;
		}
		if (ch == '\0' ||
		    ch == '[' && (fmt = setup(fmt, tab)) == NULL)
			return(EOF); /* unexpected end of format */
		if (isupper(ch))  /* no longer documented */
		{
			size = 'l';
			ch = _tolower(ch);
		}
		if (ch!= 'n' && !flag_eof)
		  if (ch != 'c' && ch != '[') 
		  {
			while (isspace(inchar = locgetc()))
				;
			if(locungetc(inchar) == EOF )
				break;
		  }
		switch(ch)
		{
		 case 'c':
		 case 's':
/*	start for MNLS by UNIX Pacific on Sep.03.86	*/
			  if (size == 'w') {
				size = wstring(stow,ch,len,iop,&va_alist);
				break;
			  }
/*	end for MNLS	*/
		 case '[':
			  size = string(stow,ch,len,tab,iop,&va_alist);
			  break;
                 case 'n':
			  if (size == 'h')
				*va_arg(va_alist, short *) = (short) chcount;
		          else if (size == 'l')
				*va_arg(va_alist, long *) = (long) chcount;
			  else
			  	*va_arg(va_alist, int *) = (int) chcount;
			  continue;
		 case 'i':
                 default:
			 size = number(stow, ch, len, size, iop, &va_alist);
			 break;
                 }
		   if (size) 
		          nmatch += stow;   
                   else return ((flag_eof && !nmatch) ? EOF : nmatch);
                continue;
	}
	return (nmatch != 0 ? nmatch : EOF); /* end of input */
}

/***************************************************************
 * Functions to read the input stream in an attempt to match incoming
 * data to the current pattern from the main loop of _doscan().
 ***************************************************************/
static int
number(stow, type, len, size, iop, listp)
int stow, type, len, size;
register FILE *iop;
va_list *listp;
{
	char numbuf[64], inchar, lookahead;
	register char *np = numbuf;
	register int c, base;
	int digitseen = 0, dotseen = 0, expseen = 0, floater = 0, negflg = 0;
	long lcval = 0;
	llvalue llcval, hibitll;
	SET_LL(llcval, 0);
	switch(type) 
	{
	case 'e':
	case 'f':
	case 'g':
		floater++;
	case 'd':
	case 'u':
        case 'i':
		base = 10;
		break;
	case 'o':
		base = 8;
		break;
	case 'x':
		base = 16;
		break;
	default:
		return(0); /* unrecognized conversion character */
	}
	switch(c = locgetc()) 
	{
	case '-':
		negflg++;
	case '+': /* fall-through */
		if (--len <= 0)
		   break;
		if ( (c = locgetc()) != '0')
		   break;
        case '0':
                if ( (type != 'i') || (len <= 1) )  
		   break;
	        if ( ((inchar = locgetc()) == 'x') || (inchar == 'X') ) 
	        {
		      /* If not using sscanf and *
		       * at the buffer's end     *
		       * then LOOK ahead         */

                   if ( (iop->_file == _NFILE) || (iop->_cnt != 0) )
		      lookahead = locgetc();
		   else
		   {
		      if ( read(fileno(iop),np,1) == 1)
		         lookahead = *np;
                      else
		         lookahead = EOF;
                      chcount += 1;
                   }    
		   if ( isxdigit(lookahead) )
		   {
		       base =16;

		       if ( len <= 2)
		       {
			  locungetc(lookahead);
			  len -= 1;            /* Take into account the 'x'*/
                       }
		       else 
		       {
		          c = lookahead;
			  len -= 2;           /* Take into account '0x'*/
		       }
                   }
	           else
	           {
	               locungetc(lookahead);
	               locungetc(inchar);
                   }
		}
	        else
	        {
		    locungetc(inchar);
	            base = 8;
                }
	}
	for (; --len  >= 0 ; *np++ = c, c = locgetc()) 
	{
		if (np > numbuf + 62)           
		{
		    errno = ERANGE;
		    return(0);
                }
		if (isdigit(c) || base == 16 && isxdigit(c)) 
		{
			int digit = c - (isdigit(c) ? '0' :  
			    isupper(c) ? 'A' - 10 : 'a' - 10);
			if (digit >= base)
				break;
			if (stow && !floater) 
			{
			    if (size == LONGLONG_CHAR) {
				llvalue temp;
				/* llcval = base * llcval + digit; */
				/* use shifts so don't need llmult in libc */
				switch (base) {
				case 8:
					llcval.ll = __ll_lshifti(llcval.ll, 3);
					break;
				case 16:
					llcval.ll = __ll_lshifti(llcval.ll, 4);
					break;
				case 10:
				default:
					/* x * 10 == ((x * 4) + x) * 2 */
					temp.ll = __ll_lshifti(llcval.ll, 2);
					LL_ADD(llcval, temp, llcval);
					llcval.ll = __ll_lshifti(llcval.ll, 1);
					break;
				}
				SET_LL(temp, digit);
				LL_ADD(llcval, llcval, temp);
			    } else
				lcval = base * lcval + digit;
			}
			digitseen++;


			continue;
		}
		if (!floater)
			break;
		if (c == '.' && !dotseen++)
			continue;
		if ( (c == 'e' || c == 'E') && digitseen && !expseen++) 
                {
			*np++ = c;
			c = locgetc();
			if (isdigit(c) || c == '+' || c == '-' || isspace(c))
				continue;
		}
		break;
	}


	if (stow && digitseen)
		if(floater) 
		{
			register double dval;
	
			*np = '\0';
			dval = atof(numbuf);
			if (negflg)
				dval = -dval;
			if (size == 'l')
				*va_arg(*listp, double *) = dval;
			else
				*va_arg(*listp, float *) = (float)dval;
		}
		else if (size == LONGLONG_CHAR)
		{
			hibitll.ll = __ll_lshifti(1, BITS_PER_LONGLONG - 1);
			/* suppress possible overflow on 2's-comp negation */
			if (negflg && LL_NEQ(llcval, hibitll)) {
				LL_NEG(llcval, llcval);
			}
			*va_arg(*listp, longlong_t *) = llcval.ll;
		}
		else
		{
			/* suppress possible overflow on 2's-comp negation */
			if (negflg && lcval != HIBITL)
				lcval = -lcval;
			if (size == 'l')
				*va_arg(*listp, long *) = lcval;
			else if (size == 'h')
				*va_arg(*listp, short *) = (short)lcval;
			else
				*va_arg(*listp, int *) = (int)lcval;
		}
	if (locungetc(c) == EOF)
	    flag_eof=1;
	return (digitseen); /* successful match if non-zero */
}

static int
string(stow, type, len, tab, iop, listp)
register int stow, type, len;
register char *tab;
register FILE *iop;
va_list *listp;
{
	register int ch;
	register char *ptr;
	char *start;

	start = ptr = stow ? va_arg(*listp, char *) : NULL;
	if (type == 'c' && len == MAXINT)
		len = 1;
	while ( (ch = locgetc()) != EOF &&
	    !(type == 's' && isspace(ch) || type == '[' && tab[ch])) 
        {
		if (stow) 
			*ptr = ch;
		ptr++;
		if (--len <= 0)
			break;
	}
	if (ch == EOF ) 
	{
	       flag_eof = 1;
	       chcount-=1;
        }
        else if (len > 0 && locungetc(ch) == EOF)
		flag_eof = 1;
	if (ptr == start)
		return(0); /* no match */
	if (stow && type != 'c')
		*ptr = '\0';
	return (1); /* successful match */
}

/*	start for MNLS by UNIX Pacific on Sep.03.86	*/
static int
wstring(stow, type, len, iop, listp)
register int stow, type, len;
register FILE *iop;
va_list *listp;
{
	register ch;
	register wchar_t *wp;
	wchar_t *start;

	start = wp = stow ? va_arg(*listp, wchar_t *) : NULL;
	if (type == 'c' && len == MAXINT)
		len = 1;
	while ( (ch = getwc(iop)) != EOF &&
		! (type == 's' && iswspace(ch)) )
	{
		chcount += wcsize(ch);
		if (stow)
			*wp = ch;
		wp++;
		if (--len <= 0)
			break;
	}
	if (ch ==EOF)
		flag_eof = 1;
	else if (len > 0 && ungetwc(ch, iop) == EOF)
		flag_eof = 1;
	if (wp == start)
		return(0); /* no match */
	if (stow && type != 'c')
		*wp = 0;
	return(1); /* successful match */
}
/*	end for MNLS	*/

static unsigned char *
setup(fmt, tab)
register unsigned char *fmt;
register char *tab;
{
	register int b, c, d, t = 0;

	if (*fmt == '^') 
	{
		t++;
		fmt++;
	}
	(void) memset(tab, !t, NCHARS);
	if ( (c = *fmt) == ']' || c == '-')  /* first char is special */
	{
		tab[c] = t;
		fmt++;
	}
	while ( (c = *fmt++) != ']') 
	{
		if (c == '\0')
			return(NULL); /* unexpected end of format */
		if (c == '-' && (d = *fmt) != ']' && (b = fmt[-2]) < d) 
		{
			(void) memset(&tab[b], t, d - b + 1);
			fmt++;
		} 
		else
			tab[c] = t;
	}
	return (fmt);
}
