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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <io.h>
#include <getopt.h>

static char *pmode (int m)
{
  static char buf[16], *p;
  int i, n;

  switch (m & S_IFMT)
    {
    case S_IFREG:
      buf[0] = ' ';
      break;
    case S_IFDIR:
      buf[0] = 'd';
      break;
    default:
      buf[0] = '?';
      break;
    }
  p = buf+1; n = m & 0777;
  for (i = 0; i < 3; ++i)
    {
      *p++ = (n & S_IREAD  ? 'r' : '-');
      *p++ = (n & S_IWRITE ? 'w' : '-');
      *p++ = (n & S_IEXEC  ? 'x' : '-');
      n <<= 3;
    }
  buf[10] = 0;
  return buf;
}


int main (int argc, char *argv[])
{
  time_t t;
  time_t zero;
  int c, i, inp_flag, sleep_sec, sleep_millisec;
  struct stat s;
  struct tm *tm_p;
  char fs[16], buf[256];

  inp_flag = 0; sleep_sec = -1; sleep_millisec = -1;
  while ((c = getopt (argc, argv, "im:s:")) != -1)
    switch (c)
      {
      case 'i':
        inp_flag = 1;
        break;
      case 'm':
        sleep_millisec = atoi (optarg);
        break;
      case 's':
        sleep_sec = atoi (optarg);
        break;
      }
  for (i = optind; i < argc; ++i)
    {
      if (isalpha ((unsigned char)argv[i][0])
          && argv[i][1] == ':' && argv[i][2] == 0)
        {
          if (_filesys (argv[i], fs, sizeof (fs)) != 0)
            perror (argv[i]);
          else
            printf ("File-system driver=%s\n", fs);
        }
      else if (stat (argv[i], &s) == 0)
        {
          printf ("%s:\n", argv[i]);
          printf ("  dev=%d ino=%d mode=0%o \"%s\" nlink=%d\n",
                  (int)s.st_dev, (int)s.st_ino, (int)s.st_mode,
                  pmode ((int)s.st_mode), (int)s.st_nlink);
          printf ("  uid=%d gid=%d rdev=%d size=%d\n",
                  (int)s.st_uid, (int)s.st_gid, (int)s.st_rdev,
                  (int)s.st_size);
          printf ("  atime=%s", ctime (&s.st_atime));
          printf ("  mtime=%s", ctime (&s.st_mtime));
          printf ("  ctime=%s", ctime (&s.st_ctime));
          printf ("  attr=0x%.2lx\n", s.st_attr);
        }
      else
        perror (argv[i]);
    }
  if (sleep_sec >= 0)
    sleep (sleep_sec);
  if (sleep_millisec >= 0)
    _sleep2 (sleep_millisec);
  zero = 0;
  time (&t);
  printf ("timezone  = %ld\n", timezone);
  printf ("daylight  = %d\n", daylight);
  printf ("tzname[0] = %s\n", tzname[0]);
  printf ("tzname[1] = %s\n", tzname[1]);
  printf ("time      = %ld\n", (long)t);
  printf ("clock     = %ld\n", (long)clock ());
  tm_p = gmtime (&zero);
  printf ("epoch:      %s", asctime (tm_p));
  tm_p = gmtime (&t);
  printf ("GMT:        %s", asctime (tm_p));
  printf ("ctime     = %s", ctime (&t));
  if (inp_flag)
    {
      printf ("Time: ");
      if (fgets (buf, sizeof (buf), stdin) == NULL)
        return 0;
      t = strtoul (buf, NULL, 10);
      printf ("ctime = %s", ctime (&t));
    }
  return 0;
}
