/*
 * open.c - open(), creat()

    This file is part of libRILc, a standard C library for GCC on Amiga OS.
    Copyright © 1998  Rask Ingemann Lambertsen

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    As a special exception, if you link this library with files compiled
    with a GNU compiler to produce an executable, this does not cause the
    resulting executable to be covered by the GNU General Public License.
    This exception does not however invalidate any other reasons why the
    executable file might be covered by the GNU General Public License.
*/

#include <dos/dos.h>
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>

#ifdef __PPC__
#include <powerup/gcclib/powerup_protos.h>
#include <ppcproto/dos.h>
#undef  Open
#define Open(a,b)   PPCOpen(a,b)
#undef  Seek
#define Seek(a,b,c) PPCSeek(a,b,c)
#else
#include <proto/dos.h>
#endif

#include "internal/globals.h"
#include "internal/systemcalls.h"
#include "stdio/globals.h"

int open (const char *name, int flags, ...)
{
    __syscall_handle sh;
    LONG fhMode;
    BOOL truncate;
    FILE *file;
    BPTR fh;

    if ((flags & O_TRUNC) && (flags & O_CREAT))
    {
      fhMode = MODE_NEWFILE;
      truncate = FALSE;     /* MODE_NEWFILE truncates. */
    }
    else if (flags & O_CREAT)
    {
      fhMode = MODE_READWRITE;
      truncate = FALSE;
    }
    else if (flags & O_TRUNC)
    {
      fhMode = MODE_OLDFILE;
      truncate = TRUE;
    }
    else
    {
      fhMode = MODE_OLDFILE;
      truncate = FALSE;
    }

    sh = __syscall_start ();
    file = __alloc_file ();
    if (!file)
    {
      __seterrno ();
      __syscall_end (sh);
      return (-1);
    }

    /* Now, try to open the file */
    fh = Open ((STRPTR) name, fhMode);
    if (fh)
    {
      /* Initialise various fields. */
      __fopen (file, fh, -1, BUFSIZ, BUF_FULL);

      /* Append if requested. */
      if (flags & O_APPEND)
        Seek (fh, 0, OFFSET_END);

      /* Truncate if requested. */
      if (truncate)
        SetFileSize (fh, 0, OFFSET_BEGINNING);
    }
    else
    {
      __seterrno ();
      __free_file (file);
      file = NULL;
    }

    __syscall_end (sh);
    return (file ? (int) file : -1);
}

int creat (const char *path, mode_t mode)
{
  return (open (path, O_TRUNC | O_CREAT, mode));
}
