/* Copyright (C) 1986,1987 Manx Software Systems, Inc.  */

/* not exactly re-entrant, is it?  it does make a simple directory scanner though */

#define MAXNAMELEN 256

static struct AnchorPath *	_ap = NULL;

char *				scdir(char *pat);
static struct AnchorPath *	findfirst(char *path);
static struct AnchorPath *	findrtn(ULONG rc);
static struct AnchorPath *	allocap(VOID);

#define findnext() (findrtn(FindNext(_ap)))

	/* Olsen: these two defines were MISSING - nothing worked! */

#define	SET_ID(t,i)	((SHORT *) t)[-1]=i
#define arpisdir(ap)	(ap -> ap_Info . fib_DirEntryType > 0)

char *
scdir(char *pat)
{
	struct AnchorPath *ap;
	static char time = 0;

	Chk_Abort();

	do
	{
		/* new pattern */

		if(!time)
		{
			time = 1;
			ap = findfirst(pat);
		}
		else	/* continue pattern */
			ap = findnext();
	}
	while(ap && arpisdir(ap));

		/* no more (return null) */

	if(!ap)
	{
		time = 0;
		return(NULL);
	}

	return(ap -> ap_Buf);	/* return ptr to name */
}

static struct AnchorPath *
findfirst(char *path)
{
	if(!_ap)
		if(!allocap())
			return(NULL);

	return(findrtn(FindFirst(path,_ap)));
}

static struct AnchorPath *
findrtn(ULONG rc)
{
	switch(rc)
	{
		case 0:
			return(_ap);

		case ERROR_BREAK:
			_abort();

		case ERROR_NO_MORE_ENTRIES:
			errno = 0;
			break;

		default:
			errno = rc;
			break;
	}

	FreeAnchorChain(_ap);

	return(NULL);
}

static
struct AnchorPath *
allocap()
{
	struct AnchorPath *ap = NULL;

	if(ap = ArpAlloc(sizeof(struct AnchorPath) + MAXNAMELEN))
	{
		SET_ID(ap,TRAK_ANCHOR);

		if(Enable_Abort)
			ap -> ap_BreakBits = SIGBREAKF_CTRL_C;

		ap -> ap_StrLen = MAXNAMELEN;

		_ap = ap;
	}
	else
		errno = ENOMEM;

	return(ap);
}
