/*
 * wild.c - wildcard expander
 *
 * S. Leoce 26 Jun 88	psj@va
 *
 * Purpose:
 *	expands wildcards in passed arg, returning the next matching name
 * 	or null when no more files match.
 *
 * Usage:
 *	initial call with the search pattern according to regular DOS
 *	rules. '*' (none or more of any character), '?' (exactly one char).
 *	subsequent calls with NULL argument to track through the directory,
 *	subroutine expects that a non-NULL argument restarts the search
 *	for a new pattern.
 *
 * Errors:
 *	None.
 */

#include <stdio.h>
#include <dir.h>

static	char * _Subroutine = "_wild - wildcard expander";

char *strcpy();
char *strrev();
char *strcat();
char *strupr();
char *strtok();

int findfirst();
int findnext();
int fnsplit();

void fnmerge();

int _FAttr ;		/* result from FNSPLIT */

char * _wild( arg )
char * arg;
{

	static char ext [MAXEXT];	/* file extension	*/
	static char dir [MAXDIR];	/* file directory	*/
	static char file [MAXFILE];	/* primary file name	*/
	static char drive [MAXDRIVE];	/* file drive specifier	*/

	static struct ffblk ffblk;	/* file control block	*/
	static char name [MAXPATH];	/* full file path	*/

	auto int done;			/* status from find	*/

	if( arg ) {
		done = findfirst( arg, &ffblk, 0 );
		_FAttr = fnsplit( arg, drive, dir, file, ext );
	}
	else
		done = findnext( &ffblk );

	if( done )
		return (NULL);

	if( _FAttr & WILDCARDS ) {

		auto char text [MAXEXT];

		strcpy( file, strtok( ffblk.ff_name, "." ) );
		strcpy( text, strtok( NULL, "." ) );
		strrev( text );
		strcat( text, "." );
		strcpy( ext, strrev( text ) );

	}
	fnmerge( name, drive, dir, file, ext );
	strupr( name );
	
	return( name );
}