/*
**  Do shell-style pattern matching for ?, \, [], and * characters.
**  Might not be robust in face of malformed patterns; e.g., "foo[a-"
**  could cause a segmentation violation.
**
**  Written by Rich $alz, mirror!rs, Wed Nov 26 19:03:17 EST 1986.
*/

/* I had to modify this by renaming TRUE to VRAI and FALSE to FAUX.  The
originals were causing warnings, so I just renamed them rather than spend
a long time hunting down the problem.  It works, so what the heck?  I might
scrap this whole routine in a later version as I don't like its case sen-
sitivity. -KK */

void NoCase();

#define VRAI		1
#define FAUX		0

static int
Star(s, p)
    register char	*s;
    register char	*p;
{
    while (wildmat(s, p) == FAUX)
	if (*++s == '\0')
	    return(FAUX);
    return(VRAI);
}


int
wildmat(s, p)
    register char	*s;
    register char	*p;
{
    register int 	 last;
    register int 	 matched;
    register int 	 reverse;

    NoCase(s);
    NoCase(p);

    for ( ; *p; s++, p++)
	switch (*p) {
	    case '\\':
		/* Literal match with following character; fall through. */
		p++;
	    default:
		if (*s != *p)
		    return(FAUX);
		continue;
	    case '?':
		/* Match anything. */
		if (*s == '\0')
		    return(FAUX);
		continue;
	    case '*':
		/* Trailing star matches everything. */
		return(*++p ? Star(s, p) : VRAI);
	    case '[':
		/* [^....] means inverse character class. */
		if (reverse = p[1] == '^')
		    p++;
		for (last = 0400, matched = FAUX; *++p && *p != ']'; last = *p)
		    /* This next line requires a good C compiler. */
		    if (*p == '-' ? *s <= *++p && *s >= last : *s == *p)
			matched = VRAI;
		if (matched == reverse)
		    return(FAUX);
		continue;
	}

    return(*s == '\0');
}


void NoCase(instring)  
char *instring;
{
    while(*instring != 0)
    {
        *instring = tolower(*instring);
        instring++;
    }
}
