#include <stdio.h>
#include <ctype.h>
#include "getword.h"


char buf[BUFSIZE];	/* ungetch用のバッファ */
int bufp = 0;		/* buf中の次の空き位置 */


int getword(char *word, int lim)
{
	int c, getch(void);
	void ungetch(int);
	
	char *w = word;
	
	printf("[DBG] getword() start\n");
	
	/* スペースを読み飛ばす */
	while (isspace(c = getch())) {
		;
	}
	
	if (c != EOF) {
		*(w++) = c;	
	}
	
	if (!isalpha(c)) {
		*w = '\0';
		return c;
	}
	
	for (; --lim > 0; w++) {
		if (!isalnum(*w = getch())) {
			ungetch(*w);
			break;
		}
	}
	
	*w = '\0';

	printf("[DBG] getword() end  w:%s\n", w);
	
	return w[0];
}



int getch(void)	/* (押し戻された可能性もある)1文字を取ってくる */
{
	return (bufp > 0 ? buf[--bufp] : getchar());
}


void ungetch(int c)	/* 文字を入力に戻す */
{
	if (bufp >= BUFSIZE) {
		printf("ungetch: too meny charadtors\n");
	}
	else {
		buf[bufp++] = c;
	}
}