
#include "xpm.h"	/* CPMIO header file for i/o operations.*/
#include "megen.h"	/* general defines		*/
#include "meglob.h"	/* global variable definitions	*/
#include "mefiles.h"	/* file names			*/

#include "ctype.h"


/* Add a new user to users file */

add_user(up)
 usr *up;
{
int tval,rec,lastrec,user_rec;

if ( (tval=find_user(up->name))>=0 ) return ERROR;  /* user exists already */

rec=getrec(users);	/* save current place */

if (tval==HASHEMPTY)	/* easiest case ..  update hash file, write to last */
	{
	toeof(users);			/* end of file to write new */
	user_rec=getrec(users);		/* this is record to return */
	movmem(up,bufloc(users),128);
	if (write(users,0)!=128) return ERROR;
	write_hash(hash_fn(up->name)%HFSIZE,getrec(users));
	}
   else	{		/* we are at dead user, or end of list */
	usr *ufp;

	read(users,0);
	ufp=bufloc(users);
	if ( (ufp->file_info)&DEADUSER )  /* if record is from dead user.. */
		{
		up->file_info=(ufp->file_info)^DEADUSER; /* make live user */
		up->number=ufp->number;	/* set to write to current loc     */
		user_rec=getrec(users);
		}
	   else	{			 /* record from end of hash list */
		char tbuf[129];

		movmem(ufp,tbuf,128);		/* save user being updated */
		toeof(users);
		user_rec=lastrec=getrec(users);	/* save eof record number  */
		movmem(up,bufloc(users),128);	/* read for write to eof   */
		if (write(users,0)!=128) return ERROR;
	
		setarec(users,rec);		
		movmem(tbuf,ufp,128);		/* restore user (no read op) */
		ufp->file_info|=MOREHASH;	/* signal not end of list  */
		ufp->number=lastrec;		/* point to end */
		}
	write(users,0);				/* write record */

	}	/* hash not empty else */

close(users); users=open(USERFILE,0);	/* flush buffer so toeof works later */
setarec(users,user_rec);
return user_rec;	/* all ok, return user record (user number-1) */

}   /* add_user */


write_hash(h_val,rec)
 unsigned h_val;
 int rec;
{
FILE *hashfile;
int *ip;

hashfile=open_hash();
ip=bufloc(hashfile);
setarec(hashfile,(h_val/64));	/* seek to record to update */
read(hashfile,0);		/* read old stuff */
ip[h_val%64]=rec;		/* change old to new */
write(hashfile,0);		/* write */
close(hashfile);

}


/* delete user @ name from users file.. (set DEADUSER flag) */

del_user(name)
 char *name;
{
usr *up;

if (find_user(name)<0) return ERROR;	/* user not found */

up=bufloc(users);			/* point to read in record */
up->file_info|=DEADUSER;		/* set dead user flag	   */
write(users,0);				/* update		   */

return getrec(users);			/* return record loc if ok */
}


