/**********************************************
 **************   events.c   ******************
 **********************************************/

#define INTUI_V36_NAMES_ONLY

#include <exec/exec.h>
#include <intuition/intuition.h>

#include <clib/exec_protos.h>
#include <clib/gadtools_protos.h>

#include "stickit2.h"

#include <stdio.h>		/* For printf */

#include "consts.h"
#include "structs.h"
#include "proto.h"

extern prj_p prj;

/*
Function : void events_mainloop(void)
Purpose : Handles the incoming events from all the ports and dispatches the
	calls to the appropriate handler.
*/

void events_mainloop(void)
{
	ULONG signals;
	BOOL done = FALSE;

	while (!done) {
		signals = Wait((1L << prj->broker_msg_port->mp_SigBit) |
(1L << prj->main_msg_port->mp_SigBit));

		if (signals & (1L << prj->broker_msg_port->mp_SigBit))
			done = commod_event();
		else if (signals & (1L << prj->main_msg_port->mp_SigBit))
			done = main_event();
	}
}

/*
Function : BOOL main_event()
Purpose : A message has arrived in the main message port. It may be from the
	commodities window (hence the GT_GetIMsg) or from a note.
*/

BOOL main_event()
{
	struct IntuiMessage *msg;
	struct IntuiMessage curr_msg;

	BOOL done = FALSE;

	while (msg = (struct IntuiMessage *)GT_GetIMsg(prj->main_msg_port)) {
		curr_msg.Code = msg->Code;
		curr_msg.Class = msg->Class;
		curr_msg.Qualifier = msg->Qualifier;
		curr_msg.IAddress = msg->IAddress;
		curr_msg.MouseX = msg->MouseX;
		curr_msg.MouseY = msg->MouseY;
		curr_msg.Seconds = msg->Seconds;
		curr_msg.Micros = msg->Micros;
		curr_msg.IDCMPWindow = msg->IDCMPWindow;

		GT_ReplyIMsg ((struct IntuiMessage *)msg);

		if ((commod) && (curr_msg.IDCMPWindow == commod))
			done = commodwin_event(&curr_msg);
		else
			done = note_event(&curr_msg);

		if (done)
			break;
	}

	/* If the done was from the commod window, check to see whether it */
	/* is a quit or hide */

	if ((done) && (commod) && (curr_msg.IDCMPWindow == commod)) {
		if (!prj->abouttoquit) {
			closewindowcommod();
			done = FALSE;
		}
	}
 
	return(done);
}
