/*automusictimer.c*/
/* Copyright 1990 Thomas E. Janzen All Rights Reserved */
/*
**  FACILITY:
**
**	AlgoRhythms music improviser on Commodore (TM) Amiga (TM)
**	compiled with Lattice (TM) C 5.05
**
**  ABSTRACT:
**
**	Algorhythms improvises music over the MIDI serial port.
**
**  AUTHORS: Thomas E. Janzen
**
**  CREATION DATE:	26-MAR-1990
**
**  MODIFICATION HISTORY:
**    DATE	NAME	DESCRIPTION
**--
*/
#include "exec/types.h"
#include "exec/nodes.h"
#include "exec/lists.h"
#include "exec/memory.h"
#include "exec/interrupts.h"
#include "exec/ports.h"
#include "exec/libraries.h"
#include "exec/tasks.h"
#include "exec/io.h"
#include "exec/devices.h"
#include "devices/timer.h"
#include <proto/dos.h>
#include <proto/graphics.h>
#include <proto/exec.h>
#include <proto/mathffp.h>
#include <proto/intuition.h>

APTR TimerBase;
extern struct GfxBase *GfxBase;
extern struct IntuitionBase *IntuitionBase;
extern struct DOSBase *DOSBase;
extern struct MathBase *MathBase;

struct timerequest *tr;
extern struct IORequest *CreateExtIO();

extern struct timerequest *CreateTimer(ULONG unit);

int DeleteTimer(struct timerequest *);

struct timerequest *CreateTimer(ULONG unit) {
	int error;
	struct MsgPort *timerport;
	struct timerequest *timermsg;
	timerport=CreatePort(NULL,0);
	if(timerport==NULL) {
		return(NULL);
	}
	timermsg=(struct timerequest *)
		CreateExtIO(timerport,sizeof(struct timerequest));
	if(timermsg==NULL) {
		return(NULL);
	}
	error=OpenDevice(TIMERNAME,unit,timermsg,0);
	if(error!=0) {
		DeleteTimer(timermsg);
		return(NULL);
	}
	return(timermsg);
}

int StartTimer(void) {
	tr=CreateTimer(UNIT_MICROHZ);
	if(tr==0)return(-1);
	return (0);
}

int GetSysTime(struct timeval *tv) {
	tr->tr_node.io_Command=TR_GETSYSTIME;
	DoIO(tr);
	*tv=tr->tr_time;
	return (0);
}

void RemoveTimer(void) {
	DeleteTimer(tr);
}

int DeleteTimer(struct timerequest *tr) {
	struct MsgPort *tp;
	if(tr != 0) {
		tp=tr->tr_node.io_Message.mn_ReplyPort;
		if(tp!=0) {
			DeletePort(tp);
		}
		if (tr) CloseDevice(tr);
		DeleteExtIO(tr,sizeof(struct timerequest));
	}
	return 0;
}
