#include "config.h"
#include "libiberty.h"
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef __MINGW32__
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

/* 

@deftypefn Supplemental int gettimeofday (struct timeval *@var{tp}, void *@var{tz})

Writes the current time to @var{tp}.  This implementation requires
that @var{tz} be NULL.  Returns 0 on success, -1 on failure.

@end deftypefn

*/ 

int
gettimeofday (struct timeval *tp, void *tz)
{
/* MS Windows version */
#ifdef __MINGW32__
  /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
  static const unsigned long long W32_FT_OFFSET = 116444736000000000ULL;
  SYSTEMTIME s_time;
  union {
    unsigned long long ns100;
    FILETIME f_time;
  } now;

  if (tz)
    abort ();
  /* GetSystemTimeAsFileTime, introduced with NT version 3.5 and
     also available on Win9x, would be more efficient.  We use
     this instead to provide support for NT versions back to 3.1.
     This will also work on WinCE.  We don't worry about NT 3.0
     and earlier since the CRT used by mingw (msvcrt.dll) is not
     compatible with NT 3.0 either.  */
  GetSystemTime (&s_time);
  if (!SystemTimeToFileTime (&s_time, &now.f_time))
    return -1; 
  tp->tv_usec=(long)((now.ns100 / 10ULL) % 1000000ULL );
  tp->tv_sec= (long)((now.ns100 - W32_FT_OFFSET) / 10000000ULL);
  return 0;

#else 

/* Generic version */
  if (tz)
    abort ();
  tp->tv_usec = 0;
  if (time (&tp->tv_sec) == (time_t) -1)
    return -1;
  return 0;

#endif

}
