// -*- C++ -*-
//    Title: myclock.h
//  Created: Sun Mar 14 11:47:51 2010
//   Author: Tim Weyrich <t.weyrich@cs.ucl.ac.uk>
//      $Id: $
//
// copyright (c) 2010, University College London
//

#ifndef __MYCLOCK_H__
#define __MYCLOCK_H__

#ifndef _WIN32

#include <sys/time.h>

#else

#include <time.h>
#include <windows.h>

#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
  #define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64
#else
  #define DELTA_EPOCH_IN_MICROSECS  11644473600000000ULL
#endif

struct timezone 
{
  int  tz_minuteswest; /* minutes W of Greenwich */
  int  tz_dsttime;     /* type of dst correction */
};

static int gettimeofday(struct timeval *tv, struct timezone *tz)
{
  FILETIME ft;
  unsigned __int64 tmpres = 0;
  static int tzflag = 0;

  if (NULL != tv)
  {
    GetSystemTimeAsFileTime(&ft);

    tmpres |= ft.dwHighDateTime;
    tmpres <<= 32;
    tmpres |= ft.dwLowDateTime;

    tmpres /= 10;  /*convert into microseconds*/
    /*converting file time to unix epoch*/
    tmpres -= DELTA_EPOCH_IN_MICROSECS; 
    tv->tv_sec = (long)(tmpres / 1000000UL);
    tv->tv_usec = (long)(tmpres % 1000000UL);
  }

  if (NULL != tz)
  {
    if (!tzflag)
    {
      _tzset();
      tzflag++;
    }
    tz->tz_minuteswest = _timezone / 60;
    tz->tz_dsttime = _daylight;
  }

  return 0;
}

#define timerisset(tvp)                         \
        ((tvp)->tv_sec || (tvp)->tv_usec)

#define timercmp(tvp, uvp, cmp)                 \
((tvp)->tv_sec cmp (uvp)->tv_sec ||             \
 (tvp)->tv_sec == (uvp)->tv_sec &&              \
 (tvp)->tv_usec cmp (uvp)->tv_usec)

#define timerclear(tvp)                         \
        ((tvp)->tv_sec = (tvp)->tv_usec = 0) 

#endif

//! Returns time since first call to myclock() in seconds.
static double  myclock(void)
{
    static struct timeval  start = {0, 0};
    struct timeval  now; 
    gettimeofday(&now, NULL);
    
    if (!timerisset(&start))
        start = now;

    return (double)(now.tv_sec - start.tv_sec)
        + 1e-6 * ((double)now.tv_usec - (double)start.tv_usec);
};

#endif
