
#include "yodl.h"
#include "config.h"

/* local function that returns colon separated paths by index */
/* 
   Example:  Suppose name = "A:BCD:EFGH", then

   next_path(name, 0) would return "A"
   next_path(name, 1) would return "BCD"
   next_path(name, 2) would return "EFGH"
   next_path(name, 3) would return NULL

   Function added/modified by 

   Steve Fuhrman                                     Work  : 214-860-6837
   i2 Technologies, Inc.                             Fax   : 214-860-6432
   909 East Las Colinas Blvd. 12th floor
   Irving, Texas 75039                               E-Mail: steve_fuhrman@i2.com

   Inserted into the Yodl sources by FBB 971025.

 */

static char *
next_path (char const *name, int *pathindex)
{
  char *
    tmp_path = NULL;
  int
    i, n, colons, start_path, end_path;

  n = strlen (name);

  /* Find path indicated (paths separated by colon) */

  colons = 0;
  start_path = 0;
  end_path = n - 1;

  for (i = 0; i < n; i++)
    {
      if (name[i] == ':')
	{
	  colons++;
	  end_path = i - 1;

	  if (colons == *pathindex)
	    {
	      /* found it */
	      for (i = start_path; i <= end_path; i++)
		tmp_path = str_addchar (tmp_path, name[i]);

	      return (tmp_path);
	    }

	  start_path = i + 1;	/* remember start of new path */
	}
    }

  /* If no colons and we want the first path, return a copy of the whole path */
  if ((colons == 0) && (*pathindex == 1))
    {
      tmp_path = xstrdup (name);
    }
  else if (colons == (*pathindex - 1))
    {
      /* If colons found and we want the last path, return a copy of the last
         part of the path */

      for (i = start_path; i < n; i++)
	tmp_path = str_addchar (tmp_path, name[i]);
    }

  return (tmp_path);
}

char *
file_expandname (char const *name)
{
  char
   *bareext, *dirext;
  int
    pathindex;

  if (file_isfile (name))	/* file as-is */
    return (xstrdup (name));

  bareext = xstrdup (name);
  bareext = str_concat (bareext, DEFAULT_EXT);	/* supply extension */
  if (file_isfile (bareext))
    return (bareext);

  free (bareext);		/* prefix with dir */

  pathindex = 1;		/* start with first path */

  while ((dirext = next_path (stdinclude, &pathindex)))
    {
      dirext = str_addchar (dirext, '/');
      dirext = str_concat (dirext, name);
      if (file_isfile (dirext))
	return (dirext);

      dirext = str_concat (dirext, DEFAULT_EXT);	/* add extension */
      if (file_isfile (dirext))
	return (dirext);

      free (dirext);
      pathindex++;		/* look for the next path in stdinclude */
    }

  return (xstrdup (name));
}
