/* ARIADNE V.1.0



 Copyright 

 Richard Mott 2000
 
 Wellcome Trust Centre For Human Genetics
 Roosevelt Drive
 Oxford OX3 7AD
 

*/

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

/* some functions for opening a file in a file search path */
/* return value is the FILE pointer to the opened file, or NULL
   BaseName is the name of the file without Directory
   mode is the file open mode cf fopen
   searchpath is the colon-separated search path
   fullname is the name of the file successfully opened, or NULL 
   env is an environment variable containing the search path
*/

FILE *OpenFileInSearchPath(char *BaseName, char *mode, char *searchpath, char *fullname )
{
  FILE *fp=NULL;
  /*char buf[512];*/

  if ( searchpath ) /* if search path defined... */
    {
      char *s = strdup(searchpath);
      char *p = strtok(s,":");
      while ( p )
	{
	  sprintf(fullname,"%s/%s", p, BaseName );
	  if ( (fp = fopen(fullname,mode)) )
	    break;
	  p = strtok(NULL,":");
	}
      free(s);
    }

  if ( ! fp ) /* try to open in cwd */
    {
      strcpy( fullname, BaseName );
      fp = fopen(BaseName,mode);
    }

  if ( ! fp )
    *fullname = 0;

  return fp;
}

/* open a file in a search path specified by the environment variable env */

FILE *OpenFileInEnvPath(char *BaseName, char *mode, char *env, char *fullname )
{
  return OpenFileInSearchPath( BaseName, mode, getenv(env), fullname );
}

