#include "all_defs.h"
#include "opts__defs.h"
#include <stdint.h>

#define Z(X)
#define sn(X) tod = X; goto no

void fmt_time(char *fmt) /*EXTRACT_INCL*/{
  uint32_t day, mon, year, tod;
  uint32_t tm_wday, tm_sec, tm_min, tm_hour;
#if 0
  uint32_t yday=0;
#endif
  char buf[16], *m;

  time_t now = time(0);
  now += get_tz(now);

  tod = (uint32_t)now % 86400;
  day = (uint32_t)now / 86400;

  tm_wday = ((day+4) % 7);
  tm_sec  = tod%60; tod /= 60;
  tm_min  = tod%60;
  tm_hour = tod/60;

  year = 4*day + 2;
  year /= 1461;

  day += 671;
  day %= 1461;		/* day 0 is march 1, 1972 */
  Z(if (day < 306) yday = 1);
  if (day == 1460) { day = 365; Z(yday = 59); }
  else { day %= 365;   Z(yday += (day + 59) % 365); }

  day *= 10;
  mon = (day + 5) / 306;
  day = day + 5 - 306 * mon;
  day /= 10;
  if (mon >= 10) mon -= 10;
  else mon += 2;	/* day 0,1,30, mon 0..11,  year 1970=0,1,2 */

  year += 1970;
  day += 1;

  for (; (*buf=*fmt); ++fmt) {
    tod = 1;
    m = Oo[Omonths] + 3*mon;
    switch (*buf) {
    no:
      if (tod<10) out_char('0');
      tod = fmt_ulong(buf,tod);
      break;
    case 'Y': sn(year);
    case 'm': sn(mon +1);
    case 'd': sn(day);
    case 'H': sn(tm_hour);
    case 'M': sn(tm_min);
    case 'S': sn(tm_sec);
    case 'a': m = Oo[Odays] + 3*tm_wday;
    case 'b':
      tod = str_copynz(buf,m,3);
    }
    buf[tod] = 0;
    out_puts(buf);
  }
}
