/* sys/filefind.c (emx+gcc) -- Copyright (c) 1992-1993 by Eberhard Mattes */

#include <sys/emx.h>
#include <string.h>
#include <errno.h>
#include <os2emx.h>
#include "syscalls.h"

static int find_conv (struct find_data *fd, struct _find *fp)
{
  if (fd->find_count != 1)
    {
      errno = ENOENT;
      return (-1);
    }
  fp->attr = (unsigned char)fd->find_buf.attrFile;
  fp->time = *(unsigned short *)&fd->find_buf.ftimeLastWrite;
  fp->date = *(unsigned short *)&fd->find_buf.fdateLastWrite;
  fp->size_lo = (unsigned short)(fd->find_buf.cbFile & 0xffff);
  fp->size_hi = (unsigned short)(fd->find_buf.cbFile >> 16);
  strcpy (fp->name, fd->find_buf.achName);
  return (0);
}


int __findfirst (const char *name, int attr, struct _find *fp)
{
  ULONG rc;
  struct find_data *fd;

  fd = &SYS_THREAD->fd;
  fd->find_handle = HDIR_SYSTEM;
  fd->find_count = 1;
  rc = DosFindFirst (name, &fd->find_handle, attr & 0x37,
                     &fd->find_buf, sizeof (fd->find_buf),
                     &fd->find_count, 1);
  if (rc != 0)
    {
      _sys_set_errno (rc);
      return (-1);
    }
  return (find_conv (fd, fp));
}


int __findnext (struct _find *fp)
{
  ULONG rc;
  struct find_data *fd;

  fd = &SYS_THREAD->fd;
  fd->find_count = 1;
  rc = DosFindNext (fd->find_handle, &fd->find_buf, sizeof (fd->find_buf),
                    &fd->find_count);
  if (rc != 0)
    {
      _sys_set_errno (rc);
      return (-1);
    }
  return (find_conv (fd, fp));
}
