//    Copyright (C) 2001,2002,2003  Mike Rieker, Beverly, MA USA

#include "ozone.h"
#include "oz_io_console.h"
#include "oz_sys_dateconv.h"
#include "oz_sys_event.h"
#include "oz_sys_handle_getinfo.h"
#include "oz_sys_xprintf.h"
#include "oz_util_start.h"


static char *pn = "aclock";

static uLong rawrite (void *dummy, uLong *size, char **buff);

uLong oz_util_main (int argc, char *argv[]) {
  char rawbuff[256];
  int i, index, jobname_w, newcount, oldcount, processname_w, threadname_w, username_w;
  Long oldevent;
  OZ_IO_console_ctrlchar console_ctrlchar;
  OZ_Datebin utc_time, local_time;
  volatile uLong aborted;
  time_t t;
  struct tm *ltime;


  if (argc > 0) pn = argv[0];


  aborted = OZ_PENDING;
  memset (&console_ctrlchar, 0, sizeof console_ctrlchar);
  console_ctrlchar.mask[0]  = (1 << ('C' - '@')) | (1 << ('Z' - '@'));
  console_ctrlchar.terminal = 1;
  sts = oz_sys_io_start (OZ_PROCMODE_KNL, oz_util_h_console, &aborted, 0, NULL, NULL, OZ_IO_CONSOLE_CTRLCHAR, sizeof console_ctrlchar, &console_ctrlchar);
  if (sts != OZ_STARTED) oz_sys_io_fs_printf (oz_util_h_error, "%s: error %u enabling control char abort\n", pn, sts);
  else oz_sys_io_fs_printf (oz_util_h_console, "%s: use control-C or control-Z to exit\n", pn);

loop:
  if (aborted != OZ_PENDING) return (OZ_SUCCESS);

//  time = oz_hw_tod_getnow ();
  local_time = oz_sys_datebin_tzconv (oz_hw_tod_getnow(), OZ_DATEBIN_TZCONV_UTC2LCL, 0);


//datelongs[OZ_DATELONG_DAYNUMBER]

  oz_sys_xprintf (rawrite, NULL, sizeof rawbuff, rawbuff, NULL, "");
  oz_sys_xprintf (rawrite, NULL, sizeof rawbuff, rawbuff, NULL, "[aclock]\r\n");
  oz_sys_xprintf (rawrite, NULL, sizeof rawbuff, rawbuff, NULL, "[%t]\r\n", local_time);

  oz_sys_xprintf (rawrite, NULL, sizeof rawbuff, rawbuff, NULL, "");

  /* Now wait for a second before doing it again */


  sleep (1);
  goto loop;
}


static uLong rawrite (void *dummy, uLong *size, char **buff) {
  uLong sts;
  OZ_IO_console_putdat console_putdat;

  memset (&console_putdat, 0, sizeof console_putdat);
  console_putdat.size = *size;
  console_putdat.buff = *buff;
  sts = oz_sys_io (OZ_PROCMODE_KNL, oz_util_h_console, 0, OZ_IO_CONSOLE_PUTDAT, sizeof console_putdat, &console_putdat);
  return (sts);
}