/*
	expand.c
*/

#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <dos.h>


typedef	char	bool;
#define	YES	1
#define	NO	0


#define	iskanji(c)	('\x81'<=(c)&&(c)<='\x9f' || '\xe0'<=(c)&&(c)<='\xfc')
#define	iskanji2(c)	('\x40'<=(c)&&(c)<='\x7e' || '\x80'<=(c)&&(c)<='\xfc')


/***#pragma nonrec***/


/*	directory search	*/

static	int	_cmp(p, q)
char	**p, **q;
{
	return (strcmp(*p, *q));
}


static	char	*_dirof(char *buf, char *s)
{
	char	*p, *r, c;

	r = p = buf;
	while (c = *s++) {
		*p++ = c;
#ifdef	MSKANJI
		if (iskanji(c) && iskanji2(*s))
			*p++ = *s++;
		else
#endif
		if (c == ':' || c == '\\' || c == '/')
			r = p;
	}
	*r = '\0';
	return (buf);
}



int	_expand(char *pat, int maxargc, char *xargv[])
{
	struct	find_t	f;
	char	fn[100];
	unsigned c;
	int	xargc;

	xargc = 0;
	c = _dos_findfirst(pat, _A_NORMAL | _A_RDONLY | _A_SUBDIR, &f);
	for (; c == 0; c = _dos_findnext(&f)) {
		if (strcmp(f.name, ".") == 0 || strcmp(f.name, "..") == 0)
			continue;
		strcat(_dirof(fn, pat), f.name);
		if (xargc >= maxargc || (xargv[xargc++] = strdup(fn)) == NULL)
			return (-1);
	}
	qsort(xargv, xargc, sizeof(char *), _cmp);
	return (xargc);
}
