/* findfile.c: Search all directories for a file */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dir.h>
#include <io.h>
#include <string.h>

/* Change these for UNIX */
#define SEPSTR "\\"
#define OFFSET 2

void visit_dirs(char *dir, char *file);

main(int argc, char *argv[])
{
    if (argc > 1)
    {
        char *file = argv[1];
        char *root = (argc > 2) ? argv[2] : SEPSTR;

        visit_dirs(root,file);
    }
    return 0;
}

void visit_dirs(char *dir, char *file)
{
    DIR *dirp;
    struct dirent *entry;
    struct stat finfo;
    char *curdir = getcwd(NULL,FILENAME_MAX);

    /* Enter the directory */
    assert(chdir(dir) == 0);
    
    /* Process current directory */
    if (access(file,0) == 0)
    {
        char *tempdir = getcwd(NULL,FILENAME_MAX);
        char *sep = strcmp(tempdir+OFFSET,SEPSTR) ?
                    SEPSTR : "";
        printf("%s%s%s\n",
               strlwr(tempdir+OFFSET),sep,strlwr(file));
        free(tempdir);
    }
    
    /* Descend into subdirectories */
    assert((dirp = opendir(".")) != NULL);
    while ((entry = readdir(dirp)) != NULL)
    {
        if (entry->d_name[0] == '.')
            continue;
        stat(entry->d_name,&finfo);
        if (finfo.st_mode & S_IFDIR)
            visit_dirs(entry->d_name,file);
    }

    /* Cleanup */
    closedir(dirp);
    chdir(curdir+OFFSET);
    free(curdir);
}


