/**
 ** \file misc/timer.cc
 ** \brief Implementation for misc/timer.hh.
 */

#include <iostream>
#include <iomanip>

#include <sys/times.h>
#include <unistd.h>

#include "misc/timer.hh"
#include "misc/contract.hh"

/*-----------------.
| Timer::TimeVar.  |
`-----------------*/

Timer::TimeVar::TimeVar ()
  : initial (true)
{ }

void
Timer::TimeVar::start ()
{
  struct tms tms;

  begin.wall = times (&tms);
  begin.user = tms.tms_utime;
  begin.sys  = tms.tms_stime;

  if (initial)
    {
      initial = false;
      first = begin;
    }
}

void
Timer::TimeVar::stop ()
{
  struct tms tms;

  last.wall = times (&tms);
  last.user = tms.tms_utime;
  last.sys = tms.tms_stime;
  elapsed.wall += last.wall - begin.wall;
  elapsed.user += last.user - begin.user;
  elapsed.sys += last.sys - begin.sys;
}

bool
Timer::TimeVar::is_zero ()
{
  return (true
	  && elapsed.wall == 0
	  && elapsed.user == 0
	  && elapsed.sys  == 0);
}


/*--------.
| Timer.  |
`--------*/

Timer::Timer () :
  clocks_per_sec_ (sysconf (_SC_CLK_TCK))
  //  clocks_per_sec_ (100)
{ }


Timer::~Timer ()
{
  // If magic is asked on destruction, let it happen completely.
  if (dump_stream)
    {
      // Consider that if the tasks were not properly closed, then
      // stop was not invoked either.
      if (!tasks.empty ())
	{
	  do
	    pop ();
	  while (!tasks.empty ());
	  stop ();
	}
      dump (*dump_stream);
    }

  // Deallocate all our TimeVar.
  for (task_map_type::iterator i = tasksmap.begin (); i != tasksmap.end (); ++i)
    delete i->second;
}


void
Timer::name (int i, std::string task_name)
{
  intmap[i] = task_name;
}

void
Timer::timeinfo (long time, long total_time, std::ostream& out)
{
  out << setiosflags (std::ios::left);
  out << std::setw (6) << std::setprecision (6) << (float) (time) / clocks_per_sec_;
  out << resetiosflags (std::ios::left);
  out << " (";
  out << std::setw (5) << std::setprecision (3) << (total_time ?
						   (float) time * 100 / total_time :
						   (float) time);
  out << "%) ";
}


void
Timer::dump (std::ostream &out = std::cerr)
{
  out << "Execution times (seconds)" << std::endl;
  for (task_map_type::const_iterator i = tasksmap.begin ();
       i != tasksmap.end (); ++i)
    {
      if (!(i->second->is_zero ()))
	{
	  out << " " << i->first << std::setw (26 - i->first.length ());
	  out << ": ";
	  timeinfo (i->second->elapsed.user, total.elapsed.user, out);
	  out << "  ";
	  timeinfo (i->second->elapsed.sys, total.elapsed.sys, out);
	  out << "  ";
	  timeinfo (i->second->elapsed.wall, total.elapsed.wall, out);
	  out << std::endl;
	}
    }
  out << std::endl;

  out << "Cumulated times (seconds)" << std::endl;
  for (task_map_type::const_iterator i = tasksmap.begin ();
       i != tasksmap.end (); ++i)
    {
      if (0 != (i->second->last.wall - i->second->first.wall))
	{
	  out << " " << i->first << std::setw (26 - i->first.length ());
	  out << ": ";
	  timeinfo (i->second->last.user - i->second->first.user, total.elapsed.user, out);
	  out << "  ";
	  timeinfo (i->second->last.sys - i->second->first.sys, total.elapsed.sys, out);
	  out << "  ";
	  timeinfo (i->second->last.wall - i->second->first.wall, total.elapsed.wall, out);
	  out << std::endl;
	}
    }
  out << std::endl;

  out << " TOTAL (seconds)"  << std::setw (11) << ": "

      << setiosflags (std::ios::left) << std::setw (7)
      << (float) total.elapsed.user / clocks_per_sec_
      << std::setw (11)
      << "user,"

      << std::setw (7)
      << (float) total.elapsed.sys / clocks_per_sec_
      << std::setw (11)
      << "system,"

      << std::setw (7)
      << (float) total.elapsed.wall / clocks_per_sec_
      << "wall"

      << resetiosflags (std::ios::left) << std::endl;
}

void
Timer::push (const std::string task_name)
{
  TimeVar *current;

  // if stack isn't empty, we set elapsed time for the current task
  if (!tasks.empty ())
    tasks.top ()->stop ();

  if (tasksmap.find (task_name) == tasksmap.end ())
    tasksmap[task_name] = new TimeVar;

  current = tasksmap[task_name];
  tasks.push (current);
  current->start ();
}

void Timer::pop ()
{
  precondition (!tasks.empty ());

  // Set the Elapsed time for the task we are closing
  tasks.top ()->stop ();

  // Current task is removed of the stack
  tasks.pop ();

  // We set the start time of the previous task at current time
  if (!tasks.empty ())
    tasks.top ()->start ();
}
