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

#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <io.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <emx/io.h>
#include <emx/time.h>
#include <emx/syscalls.h>

int _stat (const char *name, struct stat *buffer)
{
  int rc, 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;
    }
  rc = __stat (name, buffer);
  if (rc == 0)
    {
      if (slash && ((buffer->st_mode & S_IFMT) != S_IFDIR))
        {
          errno = ENOTDIR;
          return -1;
        }
      if (!_tzset_flag) _tzset ();
      _loc2gmt (&buffer->st_atime, -1);
      _loc2gmt (&buffer->st_mtime, -1);
      _loc2gmt (&buffer->st_ctime, -1);
      if ((buffer->st_mode & S_IFMT) == S_IFREG)
        {
          tmp = _getext (name);
          if (tmp != NULL &&
              (_stricmp (tmp, ".exe") == 0 ||
               _stricmp (tmp, ".com") == 0 ||
               _stricmp (tmp, ".cmd") == 0 ||
               _stricmp (tmp, ".bat") == 0))
            buffer->st_mode |= (S_IEXEC >> 6) * 0111;
        }
    }
  return rc;
}
