/* demomain.c -- demonstration of Commodities popup application
 * Copyright 1988, I and I Computing, all right reserved
 * May be freely used and distributed.
 */

#include "sysall.h"

#include "cx/cxfunctions.h"

#define D(x)	;
/* #define printf	kprintf */

/* for development purposes	*/
#ifndef LIBNAME
#define LIBNAME "commodities.library"
#endif

#define CXLIBNAME LIBNAME
#define CXLIBVERS (0)

struct IntuitionBase	*IntuitionBase = NULL;
struct Library	*CxBase = NULL;

/* these globals are the connection between the main program
 * loop and the two message handling routines
 */

struct MsgPort	*cxport = NULL;	/* commodities messages here		*/
ULONG			cxsigflag = 0;	/* signal for above					*/

struct MsgPort	*iport = NULL;	/* Intuition IDCMP messages here	*/
ULONG			isigflag = 0;	/* signal for above					*/

main( argc, argv )
char	**argv;
{
	char	**ttypes;
	ULONG	sigrcvd;
	struct Message	*msg;
	struct Library	*openLibrary();

	IntuitionBase = (struct IntuitionBase *)
		openLibrary( "intuition.library", 33 );
	CxBase = openLibrary( CXLIBNAME, CXLIBVERS );

	D( printf(" opening cx: %s, %d\n", CXLIBNAME, CXLIBVERS ) );

	if ( ! ( IntuitionBase && CxBase ) ) terminate();

	/* commodities support library function to find argv or tooltypes	*/
	ttypes = ArgArrayInit( argc, argv );

	if ( ! setupCX( ttypes ) )
	{
		D( printf(" setupCX failed, terminating\n") );
		terminate();
	}

	setupWindow();			/* will try to setup iport		*/

	for (;;)				/* exit by calling terminate	*/
	{
		/* handling two ports:
		 * either will wake us up;
		 * simple approach often works.
		 */
		sigrcvd = Wait ( SIGBREAKF_CTRL_E | isigflag | cxsigflag );

		/* commodities convention: easy to kill	*/
		if ( sigrcvd & SIGBREAKF_CTRL_E ) terminate();

		while ( cxport && (msg = GetMsg( cxport )) ) handleCxMsg( msg );
		while ( iport && (msg = GetMsg( iport )) ) handleIMsg( msg );
	}

}

terminate()
{
	shutdownCX();
	shutdownWindow();

	ArgArrayDone(); 	/* cx_supp.lib function	*/

	closeLibrary( CxBase );
	closeLibrary( IntuitionBase );

	exit( 0 );
}

/*
 * might want to call an alert or something
 */
struct Library	*openLibrary( name, version )
char	*name;
{
	return ( OpenLibrary( name, (LONG) version ) );
}

closeLibrary( lib )
struct Library	*lib;
{
	if ( lib ) CloseLibrary( lib );
}
