/* sys/open.c (emx+gcc) -- Copyright (c) 1992-1993 by Eberhard Mattes */

#include <sys/emx.h>
#define INCL_DOSERRORS
#include <os2emx.h>
#include <errno.h>
#include "syscalls.h"

int __open (const char *name, int flags)
{
  ULONG rc;
  ULONG mode, attr, action, open_mode;
  HFILE handle;
  int fail_errno;

  mode = flags & 0x77;
  attr = (flags >> 8) & 0xff;
  if (_sys_umask & 0200)
    attr |= 1;
  fail_errno = ENOENT;
  if (flags & 0x10000)
    {
      if (flags & 0x20000)
        {
          open_mode = OPEN_ACTION_FAIL_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
          fail_errno = EEXIST;
        }
      else if (flags & 0x40000)
        open_mode = OPEN_ACTION_REPLACE_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
      else
        open_mode = OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
    }
  else if (flags & 0x40000)
    open_mode = OPEN_ACTION_REPLACE_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
  else
    open_mode = OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
  rc = DosOpen (name, &handle, &action, 0, attr, open_mode, mode, NULL);
  if (rc == ERROR_OPEN_FAILED)
    {
      errno = fail_errno;
      return (-1);
    }
  if (rc != 0)
    {
      _sys_set_errno (rc);
      return (-1);
    }
  return (handle);
}
