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

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
#include <string.h>
#include <emx/time.h>

#define DST_UNSET       4217

static int start_dst;
static time_t start;


static void ptime (time_t t)
{
  char *p;

  p = asctime (gmtime (&t));
  p[24] = 0;
  fputs (p, stdout);
}


static void range (time_t end)
{
  if (start_dst != DST_UNSET && start <= end)
    {
      ptime (start);
      printf (" - ");
      ptime (end);
      printf (" %d\n", start_dst);
    }
}


static void usage (void)
{
  puts ("Usage: dst1 [-z <zone>]");
  exit (1);
}


#define STEP    (5*60)

int main (int argc, char *argv[])
{
  time_t t, tmp, prev, stop;
  int i, dst;
  char *p;

  i = 1;
  while (i < argc)
    if (strcmp (argv[i], "-z") == 0)
      {
        ++i;
        if (i >= argc)
          usage ();
        p = malloc (strlen (argv[i]) + 4);
        sprintf (p, "TZ=%s", argv[i]);
        putenv (p);
        ++i;
      }
    else
      break;
  if (i != argc)
    usage ();

  tzset ();
  t = 0; prev = 0; start_dst = DST_UNSET;
  for (;;)
    {
      tmp = t;
      dst = _loc2gmt (&tmp, -1);
      if (dst != start_dst)
        {
          stop = t; t = prev;
          for (;;)
            {
              tmp = t;
              dst = _loc2gmt (&tmp, -1);
              if (dst != start_dst)
                break;
              if (t == stop)
                abort ();
              ++t;
            }
          range (t - 1);
          start = t; start_dst = dst;
        }
      prev = t;
      if (t == TIME_T_MAX)
        break;
      if (t > TIME_T_MAX - STEP)
        t += 1;
      else
        t += STEP;
    }
  range (t - 1);
  return 0;
}
