#include <exec/types.h>
#include <workbench/startup.h>
#include <string.h>
#include "/include/GTDriverMPC.h"

#include <proto/exec.h>
#include <proto/dos.h>

void CloseAll(char *msg);
short SendCommand(ULONG comm, ULONG data);
void exit(int);

struct MsgPort *myport = NULL,*port = NULL,*repport = NULL;
struct TabletCommand Tcmd;
ULONG  Temp;

main(int argc, char **argv)
{
	short ret;
	char *butname;
	char buff[256];

	/*
	 * Create message port to get messages from driver
	 */
	myport = CreateMsgPort();
	if (! myport) CloseAll("Unable to create message port\n");

	/*
	 * Create Msg port to receive replies to command sent to the driver
	 */
	repport = CreateMsgPort();
	if (! repport) CloseAll("Unable to create message port\n");


	/*
	 * Get PButton file name
	 */

	 /* started from WB */
	if (argc == 0) {
		if (((struct WBStartup *)argv)->sm_NumArgs >= 2) {
			if (! NameFromLock(((struct WBStartup *)argv)->sm_ArgList[1].wa_Lock,buff,256))
				CloseAll("Error: unable to get full filename\n");
			else
				AddPart(buff,((struct WBStartup *)argv)->sm_ArgList[1].wa_Name,256);
			butname = buff;
		}
		else
			return;
	}
	else {
		if (argc >= 2)
			butname = argv[1];
		else
			return;
	}

	/*
	 * Send command to driver: Use a new Pbutton file
	 */

	ret  = SendCommand(MPC_NEWBUTTONS,(ULONG )butname);
	if(ret == NO_PUBPORT) CloseAll("Unable to find "GTDPUBPORTNAME".\n");
	else if (ret == COMMAND_FAILED) CloseAll("Unable to use new Pbutton file.\n");
	CloseAll(NULL);
}

short SendCommand(ULONG comm, ULONG data)
{
	/*
	 * Initialize the TabletCommand structure to set GTDriver to
	 * work sending data to this program (to myport).
	 */
	Tcmd.msg.mn_Node.ln_Type = NT_MESSAGE;
	Tcmd.msg.mn_ReplyPort = repport;
	Tcmd.msg.mn_Length = sizeof(struct TabletCommand);
	Tcmd.Command = comm;
	Tcmd.Data = (void *)data;

	/*
	 * Search the GTDriver message port and set it to use my message port
	 */
	Forbid();
	port = FindPort(GTDPUBPORTNAME);
	if (! port){
		Permit();
		return NO_PUBPORT;
	}
	PutMsg(port,(struct Message *)&Tcmd);
	Permit();
	WaitPort(repport);
	GetMsg(repport);
	return (short )Tcmd.Command;
}

void CloseAll(char *msg)
{
	if (msg) Printf(msg);
	if (repport) DeleteMsgPort(repport);
	if (myport) DeleteMsgPort(myport);
	exit(0);
}