/*
 * This is an interface to the posix regular-expression matching.
 */

#include "localsys.h"

#ifdef HAVE_POSIX_REGEX

static regex_t compiled_pattern;	/* for storing a compiled pattern */
static int free_pattern = 0;		/* set !0 if a later call to p_compile()
					 * should free the compiled pattern.
					 */

static int posix_flags = 0;		/* user-specified regcomp flags */

/*
 * Specify cflags for use in future regcomp() calls.
 */
void
p_regcomp_flags(cflags)
int cflags;
{
    posix_flags |= cflags;
}

/*
 * Compile a pattern and store in compiled_pattern, above.
 * Return NULL on success, else some error string.
 */
char *
p_compile(regex)
char *regex;
{
    int i;
    static char buf[1000];

    if (free_pattern) {
	/* Free old pattern space */
	regfree(&compiled_pattern);
	free_pattern = 0;
    }

    if ((i=regcomp(&compiled_pattern, regex, posix_flags | REG_NOSUB)) != 0) {
	/* compile failed */
	regerror(i, &compiled_pattern, buf, sizeof(buf));
	return buf;
    }

    free_pattern = 1;	/* remind us to free the pattern next time. */

    return NULL;
}

int
p_compare(str)
char *str;
{
    regmatch_t pmatch[1];
    return (regexec(&compiled_pattern, str, 1, pmatch, 0) == 0);
}

#else

    /* --------- POSIX regex routines not available -----------  */

static int posix_flags = 0;

void
p_regcomp_flags(cflags)
int cflags;
{
    return;
}

char *
p_compile(regex)
char *regex;
{
    Error(0, 1, "p_compile(): POSIX regular expressions not available.\n");
    return NULL;
}

int
p_compare(str)
char *str;
{
    Error(0, 1, "p_compare(): POSIX regular expressions not available.\n");
    return NULL;
}

#endif
