/*+JMJ
 *	ZOTIME - Print date and time in user's local time zone
 *	Copyright 2011 David Meyer <papa@twenex.org>
 *
 *      TOPS-20 DAYTIME prints only the time in host's local
 *      time without zone designation.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "krcompat.h"

#define INIFILE "zotime.ini"
#define DEFAULT_OFFSET "0"

void print_zotime PARAMS((time_t timer, char *zoffset));

char* month[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

char* wkday[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

int main(argc, argv)
     int argc;
     char *argv[];
{
  FILE *inif;
  char zostr[7];
  int argi;
  time_t timer = time(NULL);

  if (argc > 1)
    {
      for (argi = 1; argi < argc; ++ argi)
	print_zotime(timer, argv[argi]);
    }
  else if ((inif = fopen(INIFILE, "r")) != NULL)
    {
      while (fscanf(inif, "%6s", zostr) == 1)
	print_zotime(timer, zostr);
      fclose(inif);
    }
  else
    {
      strcpy(zostr, DEFAULT_OFFSET);
      print_zotime(timer, zostr);
    }
  exit(0);
}

void print_zotime(timer, zoffset)
     time_t timer;
     char *zoffset;
{
  int zohr, zomin, zosec;
  char zoout[7];
  struct tm *now;

  zohr = zomin = 0;
  if (strstr(zoffset, ":") != NULL)
    sscanf(zoffset, "%d:%d", &zohr, &zomin);
  else
    sscanf(zoffset, "%d", &zohr);
  if (-12 <= zohr && zohr <= 12 && 0 <= zomin && zomin <= 60)
    {
      zosec = (abs(zohr) *60 + zomin) * (zohr < 0 ? -60 : 60);
      timer += zosec;
      now = gmtime(&timer);
      if (zomin != 0)
	sprintf(zoout, "%+d:%02d", zohr, zomin);
      else if (zohr != 0)
	sprintf(zoout, "%+d", zohr);
      else
	strcpy(zoout, "");
      printf(" %s, %s %d, %04d %02d:%02d:%02d UTC%s\n", wkday[now->tm_wday], month[now->tm_mon], now->tm_mday, now->tm_year + 1900, now->tm_hour, now->tm_min, now->tm_sec, zoout);
    }
  else
    fprintf(stderr, "Time zone offset format error: %s\n", zoffset);
}