/* timer.c */
#include <exec/types.h>
#include <exec/lists.h>
#include <exec/nodes.h>
#include <exec/ports.h>
#include <exec/io.h>
#include <exec/devices.h>
#include <devices/timer.h>

extern short debug;
extern long CheckIO();
struct Device *TimerBase;
struct timeRequest {
   struct IORequest tr_node;
   struct timeval tr_time;
};
extern struct timeRequest *CreateExtIO();
extern struct MsgPort *CreatePort();
struct MsgPort *timerport;
struct timeRequest timermsg;
extern long waitbits;
long timerbit;
inittimer()
{
   char debugstr[30];
   short error;
   timerport = CreatePort("timer.port",0L);
   if(timerport == NULL) {
      printf("cannot createport timer\n");
      return(1);
   }
   error = OpenDevice(TIMERNAME,UNIT_VBLANK,&timermsg,0L);
   if(error) {
      DeletePort(timerport);
      printf("can't open timer device\n");
      return(1);
   }
   timermsg.tr_node.io_Message.mn_ReplyPort = timerport;
   timermsg.tr_node.io_Command = TR_ADDREQUEST;
   timermsg.tr_node.io_Flags = 0;
   timermsg.tr_node.io_Error = 0;
   TimerBase = timermsg.tr_node.io_Device;
   timerbit = 1L << timerport->mp_SigBit;
   waitbits |= timerbit;
if(debug) {
   sprintf(debugstr,"timerbit = %lx\n");
   ttputs(debugstr);
}
   return(0);
}

endtimer()
{
   CloseDevice(&timermsg);
   DeletePort(timerport);
}
struct timeval tval;
settimer(secs)
short secs;
{
   if(secs <= 0)secs = 1;
   timermsg.tr_time.tv_secs = secs;
   timermsg.tr_time.tv_micro = 0L;
   timermsg.tr_node.io_Command = TR_ADDREQUEST;
if(debug)ttputc('\n');
   SendIO(&timermsg);
if(debug)ttputs("sendio timer\n");
}

cantimer()
{
if(debug)ttputs("abort ");
   AbortIO(&timermsg);
if(debug)ttputs("Wait ");
   Wait(timerbit);
if(debug)ttputs("WaitIO ");
   WaitIO(&timermsg);
}
/* This version works. The main Wait loop must have a WaitIO(&timermsg)
*/
