/* glob1.c (emx+gcc) */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include <glob.h>
#include <assert.h>


static void usage (void)
{
  puts ("Usage: glob1 [-cefmprs] [-o<offs>] <pattern> ...");
  exit (1);
}


static int my_errfun(const char *path, int err)
{
  fprintf (stderr, "my_errfun: %s: %s\n", path, strerror (err));
  return 0;                     /* Continue */
}


int main (int argc, char *argv[])
{
  glob_t g;
  int r, i, c, flags, offs;
  long n;
  char *e;
  int (*errfun)(const char *, int);

  flags = 0; g.gl_offs = 42; offs = 0; errfun = NULL;
  while ((c = getopt (argc, argv, "cefmo:prs")) != -1)
    switch (c)
      {
      case 'c':
        flags |= GLOB_NOCHECK;
        break;
      case 'e':
        flags |= GLOB_NOESCAPE;
        break;
      case 'f':
        errfun = my_errfun;
        break;
      case 'm':
        flags |= GLOB_MARK;
        break;
      case 'o':
        flags |= GLOB_DOOFFS;
        n = strtol (optarg, &e, 10);
        if (n < 0 || e == optarg || *e != 0)
          usage ();
        g.gl_offs = (size_t)n;
        offs = (int)n;
        break;
      case 'p':
        flags |= GLOB_PERIOD;
        break;
      case 'r':
        flags |= GLOB_ERR;
        break;
      case 's':
        flags |= GLOB_NOSORT;
        break;
      default:
        usage ();
      }
  if (optind >= argc)
    usage ();
  for (i = optind; i < argc; ++i)
    {
      if (i > optind)
        flags |= GLOB_APPEND;
      r = glob (argv[i], flags, errfun, &g);
      switch (r)
        {
        case 0:
          break;
        case GLOB_ABEND:
          fprintf (stderr, "Error: GLOB_ABEND\n");
          return 2;
        case GLOB_NOMATCH:
          fprintf (stderr, "Error: GLOB_NOMATCH\n");
          return 2;
        case GLOB_NOSPACE:
          fprintf (stderr, "Error: GLOB_NOSPACE\n");
          return 2;
        default:
          fprintf (stderr, "Unknwon error %d\n", r);
          return 2;
        }
    }
  for (i = 0; i < offs + g.gl_pathc; ++i)
    printf ("%s\n", g.gl_pathv[i]);
  assert (g.gl_pathv[offs+g.gl_pathc] == NULL);
  globfree (&g);
  return 0;
}
