/* Amiga-type replacement for standard Unix time() function.  Can't use
   Lattice's time() function from within a library because it's not
   reentrant (has some hidden static vars it sets) and because it wants
   you to have opened dos.library for some reason, which is supposedly
   a bad idea inside a library.  Oh, well... this is quite a bit
   smaller & faster anyway.  B-) */


#include <proto/all.h>
#include <exec/types.h>
#include <exec/exec.h>
#include <devices/timer.h>
#include <string.h>

/* # seconds between 1-1-70 (Unix time base) and 1-1-78 (Amiga time base).
   Add this value to the returned seconds count to convert Amiga system time
   to normal Unix system time. */
ULONG UnixTimeOffset = 252482400;



/* Returns current system time in standard Amiga-style timeval structure, if
   you pass a pointer to one.  Also returns the seconds part as the return
   value.  This lets you get just the seconds by calling GetSysTime(NULL)
   if that's all you want, or the full timeval struct if you need that.
   This is very similar to how the standard time() function is used. */

ULONG GetSysTime(struct timeval *tv) {
  struct timerequest tr;

  /* timer.device must be working or the system would've died, so let's
     not bother with error checking. */
  memset(&tr,0,sizeof(tr));
  OpenDevice(TIMERNAME,UNIT_VBLANK,(struct IORequest *)&tr,0L);

  tr.tr_node.io_Message.mn_Node.ln_Type = NT_MESSAGE;
  tr.tr_node.io_Command = TR_GETSYSTIME;

  DoIO((struct IORequest *)&tr);

  if (tv)
    *tv = tr.tr_time;

  CloseDevice((struct IORequest *)&tr);

  return tr.tr_time.tv_secs;
}
