/* sys/utimes.c (emx+gcc) -- Copyright (c) 1992-1993 by Eberhard Mattes */

#include <sys/emx.h>
#include <os2emx.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include "syscalls.h"

static void _sys_t2p (long sec, PFTIME time, PFDATE date)
{
  struct tm *p;
  USHORT tmp;

  p = gmtime (&sec);
#if 0                           /* This didn't work in GCC versions <= 2.4 */
  time->twosecs = p->tm_sec / 2;
  time->minutes = p->tm_min;
  time->hours = p->tm_hour;
  date->day = p->tm_mday;
  date->month = p->tm_mon + 1;
  date->year = p->tm_year - 1980 + 1900;
#else
  tmp = (p->tm_sec / 2) + (p->tm_min << 5) + (p->tm_hour << 11);
  *(USHORT *)time = tmp;
  tmp = p->tm_mday + ((p->tm_mon + 1) << 5) + ((p->tm_year - 80) << 9);
  *(USHORT *)date = tmp;
#endif
}


int __utimes (const char *name, const struct timeval *tvp)
{
  ULONG rc;
  FILESTATUS3 info;

  if ((name[0] == '/' || name[0] == '\\') && strlen (name) >= 6 &&
      memicmp (name+1, "pipe", 4) == 0 && (name[5] == '/' || name[5] == '\\'))
    {
      errno = ENOENT;
      return (-1);
    }
  rc = DosQueryPathInfo (name, FIL_STANDARD, &info, sizeof (info));
  if (rc != 0)
    {
      _sys_set_errno (rc);
      return (-1);
    }
  *(USHORT *)&info.ftimeCreation = 0;
  *(USHORT *)&info.fdateCreation = 0;
  _sys_t2p (tvp[0].tv_sec, &info.ftimeLastAccess, &info.fdateLastAccess);
  _sys_t2p (tvp[1].tv_sec, &info.ftimeLastWrite, &info.fdateLastWrite);
  rc = DosSetPathInfo (name, FIL_STANDARD, &info, sizeof (info), 0);
  if (rc != 0)
    {
      _sys_set_errno (rc);
      return (-1);
    }
  return (0);
}
