/*
 * The original was spagetti. I have replaced Michael's code with some of
 * my own which is a thousand times more readable and can also handle '%',
 * which substitutes anything except a space. This should enable people
 * to position things better based on argument. I have also added '?', which
 * substitutes to any single character. And of course it still handles '*'.
 * this should be more efficient than the previous version too.
 *
 * Thus this whole file becomes:
 *
 * Written By Troy Rollo
 *
 * Copyright(c) 1992
 *
 * See the COPYRIGHT file, or do a HELP IRCII COPYRIGHT 
 */
#include <stdio.h>
#include "irc.h"
#include "reg.h"
#include "ircaux.h"

static	int	total_explicit;

/*
 * The following #define is here because we *know* its behaviour.
 * The behaviour of toupper tends to be undefined when it's given
 * a non lower case letter.
 * All the systems supported by IRCII should be ASCII
 */
#define	mkupper(c)	(((c) >= 'a' && (c) <= 'z') ? ((c) - 'a' + 'A') : c)

int	match(pattern, string)
char	*pattern,
	*string;
{
	char	type;

	while (*string && *pattern && *pattern != '*' && *pattern != '%')
	{
		if (*pattern == '\\')
		{
			if (!*++pattern || !(mkupper(*pattern) ==
					mkupper(*string)))
				return 0;
			else
				pattern++, string++, total_explicit++;
		}


		if (*pattern == '?')
			pattern++, string++;
		else if (mkupper(*pattern) == mkupper(*string))
			pattern++, string++, total_explicit++;
		else
			break;
	}
	if (*pattern == '*' || *pattern == '%')
	{
		type = (*pattern++);
		while (*string)
		{
			if (match(pattern, string))
				return 1;
			else if (type == '*' || *string != ' ')
				string++;
			else
				break;
		}
	}
	if (!*string && !*pattern)
		return 1;
	return 0;
}

/*
 * This version of wild_match returns 1 + the  count  of characters
 * explicitly matched if a match occurs. That way we can look for
 * the best match in a list
 */
int	wild_match(pattern, str)
char	*pattern,
	*str;
{
	total_explicit = 0;
	if (match(pattern, str))
		return total_explicit+1;
	else
		return 0;
}
