#include <exec/memory.h>
#include <clib/dos_protos.h>
#include <clib/exec_protos.h>
#include <clib/misc_protos.h>
#include <pragmas/exec_sysbase_pragmas.h>
#include <pragmas/misc_pragmas.h>
#include <pragmas/dos_pragmas.h>
#include <resources/misc.h>
#include <dos/dos.h>

#include <devices/input.h>
#include <devices/inputevent.h>
#include "newmouse.h"

struct Library *DOSBase, *SysBase, *MiscBase;
struct MsgPort *replyport;
struct IOStdReq *req;
struct InputEvent FakeEvent;

ULONG rc;
ULONG code;

#define COORD *((STRPTR)0xdff00c)

void event(LONG);

__saveds main()
{
	SysBase = *((struct Library **)4L);
	rc = 20;
	if(DOSBase = OpenLibrary("dos.library",36))
	{
		if(replyport = CreateMsgPort()) // ReplyPort for time requests
		{
			if(req = CreateIORequest(replyport,sizeof(struct IOStdReq)))
			{
				if(!OpenDevice("input.device",NULL,(struct IORequest *)req,NULL))
				{

					BYTE CurrByte, LastByte = COORD;
					LONG diff;
					while(!CheckSignal(0xf000))
					{
						Delay(2);
						CurrByte = COORD;
						diff = (BYTE)(CurrByte - LastByte);
						if(diff)
						{
							code = NM_WHEEL_UP;
							if(diff<0)
							{
								code = NM_WHEEL_DOWN;
								diff = -diff;
							}
							while(diff--)
							{
								event(IECLASS_RAWKEY);
								event(IECLASS_NEWMOUSE);
							}
							LastByte=CurrByte;
						}
					}
					CloseDevice((struct IORequest *)req);
				}
				else
				{
					Printf("Can't open input.device\n");
				}
				DeleteIORequest(req);
			}
			else
			{
				Printf("Can't create IORequest\n");
			}
			DeleteMsgPort(replyport);
		}
		else
		{
			Printf("Can't create msgport\n");
		}
		CloseLibrary(DOSBase);
	}
	return(rc);
}

void event(LONG class)
{
	FakeEvent.ie_NextEvent = NULL;
	FakeEvent.ie_Class = class;
	FakeEvent.ie_Code = code;
	FakeEvent.ie_Qualifier = NULL;
	req->io_Data = (APTR)&FakeEvent;
	req->io_Length = sizeof(struct InputEvent);
	req->io_Command = IND_WRITEEVENT;
	DoIO((struct IORequest *)req);
}
