/* access.c (emx+gcc) -- Copyright (c) 1990-1996 by Eberhard Mattes */

#include <string.h>
#include <io.h>
#include <errno.h>
#include <emx/io.h>
#include <emx/syscalls.h>

int _access (const char *name, int mode)
{
  int a, slash;
  size_t len;
  char *tmp;

  /* If there is a trailing slash or backslash, remove it and set
     `slash' to true.  Make a local copy of the string to remove the
     slash or backslash. */

  len = strlen (name);
  slash = _trslash (name, len, 1);
  if (slash)
    {
      tmp = alloca (len);
      memcpy (tmp, name, len - 1);
      tmp[len-1] = 0;
      name = tmp;
    }

  /* Query the attributes of the file or directory. */

  a = __chmod (name, 0, 0);
  if (a < 0)
    return -1;

  /* Fail if the name ends with a slash or backslash and is not a
     directory. */

  if (slash && !(a & _A_SUBDIR))
    {
      errno = ENOTDIR;
      return -1;
    }

  /* Volume IDs are not accessible. */

  if (a & _A_VOLID)
    {
      errno = ENOENT;
      return -1;
    }

  /* When testing for write permission, check the read-only bit. */

  if ((mode & 2) && (a & _A_RDONLY))
    {
      errno = EACCES;
      return -1;
    }
  return 0;
}
