/*
 *   WaitTimeout benötigt addexit.c zum Linken
 */


#include <stdlib.h>
#include <stdio.h>
#include <exec/types.h>
#include <exec/devices.h>
#include <devices/timer.h>
#include <proto/exec.h>
#include <libraries/dos.h>
#include <proto/dos.h>

#include "addexit.h"

static struct MsgPort *port=NULL;
static struct timerequest *ioreq=NULL;
static short inited=0;

static void freeall(void)
{
   if(ioreq) {
      CloseDevice((struct IORequest *)ioreq);
      DeleteExtIO((struct IORequest *)ioreq);
   }
   if(port) DeleteMsgPort(port);
}


static void InitTimeout(void)
{
   addexit(freeall);
   if(!(port=CreateMsgPort())) exit(RETURN_FAIL);

   if(!(ioreq=(struct timerequest *)
           CreateExtIO(port,sizeof(struct timerequest)))) exit(RETURN_FAIL);


   if(OpenDevice("timer.device",UNIT_MICROHZ,(struct IORequest *)ioreq,0))
                                                          exit(RETURN_FAIL);

   ioreq->tr_node.io_Command=TR_ADDREQUEST;
   inited=1;
}


ULONG WaitTimeout(ULONG SignalMask,ULONG Seconds,ULONG Micros)
{
   ULONG sig;
   if(!inited) InitTimeout();

   ioreq->tr_time.tv_secs=Seconds;
   ioreq->tr_time.tv_micro=Micros;

   SendIO((struct IORequest *)ioreq);
   sig=Wait(SignalMask|(1<<port->mp_SigBit));
   sig&=~(1<<port->mp_SigBit);
   AbortIO((struct IORequest *)ioreq);
   WaitIO((struct IORequest *)ioreq);
   SetSignal(0,1<<port->mp_SigBit);   /* Signal von Timer zurücksetzen */
   return(sig);
}

