/*	sMOVIEmouse.c	watches mouse movements so user can control sMOVIE
	Martin J. Round. 15-Oct-89
*/

#include "sMOVIE.h"

MOUSE_INFO mouseinfo;

extern int delay;

/*	input handler subroutine - called through the handler stub	*/

struct InputEvent *myhandler(ev, mptr)

struct InputEvent *ev;			/*	a pointer to a list of events		*/
register MOUSE_INFO *mptr;		/*	a pointer to my data				*/

{
	register struct InputEvent *ep;

	/*	look through the list of events for mouse information	*/
	for (ep = ev; ep; ep = ep->ie_NextEvent) {
		if (ep->ie_Class == IECLASS_RAWMOUSE) {
			mptr->ypos += ep->ie_Y;
			switch(ep->ie_Code) {
				case IECODE_LBUTTON:		/*	pause on/off toggle	*/
					if(mptr->button >= 0)
						mptr->button = 1 - mptr->button;
					break;
				case IECODE_RBUTTON:		/*	abort program		*/
					mptr->button = -1;
					break;
				}
			}
		}

	/*	any other input handlers (e.g. intuition) won't see a thing!	*/
	/*	to let them run as normal return (ev) instead of null.			*/

	return(NULL);
	
}	/*	end of myhandler	*/

extern struct IOStdReq *CreateStdIO();

extern struct MsgPort  *CreatePort();

extern void	HandlerInterface();	/*	assembly language sMOVIEstub.a	*/

struct MsgPort *inputDevPort;

struct IOStdReq *inputRequestBlock;

struct Interrupt handlerStuff;


int mousemonitor() {	
	
	do {
		if (mouseinfo.button >0 ) 
			WaitTOF();				/*	allow input task to work	*/

		while (mouseinfo.ypos > MOUSETHRESHOLD) {
			mouseinfo.ypos -= MOUSETHRESHOLD;
			if (delay < MAXDELAY) {
				++delay;
				SetTaskPri(FindTask(NULL),21);
				}
			}

		while (mouseinfo.ypos < -MOUSETHRESHOLD) {
			mouseinfo.ypos += MOUSETHRESHOLD;
			if (delay > MINDELAY) {
				--delay;
				if (delay == 0)
					SetTaskPri(FindTask(NULL),20);
				}
			}
		} while (mouseinfo.button > 0);	/*	holding left button pauses	*/

	return (mouseinfo.button < 0);	/*	right button aborts program		*/

}	/*	end of mousemonitor	*/

int initmousemonitor() {	/*	returns 0 if successful	*/

	if ((inputDevPort = CreatePort(0,0)) == NULL)
		return(-1);

	if ((inputRequestBlock = CreateStdIO(inputDevPort)) == NULL) {
		DeletePort(inputDevPort);
		return (-1);
		}

	handlerStuff.is_Data =  (APTR)&mouseinfo;
	handlerStuff.is_Code = HandlerInterface;
	handlerStuff.is_Node.ln_Pri = 52;

	mouseinfo.ypos = mouseinfo.button = 0;

	if (OpenDevice("input.device",0,(struct IORequest *)inputRequestBlock,0)) {
		DeleteStdIO(inputRequestBlock);
		DeletePort(inputDevPort);
		return (-1);
		}

	inputRequestBlock->io_Command = IND_ADDHANDLER;
	inputRequestBlock->io_Data    = (APTR)&handlerStuff;

	DoIO((struct IORequest *)inputRequestBlock);
	
	return (0);

}	/*	end of initmousemonitor		*/


void removemousemonitor() {

	inputRequestBlock->io_Command = IND_REMHANDLER;
	inputRequestBlock->io_Data = (APTR)&handlerStuff;

	DoIO((struct IORequest *)inputRequestBlock);

	CloseDevice((struct IORequest *)inputRequestBlock);

	DeleteStdIO(inputRequestBlock);

 	DeletePort(inputDevPort);

}	/*	end of removemousemonitor	*/