/* ihelp.c -- cycles/activates windows and stuff like that	*/

#include	"sysall.h"
#include	"cx/cxusr.h"

#define D(x)	;

#ifndef LIBNAME
#define LIBNAME "commodities.library"
#endif

#define		CYCLE				1L
#define		CYCLEBACK			2L
#define		MAKEBIG				3L
#define		MAKESMALL			4L

struct Library	*CxBase;
struct MsgPort	*port;

struct NewBroker mynb = {
	NB_VERSION,
	"ihelper",					/* broker internal name	*/
	"IHelper",					/* commodity title		*/
	"Intuition keyboard stuff",	/* description			*/
	NBU_UNIQUE,					/* co-existence is low	*/
	0,							/* flags				*/
	0							/* default priority		*/
};

main(argc, argv)
int		argc;
char	**argv;
{
	char			**tt;		/* arg list	*/
	struct Message	*msg;
	int				exitval = 0;
	LONG			hotkeyid;
	LONG			sigmask;
	LONG			error;
	CxObj			*broker = NULL;
	struct MsgPort	*CreatePort();

	CxBase = OpenLibrary( LIBNAME, 2L);
	if (!CxBase) exit (3);

	/* get argument list	*/
	tt = ArgArrayInit(argc, argv);

	port = CreatePort(mynb.nb_Name, 0L);

	if (!ihelp_init()) goto ABORT;

	mynb.nb_Pri = ArgInt(tt, "PRIORITY", 0);

	broker = CxBroker(&mynb, NULL);
	if (!broker)
	{
		exitval = 2;
		goto ABORT;
	}
	D( printf("broker ok at %lx\n", broker) );

	AttachCxObj(broker,
		HotKey( ArgString(tt, "CYCLE", "f1"), port, CYCLE) );
	AttachCxObj(broker,
		HotKey( ArgString(tt, "MAKEBIG", "f2"),  port, MAKEBIG) );
	AttachCxObj(broker,
		HotKey( ArgString(tt, "MAKESMALL", "f3"), port, MAKESMALL) );
#if 0
	AttachCxObj(broker,
		HotKey( ArgString(tt, "CYCLEBACK", "shift f1"), port, CYCLEBACK) );
#endif

	if (error = CxObjError(broker))
	{
		D( printf("accumulated broker error %ld\n", error) );
		exitval = 4;
		goto ABORT;
	}
	ActivateCxObj(broker, 1L);

	D( printf("ihelp all ready to go\n") );

	sigmask = SIGBREAKF_CTRL_E | (1L << port->mp_SigBit);
	while (1)
	{
		msg = GetMsg( port );
		if( ! msg )
		{
			if( (Wait( sigmask ) & SIGBREAKF_CTRL_E) == SIGBREAKF_CTRL_E )
			{
				D( printf("got break\n") );
				exitval = 1;
				goto GOT_BREAK;
			}
			continue;
		}
		hotkeyid = CxMsgID(msg);
		D( printf("got msg, hotkeyid = %lx\n", hotkeyid) );

		ReplyMsg( msg );

		switch ( hotkeyid )
		{
		case	CYCLE:
			D( printf("cycleforward\n") );
			cycleforward();
			break;
		case	CYCLEBACK:
			D( printf("cycleback\n") );
			cyclebackward();
			break;
		case	MAKEBIG:
			D( printf("makebig\n") );
			makesize((int) MAKEBIG);
			break;
		case	MAKESMALL:
			D( printf("makesmall\n") );
			makesize((int) MAKESMALL);
			break;
		}
	}

GOT_BREAK:
ABORT:
	if (broker)
	{
		DeleteCxObjAll(broker);
		while (msg = GetMsg(port)) ReplyMsg(msg);
	}
	CloseLibrary(CxBase);

	ihelp_shutdown();
	DeletePort(port);

	ArgArrayDone();

	exit (exitval);
}
