/*******************************************************************
  uLan Utilities Library - C library of basic reusable constructions

  ul_htimmstime.c   - standard hierarchical timer for microsecond
		      time resolution

  (C) Copyright 2003 by Pavel Pisa - Originator

  The uLan utilities library can be used, copied and modified under
  next licenses
    - GPL - GNU General Public License
    - LGPL - GNU Lesser General Public License
    - MPL - Mozilla Public License
    - and other licenses added by project originators
  Code can be modified and re-distributed under any combination
  of the above listed licenses. If contributor does not agree with
  some of the licenses, he/she can delete appropriate line.
  Warning, if you delete all lines, you are not allowed to
  distribute source code and/or binaries utilizing code.
  
  See files COPYING and README for details.

 *******************************************************************/

#include <string.h>
#include "ul_gavl.h"
#include "ul_gavlflesint.h"
#include "ul_htimer.h"

#ifdef UL_HTIMER_WITH_MSTIME

#include <time.h>
#include <stdio.h>

ul_htimer_queue_t ul_root_htimer;

ul_mstime_t ul_mstime_last;
ul_mstime_t ul_mstime_next;

static ul_mstime_t ul_mstime_base_offs;

#ifndef _WIN32

#include <sys/time.h>

void ul_mstime_update(void)
{
  struct timeval tv_actual;
  ul_mstime_t ms_actual;
  long int sec;
  gettimeofday(&tv_actual,NULL);
  sec=tv_actual.tv_sec;
  ms_actual=sec*1000+tv_actual.tv_usec/1000+ul_mstime_base_offs;
  ul_mstime_last=ms_actual;
}
#else /* _WIN32 */

#include <sys/timeb.h>

void ul_mstime_update(void)
{
  struct timeb tb_actual;
  ul_mstime_t ms_actual;
  long int sec;
  ftime(&tb_actual);
  sec=tb_actual.time;
  ms_actual=sec*1000+tb_actual.millitm+ul_mstime_base_offs;
  ul_mstime_last=ms_actual;
}
#endif /* _WIN32 */


void ul_mstime_init(void)
{
  ul_mstime_update();
  ul_mstime_base_offs=-ul_mstime_last;
  ul_mstime_update();
}

void
ul_get_log_time_str(char str[30])
{
  time_t log_time;
  struct tm *log_tm;
  time(&log_time);
  
  log_tm=localtime(&log_time);
  sprintf(str,"%04d-%02d-%02d %02d:%02d:%02d",
          (int)log_tm->tm_year+1900,(int)log_tm->tm_mon+1,
          (int)log_tm->tm_mday,(int)log_tm->tm_hour,
	  (int)log_tm->tm_min,(int)log_tm->tm_sec);
}

void ul_compute_mstime_next(void)
{
  if(!ul_htimer_next_expire(&ul_root_htimer,&ul_mstime_next))
    ul_mstime_next=ul_mstime_last+0x10000000;
}
  

#endif /*UL_HTIMER_WITH_MSTIME*/
