/*********************************************************
 * Gotcha library example code.
 * (c)1995 Thomas Bickel. All rights reserved.
 *
 * Monitors the list of ARexx ports available and shows
 * removed and/or added ports.
 *********************************************************/
#include <stdio.h>

#include <exec/lists.h>
#include <clib/exec_protos.h>
#include <pragmas/exec_pragmas.h>

#include <clib/gotchalib_protos.h>
#include <pragmas/gotchalib_pragmas.h>
#include <libraries/gotchalib.h>

#include <dos/dos.h>

/***********************************************************************/
void show_list(struct List *l)
{
	struct Node *nn;
	BOOL first = TRUE;

	nn = l->lh_Head;
	while (nn->ln_Succ) {
		printf(first ? " %s" : ", %s",nn->ln_Name);
		nn = nn->ln_Succ;
		first = FALSE;
	}
	puts(".");
}

int main(long argc, char *argv[])
{
	struct Library *GotchaLibBase;
	struct List *gl, *glnew, *newports=NULL, *remports=NULL, *unchanged=NULL;
	LONG	signr;
	ULONG	sigs;

	if (GotchaLibBase = OpenLibrary("gotcha.library",1)) {
		if (-1 != (signr = AllocSignal(-1))) {
			if (GL_AddNotifyTask(signr)) {
				if (gl = GL_DupGotchaPortList()) {		/* get a copy of the list */

					printf("Available Gotcha ports:");
					show_list(gl);

					puts("\nNow launch and quit Gotcha(s). Ctrl-C to quit");

					while (1) {
						sigs = Wait(SIGBREAKF_CTRL_C | (1L << signr));

						if (sigs & SIGBREAKF_CTRL_C) break;

						if (sigs & (1L << signr)) {
							if (glnew = GL_DupGotchaPortList()) {
								if (GL_GetListsDiffs(gl,glnew,&newports,&remports,&unchanged,FN_I)) {

									printf("\nPorts added:");		show_list(newports);
									printf("Ports removed:");		show_list(remports);
									printf("Ports still here:");	show_list(unchanged);

								}
							GL_FreeList(gl); gl = glnew; glnew = NULL;
							}
						}
					}

					if (newports) GL_FreeList(newports);
					if (remports) GL_FreeList(remports);
					if (unchanged) GL_FreeList(unchanged);

					GL_FreeList(gl);
				} else
					puts("Could not obtain the list!");

				GL_RemNotifyTask(signr);
			} else
				puts("Out of mem");

			FreeSignal(signr);
		} else
			puts("No signal");

		CloseLibrary(GotchaLibBase);
	} else
		puts("Could not open 'gotcha.library'!");
}
