/*****************************************************************************\
 * $VER: TetrisQ_timerctrl.c 1.4                                             *
 *                               DICE/LATTICE C/SAS C/AZTEC C + AmigaOS 2.04 *
 *                 _                                                         *
 * 4.10.92    _   // (c)1992 by "Quarky" Dieter Temme                        *
 *            \\ //                                                          *
 * :ts=4       \X/ --- Freeware --- ONLY AMIGA MAKES IT POSSIBLE             *
 *                                                                           *
\*****************************************************************************/

#include "amigacompq.h"
#include "definitions.h"

#include <clib/exec_protos.h>
#include <devices/timer.h>

#ifdef PRAGMAS_
 #include <pragmas/exec_lib.h>
#endif


/*>> local variables <<*/
BYTE tcount;					/* counter for open timers */
ULONG timersig[2];				/* timer signal flags */
struct MsgPort *timeport[2];	/* pointer to timer message ports */
struct timerequest *timereq[2];	/* pointer to timer request structures */

/*>> time delays for falling figure in level 1 to 9 <<*/
ULONG micros[]=
{	400000, 350000, 300000, 275000, 250000, 200000, 150000, 100000, 50000
};


/*==== initialize timers ====*/
void TC_InitTimer_(void)
{	UBYTE num;

	for (num= 0; num <= 1; num++)
	{
		while (!(timeport[num]= CreateMsgPort()))
			PrintNoMem_();
		tcount++;
		while (!(timereq[num]= (struct timerequest *) \
			CreateIORequest(timeport[num], sizeof(struct timerequest))))
			PrintNoMem_();
		tcount++;
		OpenDevice("timer.device", UNIT_MICROHZ,
			(struct IORequest *)timereq[num], 0l);
		timereq[num]->tr_node.io_Command= TR_ADDREQUEST;
		timersig[num]= 1<<timeport[num]->mp_SigBit;
		tcount++;
	}
}

/*==== stop and/or start timer(s) ====*/
void TC_CtrlTimer_(const BOOL start)
{	extern ULONG currentsigs; /* from "playerctrl.c" */
	extern BYTE pl; /* from "playerctrl.c" */

	if (!start)
	{	AbortIO((struct IORequest *)timereq[pl]);
		WaitIO((struct IORequest *)timereq[pl]);
		SetSignal(0, timersig[pl]);
	} else
	{	timereq[pl]->tr_time.tv_secs= 0;
		timereq[pl]->tr_time.tv_micro= micros[LS_GetLevel_()-1];
		SendIO((struct IORequest *)timereq[pl]);
	}
}

/*==== close timers ====*/
void TC_CloseTimer_(void)
{	extern BYTE pl; /* from "playerctrl.c" */

	for (pl= (tcount > 3)? 1 : 0; pl >= 0; pl--)
		switch (tcount-(pl? 3 : 0))
		{	case 3:	if (!CheckIO((struct IORequest *)timereq[pl]))
						TC_CtrlTimer_(CT_STOP_);
					CloseDevice((struct IORequest *)timereq[pl]);
			case 2:	DeleteIORequest((struct IORequest *)timereq[pl]);
			case 1:	DeleteMsgPort(timeport[pl]);
					tcount-= 3;
		}
}
