/****************************************************************************

	RegExp.c

	This file contains the C code for the regular expression
	matching code.

	The routines supported act as a more friendly, user level
	interface to the regexp regular expression matching system.

 ****************************************************************************/

/*
 * Author:
 * 	Brian Totty
 * 	Department of Computer Science
 * 	University Of Illinois at Urbana-Champaign
 *	1304 West Springfield Avenue
 * 	Urbana, IL 61801
 * 
 * 	totty@cs.uiuc.edu
 * 	
 */ 

#include <Xfwf/RegExp.h>
#include <regexp.h>
#include <xite/includes.h>
#include XITE_STDIO_H

#ifndef FUNCPROTO
void RegExpCompile(regexp,fsm_ptr,fsm_length)
char *regexp,*fsm_ptr;
int fsm_length;
#else /* FUNCPROTO */
void RegExpCompile(char *regexp, char *fsm_ptr, int fsm_length)
#endif /* FUNCPROTO */
{
#ifndef NO_REGEXP
	compile(regexp,fsm_ptr,&(fsm_ptr[fsm_length]),'\0');
#endif
} /* End RegExpCompile */


#ifndef FUNCPROTO
int RegExpMatch(string,fsm_ptr)
char *string,*fsm_ptr;
#else /* FUNCPROTO */
int RegExpMatch(char *string, char *fsm_ptr)
#endif /* FUNCPROTO */
{
#ifndef NO_REGEXP
	if (advance(string,fsm_ptr) != 0)
		return(TRUE);
	    else
		return(FALSE);
#else
	return(TRUE);
#endif
} /* End RegExpMatch */


#ifndef FUNCPROTO
void _RegExpError(val)
int val;
#else /* FUNCPROTO */
void _RegExpError(int val)
#endif /* FUNCPROTO */
{
	fprintf(stderr,"Regular Expression Error %d\n",val);
	exit(-1);
} /* End _RegExpError */


#ifndef FUNCPROTO
void RegExpPatternToRegExp(pattern,reg_exp)
char *pattern,*reg_exp;
#else /* FUNCPROTO */
void RegExpPatternToRegExp(char *pattern, char *reg_exp)
#endif /* FUNCPROTO */
{
	int in_bracket;

	in_bracket = 0;
	while (*pattern != '\0')
	{
		if (in_bracket)
		{
			if (*pattern == ']') in_bracket = 0;
			*reg_exp++ = *pattern++;
		}
		    else
		{
			switch (*pattern)
			{
			    case '[':
				in_bracket = 1;
				*reg_exp++ = '[';
				break;
			    case '?':
				*reg_exp++ = '.';
				break;
			    case '*':
				*reg_exp++ = '.';
				*reg_exp++ = '*';
				break;
			    case '.':
				*reg_exp++ = '\\';
				*reg_exp++ = '.';
				break;
			    default:
				*reg_exp++ = *pattern;
				break;
			}
			++ pattern;
		}
	}
	*reg_exp++ = '$';
	*reg_exp++ = '\0';
} /* End RegExpPatternToRegExp */
