/*---------------------------------------------------------------*/
/*   Copyright (c) 1988 Regents of the University of California  */
/*                 All Rights Reserved                           */
/*---------------------------------------------------------------*/
/*
      @(#)findfile.c	1.1   (UCLA/IGPP)   11 Dec 1992
 */
/*-- FINDFILE -----------------------------------------------------*/
/*  Searches for the given file name on any of the given paths.    */
/*  Returns when a match is found. Globbing is done on the file    */
/*  name which is passed.                                          */
/*                                                                 */
/* Returns:                                                        */
/*   NOACCES: if the name could not be found along any path        */
/*            otherwise, the file type of the found file           */
/*                                                                 */
/*  Entry Requirements:                                            */
/*    FNAME: the name of the file to search for.                   */
/*    PATHLIST: an array of strings which specify the paths to     */
/*              search. If its a directory all directory name      */
/*              deliminators must be present.                      */
/*    FOUND_NAME: the string to place the found name in.           */
/*    FTYPE: A composite flag of the allowed values in the         */
/*           include file 'filetype.h'.                            */
/*                                                                 */
/*  Developement History:                                          */
/*    Begun: 03/02/87 - Todd King                                  */
/*                   Under GG44 support                            */
/*-----------------------------------------------------------------*/
#ifndef _MSDOS
#include <sys/file.h>
#endif               
#include <string.h>
#include "filetype.h"

findfile(fname, pathlist, found_name, ftype)
char *fname;
char *pathlist[];
char *found_name;
int ftype;
{
  char **glob();

  int i;
  static char fullpath[512];
  int pathlen;
  char **nlist;

  i = 0;
  while(strlen(pathlist[i]) != 0)
  {
    strcpy(fullpath, pathlist[i]);
    pathlen = strlen(fullpath);
    if(pathlen > 0 && fullpath[pathlen - 1] != '/') {	
       /* Add seperator */
       strcat(fullpath, "/");
    }
    strcat(fullpath, fname);
    if((nlist = glob(fullpath)) != (char **)0)  /* If no error in glob */
    {
      int ft, j, m;

      j = 0;
      while(nlist[j] != (char *)0) j++; /* determine number of elements */
      m=0;
      while(m<j)		/* Find matching file and filetype */
      {
	ft = filetype(nlist[m])&ftype;
	if(ft)
        {
	  strcpy(found_name, nlist[m]);
	  return(ft);
	}
	m++;
      }
    }
    i++;
  }
  return(NOACCESS);
}
