
#include "MW4Headers.hpp"

#include "AblProfiler.hpp"



using namespace ABL;

namespace ABL
{
	void ABL_AddToProfileLog (char* profileString);
};

Profiler* Profiler::m_Instance = 0;

Profiler* Profiler::Instance()
{
	return (m_Instance);
}

Profiler::Profiler()
	: m_Active(false)
{
	Verify(m_Instance == 0);
	m_Instance = this;
}

Profiler::~Profiler()
{
	Verify(m_Instance == this);

	SpewIt();

	m_Instance = 0;
}

void Profiler::SetActive(bool active)
{
	if (m_Active == active)
	{
		return;
	}

	m_Active = active;

	if (m_Active == true)
	{
		m_PerFunctionTiming.clear();
		m_PerModuleTiming.clear();
	}
}

bool Profiler::GetActive() const
{
	return (m_Active);
}

Profiler::CallInfo::CallInfo()
	: total_time(0)
	, total_calls(0)
{
}

void Profiler::NotifyFunctionCalled(double time,
									const char* function_name,
									const char* module_name)
{
	AddTimeToCallInfoMap(time,function_name,m_PerFunctionTiming);
	AddTimeToCallInfoMap(time,module_name,m_PerModuleTiming);
}

void Profiler::AddTimeToCallInfoMap(double time, const char* name, call_info_map& m)
{
	m[name].total_time += time;
	++(m[name].total_calls);

	call_info_map::iterator i(m.find(name));
}

inline std::string DoubleToString(double d)
{
	char buf[80];
	sprintf(buf,"%.4f",d);
	return (buf);
}

inline std::string IntToString(int i)
{
	char buf[100];
	sprintf(buf,"%d",i);
	return (buf);
}

void Profiler::SpewIt() const
{
#if defined(LAB_ONLY)
	SPEWALWAYS((0,"\n"));

	{for (call_info_map::const_iterator i = m_PerFunctionTiming.begin();
		  i != m_PerFunctionTiming.end();
		  ++i)
	{
		std::string s("Function: ");
		s += (*i).first;
		s += "  Total Time: ";
		s += DoubleToString((*i).second.total_time);
		s += "  Total Function Calls: ";
		s += IntToString((*i).second.total_calls);

		SPEWALWAYS((0,"%s",s.c_str()));
	}}

	SPEWALWAYS((0,"\n"));

	{for (call_info_map::const_iterator i = m_PerModuleTiming.begin();
		  i != m_PerModuleTiming.end();
		  ++i)
	{
		std::string s("Script: ");
		s += (*i).first;
		s += "  Total Time: ";
		s += DoubleToString((*i).second.total_time);
		s += "  Total Function Calls: ";
		s += IntToString((*i).second.total_calls);

		SPEWALWAYS((0,"%s",s.c_str()));
	}}

	SPEWALWAYS((0,"\n"));
#endif
}
