/* This is only a very simple program which allows you to test the pattern
   routines. Additionally, you see how to use the pattern.library in your
   own programs.
*/

/*
** DICE: LibMain:       dcc -2.0 -proto -mRR -ms -mS LibMain.c pattern_lib.lib -o LibMain
**       LibMainNoCase: dcc -2.0 -proto -mRR -ms -mS -D NOCASE LibMain.c pattern_lib.lib -o LibMainNoCase
*/

#include <exec/types.h>
#include <clib/exec_protos.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "pattern.h"

/*
#define NOCASE ... to create the program "LibMainNoCase"
*/


/* Base of the pattern.library */

void *PatternBase;


/* Prototypes of the functions defined and used below */

void printerror (LONG);
void main (int, char **);



/* Writes the errormessage, that belongs to the number "err" to stdout */

void printerror (err)
LONG err;
{
	char buffer[80];

	printf ("Error: %s\n", PatternErrorString (err, "default", buffer, sizeof (buffer)));
}


/* Let's start here! */

void main (argc, argv)
int argc;
char **argv;
{
	char s[512];	/* The strings to match should not be longer than 511 Bytes */
	char p[512];	/* The pattern should not be longer than 511 Bytes */
	LONG pm;
	LONG ec;

	/* Is there a pattern.library with version 5 or higher? */

	if (!(PatternBase=(struct Library *) OpenLibrary (PATLIB_NAME, PATLIB_MIN_VERSION))) {
		printf ("%s V%ld not found!\n", PATLIB_NAME, PATLIB_MIN_VERSION);
		exit (5L);
	}

	printf ("The Pattern => ");
	scanf ("%s", p);
	printf ("\nCompiling pattern %s\n", p);

#ifdef NOCASE
	if ((pm=AllocPatternNoCase (p, 0L)) > 0L) {
#else
	if ((pm=AllocPattern (p, 0L)) > 0L) {
#endif
		printf ("Please enter now the strings you want to match.\n");
		printf ("Enter '-q' or '+q' to quit!\n");

		do {
			printf ("? ");
			scanf ("%s", s);
			ec=MatchThePattern (pm, ((s[0]=='+') || (s[0]=='-')) ? &s[1] : s);
			switch (ec) {
				case 1L:
					/* Match found! */
					printf (":-%c\t\t%s\n", (s[0]=='+') ? ')' : (s[0]=='-') ? 'þ' : '?', s);
					break;
				case 0L:
					/* No match found! */
					printf (":-%c\t\t\t\t\t%s\n", (s[0]=='-') ? ')' : (s[0]=='+') ? 'þ' : '?', s);
					break;
				default:
					/* Ups. There was an error during matching the pattern */
					printerror (ec);
			}
		} while (stricmp (s, "q") && stricmp (&s[1], "q"));
		FreePattern (pm);
	}
	else
		printerror (pm);

	/* Please don't forget this! */
	CloseLibrary (PatternBase);
	exit (0L);
}
