#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>

FILE *pwd_fd;
char pwd_line[250];

struct passwd *parse(char *p)
{	int x;
	static struct passwd pwent;
	static char pwd_copy[250];
	char *entry[NRE];

	p=memcpy(pwd_copy,p,249);
	pwd_copy[249]=0;	/* don't damage original line */

	for(x=0;x<NRE;x++)
	{	entry[x]=p;
		if ((p=strchr(p,':')) != NULL)
			*p++='\0';
	}
	pwent.pw_name  =entry[NAME];	pwent.pw_dir =entry[HOME];
	pwent.pw_shell =entry[SHELL];	pwent.pw_uid =atoi(entry[UID]);
	pwent.pw_passwd=entry[PWD];	pwent.pw_gid =atoi(entry[GID]);
	return &pwent;
}

void setpwent (void)
{	if (pwd_fd != NULL)	fseek(pwd_fd,0,SEEK_SET);
	else pwd_fd = fopen(PASSWD, "r");

	if(pwd_fd == NULL)	/* last chance ! */
		if((pwd_fd=fopen("c:\\etc\\passwd","r")) == NULL) 
			fputs("pwd: Can't open PASSWD file !!\n",stderr);
}

struct passwd *getpwent (void)
{
	if (pwd_fd == NULL)	/* file not open yet */
		setpwent();
	if (fgets(pwd_line,(int)sizeof(pwd_line)-1,pwd_fd) == NULL)
		return NULL;

	return parse(pwd_line);
}

void endpwent (void)
{	if (pwd_fd != NULL)
	{	fclose (pwd_fd);
		pwd_fd = NULL;
	}
}

struct passwd *getpwnam(name)
char *name;
{	struct passwd *pwent;

	setpwent();
	while(1)
	{	if((pwent=getpwent()) == NULL)
		{	endpwent();
			return NULL;	/* loginname not found */
		}
		if(! strncmp(name,pwent->pw_name,strlen(pwent->pw_name)))
			break;  /* login name found */
    }
	endpwent();
    return pwent;
}

struct passwd *getpwuid(uid)
int uid;
{	struct passwd *pwent;

	setpwent();
	while(1)
	{	if((pwent=getpwent()) == NULL)
		{	endpwent();
			return NULL;	/* loginname not found */
		}
		if(pwent->pw_uid == uid)
			break;  /* user id found */
    }
	endpwent();
    return pwent;
}
