#include <exec/types.h>
#include <exec/io.h>
#include <exec/memory.h>
#include <exec/ports.h>

#include <sys/time.h>

#define timeval _timeval
#include <devices/timer.h>
#undef timeval

#include <dos/dos.h>
#include <dos/dosextens.h>

#include <clib/alib_protos.h>

#include <inline/stubs.h>
#ifdef __OPTIMIZE__
#include <inline/exec.h>
#include <inline/dos.h>
#else
#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#endif

int gettimeofday(struct timeval *tp, struct timezone *tzp)
{
	int ok_return=-1;

	if (tzp)
	{
      /* timezones are obsolete, we always return
       * GMT... (from DST_MET you can see, that this software has been
       * written in Middle Europe :-))
       */

      tzp->tz_minuteswest = 0;
      tzp->tz_dsttime = DST_MET;
    }

	if (tp)
	{
		struct timerequest *TimerIO;
		struct MsgPort *TimerMP;

		if ( (TimerMP = CreateMsgPort()) )
	    {
		    if ( (TimerIO = (struct timerequest *)
		        CreateExtIO(TimerMP,sizeof(struct timerequest))) )
	        {
				LONG error;
	    	        /* Open with UNIT_VBLANK, but any unit can be used */

		        if (!(error=OpenDevice(TIMERNAME,UNIT_VBLANK,(struct IORequest *)TimerIO,0L)))
	            {

		            	/* Issue the command and wait for it to finish, then get the reply */

       		    	TimerIO->tr_node.io_Command = TR_GETSYSTIME;
	           		DoIO((struct IORequest *) TimerIO);

			            /* Get the results and close the timer device */
		            tp->tv_usec = TimerIO->tr_time.tv_micro;
		            tp->tv_sec  = TimerIO->tr_time.tv_secs;

						/* add the offset from unix to amigados time system */
					tp->tv_sec += (8*365+2) * 24 * 3600;

			            /* Close the timer device */
		            CloseDevice((struct IORequest *) TimerIO);

					ok_return=0;
	            }
	        	/* else ; */
		             /* Error: Could not open timer device */

       				/* Delete the I/O request structure */
	   		    DeleteExtIO((struct IORequest *)TimerIO);
	        }
		    /* else ; */
		        /* Error: Could not create I/O structure */

		    	/* Delete the port */
		    DeleteMsgPort(TimerMP);
		}
		/* else ; */
		 /* Error: Could not create port */
	}

 	return ok_return;
}
