#include <exec/types.h>
#include <exec/execbase.h>
#include <dos/dos.h>
#include <dos/dosextens.h>
#include <dos/dosasl.h>
#include <clib/dos_protos.h>

#include <string.h>
#include <stdio.h>

struct AnchorPath MyAp;

#define SAME 0

int main(int argc,char **argv)
{
	LONG	retval = RETURN_ERROR;
	LONG	all = FALSE;
	char	dirname[256];

	if (argc < 2 || argc > 3)
	{
usage:	    printf("Usage: %s <pattern> [all]\n",argv[0]);
	    return retval;
	}

	if (argc == 3)
	{
		if (stricmp(argv[2],"all") == SAME)
			all = TRUE;
		else
			goto usage;
	}

	printf("Searching directory tree for pattern %s\n",argv[1]);

	/* Initialize the AnchorPath structure	*/
	MyAp.ap_BreakBits = SIGBREAKF_CTRL_C; /* Break on these bits	*/

	for (retval = MatchFirst(argv[1],&MyAp);
	     retval == 0;
	     retval = MatchNext(&MyAp))
	{
		if (MyAp.ap_Flags & APF_DirChanged)
		{
			printf("Changed directories...\n");
		}

		if (NameFromLock(MyAp.ap_Current->an_Lock,dirname,
				 sizeof(dirname)) == FALSE)
		{
			PrintFault(IoErr(),"Error on NameFromLock");
			break;
		}
		if (AddPart(dirname,&(MyAp.ap_Info.fib_FileName[0]),
			    sizeof(dirname)) == FALSE)
		{
			PrintFault(IoErr(),"Error on AddPart");
			break;
		}

	/* This code section deals with ALL and directory ascent/descent */
		if (MyAp.ap_Info.fib_DirEntryType > 0)
		{
		    if (MyAp.ap_Flags & APF_DIDDIR)
		    {
			printf("Ascending from directory %s\n",dirname);

		    } else if (all) {

			printf("Entering directory %s\n",dirname);

			/* make it enter the directory */
			MyAp.ap_Flags |= APF_DODIR;

		    } else {
			printf("The next dir is  ... %s\n",dirname);
		    }

		    /* clear the completed directory flag */
		    MyAp.ap_Flags &= ~APF_DIDDIR;

		} else {
		    /* Here is code for handling each particular file */
		    printf("The next file is ... %s\n",dirname);
		}
	}

    /* This absolutely, positively must be called, all of the time. */
    MatchEnd(&MyAp);

    /* Check for error, if so, print error message */
    if (retval != ERROR_NO_MORE_ENTRIES)
    {
	printf("%s failed because Error code %ld\n",argv[0],retval);
	PrintFault(retval,NULL);
    }
}

