#include "ndir.h"
#include <exec/memory.h>
#include <functions.h>

#ifdef TEST
#include <stdio.h>
#endif

/*
 * support for Berkeley directory reading routine on a V7 file system
 */

extern char *malloc();

/*
 * open a directory.
 */

DIR *
opendir(name)
char *name;
{
	register DIR *dirp;
	struct Lock  *lock;

#ifdef TEST
	fprintf( stderr, "opendir: Opening \"%s\"\n", name );
#endif
	if ( ( lock = Lock( name, ACCESS_READ )) == NULL )
	  {
#ifdef TEST
		fprintf( stderr, "opendir: Can't open.\n" );
#endif
		return NULL;
	  }

	if ( (dirp = (DIR *)malloc(sizeof(DIR))) == NULL )
	  {
#ifdef TEST
		fprintf( stderr, "opendir: couldn't malloc %d\n",sizeof(DIR));
#endif
		UnLock( lock );
		return NULL;
	  }
	if ( !Examine( lock, &dirp->fib) )
	  {
#ifdef TEST
	     fprintf( stderr, "opendir: Couldn't Examine directory\n" );
#endif
	     free( dirp );
	     UnLock( lock );
	  }

	dirp->lock = lock;
#ifdef TEST
	fprintf( stderr, "opendir: Sucessful\n" );
#endif

	return dirp;
}


/*
 * get next entry in a directory.
 */
struct direct *
readdir(dirp)
register DIR *dirp;
{
	static struct direct dir;

	while ( ExNext( dirp->lock, &dirp->fib ) )
	   {
		if ( dirp->fib.fib_DirEntryType <= 0 )
		  {
			dir.d_ino = 0;
			strcpy( dir.d_name, dirp->fib.fib_FileName );
#ifdef TEST
			fprintf( stderr, "readdir: OK \"%s\"\n",  dir.d_name);
#endif
			dir.d_namlen = strlen(dir.d_name);
			dir.d_reclen = DIRSIZ(&dir);
			return (&dir);
		  }
	    }

#ifdef TEST
	fprintf( stderr, "readdir: No More Entries.\n" );
#endif
	strcpy( dir.d_name, "" );
	return NULL;

}

/*
 * close a directory.
 */
void
closedir(dirp)
register DIR *dirp;
{

	UnLock( dirp->lock );
	free((char *)dirp);
}


#ifdef TEST
#include <errno.h>

main()
{
	char command[100];

	struct DIR *dirp;
	struct direct *dp;
	
	while(gets(command) != NULL) {

		fprintf( stderr, "test: %s\n", command );

		if ((dirp = opendir( command )) == NULL ) {
			fprintf( stderr, "couldn't open dir %s\n", command );
		}
		else
		   {
			while ((dp = readdir(dirp)) != NULL) 
				fprintf( stderr, "%s", dp->d_name );
		
			closedir( dirp );
		   }    
	}
}
#endif

