/* unixwild.c
 * Unix (tm) wildcard support routines. 
 * Created on 08/07/87
 */

/* Text a filename for wildcard content.
 * Called with:
 *		name:		pathname
 * Returns:
 *		0 => no wild characters
 *		1 => 1 or more wild characters
 */
int
iswild(name)
	char *name;
{
	register char c, *s;

	for (s = name; c = *s++; )
		if (c == '*' || c == '?') return 1;

	return 0;
}


/*
 * Compare a wild card name with a normal name.
 * Called with:
 *		wild:		name with "wild" content
 *		name:		"normal" name
 * Returns:
 *		0 => names don't match
 *		1 => names match
 *
 * This source was lifted from Steve Drew's version of Matt Dillon's
 * shell, version 2.06m.
 * 
 */

#define MAXB   8

int
wildcmp(wild,name)
	char *wild,*name;
{
	register char  *w = wild;
	register char  *n = name;
	char   *back[MAXB][2];
	register char   s1,s2;
	int     bi = 0;

	while (*n || *w){
		switch (*w){
			case '*': 
				if (bi == MAXB){
#ifdef DEBUG
					printf("Too many levels of '*'\n");
#endif
					return (0);
				}
				back[bi][0]= w;
				back[bi][1]= n;
				++bi;
				++w;
				continue;
		goback: 
				--bi;
				while (bi >= 0 && *back[bi][1]== '\0')
					--bi;
				if (bi < 0)
					return (0);
				w = back[bi][0]+ 1;
				n = ++back[bi][1];
				++bi;
				continue;
			case '?': 
				if (!*n){
					if (bi)
						goto goback;
					return (0);
				}
				break;
			default: 
				s1 = (*n >= 'A' && *n <= 'Z')?*n - 'A' + 'a' :*n;
				s2 = (*w >= 'A' && *w <= 'Z')?*w - 'A' + 'a' :*w;
				if (s1 != s2){
					if (bi)
						goto goback;
					return (0);
				}
				break;
		}
		if (*n)
			++n;
		if (*w)
			++w;
	}
	return (1);
}
#ifdef DEBUG
char normal[81], wild[81];
main()
{
	puts("Terminate this program by entering 'quit'");
	for (;;) {
		puts("Enter the non-wild pathname:");
		gets(normal);
		if (!strcmp(normal,"quit")) break;
		if (iswild(normal)) {
			puts("No, idiot!  Enter a non-wild filename!");
			continue;
		}
		puts("Enter a wild pathname:");
		gets(wild);
		if (wildcmp(wild,normal))
			puts("Yup, they match.");
		else
			puts("No match here.");
	}
}
#endif
