#include <clib/alib_protos.h>
#include <clib/alib_stdio_protos.h>
#include <clib/cia_protos.h>
#include <clib/dos_protos.h>
#include <clib/exec_protos.h>
#include <clib/misc_protos.h>
#include <clib/timer_protos.h>
#include <clib/utility_protos.h>

#include <stdlib.h>
#include <string.h>

#include <midi/realtime.h>
#include <midi/realtimebase.h>
#include <midi/mididefs.h>
#include <clib/realtime_protos.h>
#include <pragmas/realtime_pragmas.h>

void kprintf(char *,...);

ULONG __saveds __asm myHookFunc (
register __a1 struct pmTime *msg,
register __a2 struct PlayerInfo *pi);

struct Hook myHook = {
	{ NULL, NULL },
	myHookFunc,
};

struct RealTimeBase	*RealTimeBase;

struct PlayerInfo *test_pi;

char			a_sys_ex[] = { MS_SysEx, 8, 7, 6, 5, 4, 3, 2, 1, MS_EOX };
char			b_sys_ex[128];

char			r_sys_ex[] = { MS_SysEx, 0x41, 0x07, 0x14, 0x11, 0,0,0,
								0,0,0x10, 0x70, MS_EOX };
	/* stub functions */

struct PlayerInfo *CreatePlayer(Tag tag, ...)
{	return CreatePlayerA((struct TagItem *)&tag );
}

BOOL SetPlayerAttrs(struct PlayerInfo *pi, Tag tag, ...)
{	return SetPlayerAttrsA(pi, (struct TagItem *)&tag );
}

void main(int argc, char *argv[])
{	LONG	time, ticks = 500;
	LONG	result = 0;
	ULONG	hooktag = TAG_IGNORE;
	WORD	i;

	for (i=1;i<argc;i++)
	{
		if (argv[i][0] >= '0' && argv[i][0] <= '9') ticks = atol(argv[i]);
		else if (!stricmp(argv[i],"hook")) hooktag = PLAYER_Hook;
	}

	if (RealTimeBase = (struct RealTimeBase *)OpenLibrary("realtime.library",0L))
	{
		if (test_pi = CreatePlayer(
			PLAYER_Name, "test player",
			PLAYER_Conductor, "my conductor",
			PLAYER_AlarmSigBit, SIGBREAKB_CTRL_F,
			PLAYER_SignalTask, FindTask(NULL),
			hooktag, &myHook,
			TAG_DONE ))
		{
			printf("Opened Player!\n");

			SetConductorState(test_pi,CLOCKSTATE_RUNNING,0);

			time = RealTimeBase->Time;
			SetPlayerAttrs(test_pi,
				PLAYER_AlarmTime, ticks,
				PLAYER_Ready, TRUE,
				TAG_END);

			Wait(SIGBREAKF_CTRL_F);
			printf("Alarm time = %ld\n",time = RealTimeBase->Time - time);

			if (time < ticks - 50) result = 26;

			if(hooktag != TAG_IGNORE) kprintf("\n");

			DeletePlayer(test_pi);
		}
		CloseLibrary((struct Library *)RealTimeBase);
	}

	exit(result);
}

ULONG __saveds __asm myHookFunc (
register __a1 struct pmTime *msg,
register __a2 struct PlayerInfo *pi)
{
	pi->pi_MetricTime = msg->pmt_Time;
	if ((pi->pi_MetricTime & 63) == 0) kprintf("%ld\r",pi->pi_MetricTime);
	return 0L;
}
