#include <hsubs.h>

static char pbuf[512];
static int gfd = -1;

ngetent(input, name, obuf)
char *input, *name, *obuf;
{
	int h, fd, r;
	long h1;
	register char *l, *s, *p;

	if(gfd == -1){
		if((gfd = open(input, 0)) == -1){
			write(2,"ngetent: cant open input\n", 25);
			return(-1);
		}
	}

	h = hkey(name);
	h1 = (long)(h >> 2) << 9;

	if(lseek(gfd, h1, 0) == -1){
		write(2, "getent: Seek error 1\n", 21);
		return(-1);
	}

	while((r = read(gfd, pbuf, 512)) > 0 && (r & 0177) == 0){
#ifdef DIAGNOSTICS
		printf("Read block %D\n", h1++ >> 9);
#endif
		s = pbuf;
		l = s+r;
		if(h){
			s += ((h & 03) << 7);
			h = 0;
		}
		while(s < l){
			if(*s == 0)goto notfound;
			p = s;
			while(*p != ':')p++;
			*p = 0;
			if(strcmp(name, s)){
				s += 128;
				continue;
			}
			*p = ':';
			for(p = s+128, l = obuf; s < p; *l++ = *s++);
			return(0);
		}
	}
notfound:
	return(1);
}

clhash()
{
	close(gfd);
	gfd = -1;
}


ugetent(input, h, obuf)
char *input, *obuf;
int h;
{
	int uid, r;
	long h1;
	int nu;
	register char *s, *l, *p;

	if(gfd == -1){
		if((gfd = open(input, 0)) == -1){
			write(2, "ugetent: no file in\n", 20);
			return(-1);
		}
	}
	uid = h;
	h = ukey(h);
	h1 = (long)(h >> 2) << 9;
	if(lseek(gfd, h1, 0) == -1){
		write(2, "ugetent: Seek error 2\n", 22);
		return(-1);
	}
	while((r = read(gfd, pbuf, 512)) > 0 && (r & 0177) == 0){
#ifdef DIAGNOSTICS
		printf("Read from block %D\n", h1++ >> 9);
#endif
		s = pbuf;
		l = s + r;
		if(h){
			s += ((h & 03) << 7);
			h = 0;
		}
		while(s < l){
			if(*s == 0)goto notfound;
			p = s;
			while(*p++ != ':');
			while(*p++ != ':');
			nu = 0;
			while(*p >= '0' && *p <= '9')
				nu = nu * 10 + (*p++) - '0';
			if(nu != uid){
				s += 128;
				continue;
			}
			for(p = s+128, l = obuf; s < p; *l++ = *s++);
			return(0);
		}
	}
notfound:
	return(1);
}
