// clock.cpp
// celes@tecgraf.puc-rio.br
// Jul 2002

#include "clock.h"

#include <stdlib.h>
#ifdef _WIN32
#include <sys/timeb.h>
#else
#include <sys/time.h>
#endif

#ifdef _WIN32
double gettime (void)
{
  struct _timeb t;
  _ftime(&t);
  return ((double)t.time) + 0.001*t.millitm;
}
#else
double gettime (void)
{
  struct timeval t;
  gettimeofday(&t,NULL);
  return  ((double)t.tv_sec) + 0.000001*t.tv_usec;
}
#endif

void sleep(double seconds)
{
  double t0 = gettime();
  while(gettime()<(t0+seconds));
}

UtlClock::UtlClock ()
{
  Start();
}

double UtlClock::Start (double reference)
{
  m_ref     = m_lastref = reference;
  m_running = true;
  return m_ref;
}

double UtlClock::Start ()
{
  m_ref     = m_lastref = (double)gettime();
  m_running = true;
  return m_ref;
}

double UtlClock::Stop ()
{
  m_time = GetTime();
  m_running = false;
  return m_time;
}

void UtlClock::Pause ()
{
  if ( m_running )
  {
    m_time = GetTime();
  } else {
    m_ref  = gettime()-m_time; // so GetTime will return last GetTime
  }
  m_running ^= 1;
}

double UtlClock::GetStartTime () const // ??? errado
{
  return m_ref;
}

double UtlClock::GetTime () const
{
  return m_running ? (double)gettime() - m_ref : m_time;
}

double UtlClock::GetElapsedTime ()
{
  if (m_running)
  {
    double t = (double)gettime();
    double d = t-m_lastref;
    m_lastref = t;
    return d;
  }
  else {
    return 0.0;
  }
}
