/*
 *
 * BSD-like directory searching routines
 * Edwin Hoogerbeets 1989
 *
 */
#ifdef AMIGA
#include <stdio.h>
#include "dir.h"
#include <exec/memory.h>

extern char *malloc();
extern char *free();
extern struct FileLock *Lock();
extern char  *AllocMem();

static struct direct direntry;

#define FIBSIZE (long)sizeof(struct FileInfoBlock)

DIR *opendir(filename)
char *filename;
{
  DIR *dir;

  if ( !(dir = (DIR *) malloc(sizeof(DIR))) ) {
    return(NULL);
  }

  /* needs to be long word aligned, so AllocMem must be used */
  if ( !(dir->fib = (struct FileInfoBlock *)
                                   AllocMem(FIBSIZE,MEMF_CLEAR)) ) {
    free(dir);
    return(NULL);
  }

  if ( !(dir->lock = Lock(filename,ACCESS_READ)) ) {
    FreeMem(dir->fib,FIBSIZE);
    free(dir);
    return(NULL);
  }

  Examine(dir->lock,dir->fib);
  strncpy(dir->name,filename,31L);

  return(dir);
}

struct direct *readdir(dir)
DIR *dir;
{
  if ( dir ) {
    if ( ExNext(dir->lock,dir->fib) ) {
      strcpy(direntry.d_name,dir->fib->fib_FileName);
      direntry.d_namlen = strlen(direntry.d_name);

      /* inode number emulation! */
      direntry.d_ino = dir->fib->fib_DiskKey;

      direntry.d_reclen = sizeof(struct direct) - MAXNAMELEN +
                          direntry.d_namlen + 1;

      return(&direntry);
    } else {
      return(NULL);
    }
  } else {
    return(NULL);
  }
}

void closedir(dir)
DIR *dir;
{
  if ( dir ) {
    UnLock(dir->lock);
    FreeMem(dir->fib,FIBSIZE);
    free(dir);
  }
}

#endif /* AMIGA */
