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

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <time.h>
#include <sys/dirtree.h>
#include <sys/param.h>


static int debugging = 0;
static int full_name = 0;
static int show_size = 0;
static int show_time = 0;

static char path[MAXPATHLEN+1];

static void list (struct _dt_node *p, int level, int len)
{
  struct tm *tp;
  int i;

  while (p != NULL)
    {
      if (show_size)
        printf ("%10ld  ", p->size);
      if (show_time)
        {
          tp = localtime (&p->mtime);
          printf ("%.4d/%.2d/%.2d %.2d:%.2d:%.2d  ",
                  tp->tm_year + 1900, tp->tm_mon + 1, tp->tm_mday,
                  tp->tm_hour, tp->tm_min, tp->tm_sec);
        }
      if (full_name)
        {
          path[len] = 0;
          printf ("%s%s\n", path, p->name);
        }
      else
        printf ("%*s%s\n", level*2, "", p->name);
      if (p->sub != NULL)
        {
          if (full_name)
            {
              i = strlen (p->name);
              memcpy (path+len, p->name, i);
              path[len+i] = '/';
              i += len + 1;
            }
          else
            i = 0;
          list (p->sub, level+1, i);
        }
      p = p->next;
    }
}


static void usage (void)
{
  fputs ("Usage: dttest [-fst] <filespec>\n", stderr);
  exit (1);
}


int main (int argc, char *argv[])
{
  char dir[MAXPATHLEN+1];
  char mask[MAXPATHLEN+1];
  struct _dt_tree *dt;
  int c;

  opterr = 0;
  while ((c = getopt (argc, argv, "dfst")) != -1)
    switch (c)
      {
      case 'd':
        debugging = 1;
        break;
      case 'f':
        full_name = 1;
        break;
      case 's':
        show_size = 1;
        break;
      case 't':
        show_time = 1;
        break;
      default:
        usage ();
      }
  if (argc - optind != 1)
    usage ();
  if (_dt_split (argv[optind], dir, mask) != 0)
    perror (argv[1]);
  if (debugging)
    {
      printf ("dir:  %s\n", dir);
      printf ("mask: %s\n", mask);
    }
  dt = _dt_read (dir, mask, _DT_TREE|_DT_NOCPDIR);
  if (dt == NULL)
    perror (argv[optind]);
  else
    {
      _dt_sort (dt, "fnest");
      list (dt->tree, 0, 0);
      _dt_free (dt);
    }
  return 0;
}
