/* fnexplod.c (emx+gcc) -- Copyright (c) 1992-1993 by Eberhard Mattes */

#include <sys/emx.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/param.h>


char **_fnexplode (const char *mask)
{
  char **list, **tmp, *p, *q;
  int a, n, i;
  struct _find find;
  char name[MAXNAMLEN];

  _rfnlwr ();
  _sfnlwr (name);
  _strncpy (name, mask, sizeof (name));
  p = q = name;
  while (*q != 0)
    {
      if (*q == ':' || *q == '\\' || *q == '/')
        p = q + 1;
      ++q;
    }
  list = NULL; n = 0; a = 0;
  if (__findfirst (mask, 0x10, &find) != 0)
    return (NULL);
  do
    {
      if (strcmp (find.name, ".") != 0 &&
          strcmp (find.name, "..") != 0)
        {
          if (n + 1 >= a)
            {
              a += 32;
              tmp = realloc (list, a * sizeof (char **));
              if (tmp == NULL)
                {
                  errno = ENOMEM;
                  goto failure;
                }
              list = tmp;
            }
          strcpy (p, find.name);
          _fnlwr (name);
          q = strdup (name);
          if (q == NULL)
            {
              errno = ENOMEM;
              goto failure;
            }
          list[n++] = q;
        }
    } while (__findnext (&find) == 0);
  if (list != NULL)
    list[n] = NULL;
  _rfnlwr ();
  return (list);

failure:            
  if (list != NULL)
    {
      for (i = 0; i < n; ++i)
        free (list[i]);
      free (list);
    }
  _rfnlwr ();
  return (NULL);
}


void _fnexplodefree (char **list)
{
  int i;

  for (i = 0; list[i] != NULL; ++i)
    free (list[i]);
  free (list);
}
