/* The original version of this program can be found at http://damb.dk */
#include <dir.h>
#include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <string.h>
#include <time.h>
#include <locale.h>

void scan(char *dir, const char *pattern, int sub, const char *Format)
{
  struct _finddata_t fileinfo;
  long handle;
  char temp[1024];

  /* First parse any files in this directory */
  sprintf(temp, "%s\\%s", dir, pattern);
  handle = _findfirst(temp, &fileinfo);
  if(handle != -1)
  {
    do
    {
      if(!(fileinfo.attrib & _A_SUBDIR))
      {
        char a_time[128];
        char c_time[128];
        char w_time[128];
        char sub[1024];

        strftime(a_time, sizeof(a_time), Format, localtime(&fileinfo.time_access));
        strftime(w_time, sizeof(a_time), Format, localtime(&fileinfo.time_write));
        strftime(c_time, sizeof(a_time), Format, localtime(&fileinfo.time_create));
        sprintf(sub, "%s\\%s", dir, fileinfo.name);
        printf("%s, %s, %s, %s, %dn", sub, a_time, w_time, c_time, fileinfo.size);
      }
    }
    while(_findnext(handle, &fileinfo) == 0);
    _findclose(handle);
  }
  if(sub)
  {
    /* Then parse all sub directories */
    sprintf(temp, "%s\\*.*", dir);
    handle = _findfirst(temp, &fileinfo);
    if(handle != -1)
    {
      do
      {
        if((fileinfo.attrib & _A_SUBDIR) && strcmp(fileinfo.name, ".") && strcmp(fileinfo.name, ".."))
        {
          char sub[1024];
          sprintf(sub, "%s\\%s", dir, fileinfo.name);
          scan(sub, pattern, 1, Format);
        }
      }
      while(_findnext(handle, &fileinfo) == 0);
      _findclose(handle);
    }
  }
}

void usage(const char *ProgramName)
{
  fprintf(stderr, "Usage: %s [-s] [-fformat] [pattern1 [pattern2 [...]]]n", ProgramName);
  fprintf(stderr, "  -s       Scan thru subdirectoriesn");
  fprintf(stderr, "  -fformat Date/Time format in strftime style, default is %%x %%Xn");
  fprintf(stderr, "  pattern  e.g. *.* *.jpg adir.*n");
  exit(EXIT_FAILURE);
}

int main(int argc, char *argv[])
{
  char Dir[1024];
  char Format[1024] = "%x %X";
  int i, DoSub = 0, FoundPattern = 0;

  getcwd(Dir, sizeof(Dir));
  setlocale(LC_ALL, "");

  for(i = 1; i < argc; i++)
  {
    if(argv[i][0] == '-')
    {
      switch(argv[i][1])
      {
        case 's':
          DoSub = 1;
          argv[i][0] = 0;
          break;
        case 'f':
          if(argv[i][2])
          {
            strcpy(Format, &argv[i][2]);
            argv[i][0] = 0;
          }
          else
            usage(argv[0]);
          break;
        default:
          fprintf(stderr, "Unknown switch: %sn", argv[i]);
          /* No break; */
        case 'h':
          usage(argv[0]);
          break;
      }
    }
  }
  for(i = 1; i < argc; i++)
  {
    if(argv[i][0])
    {
      scan(Dir, argv[i], DoSub, Format);
      FoundPattern = 1;
    }
  }
  if(!FoundPattern)
    scan(Dir, "*.*", DoSub, Format);

  return EXIT_SUCCESS;
}