/*
*	Created:			16.11.09
*	Aurthor:			009
*	Last Modifed:		05.03.10
*	Description:		Функции дебага 
*
*	05.03.10:
*	1.оптимизация.добавлена запись времени выполнения функции
*
*	27.12.09:
*	1.добавлены типы дебага и табуляция в файле
*/

#if defined _debug_included
	#endinput
#endif

#define _debug_included
#pragma library debug

// --------------------------------------------------
// defines
// --------------------------------------------------
#if defined DEBUG_ON

#define Debug(%1,%2); format(DebugStr,sizeof(DebugStr),%2);WriteDebug(%1,DebugStr);
#define MAX_DEBUG_STRING 512
#define MAX_DEBUG_FUNCS_ON 50
#define MAX_DEBUG_WRITES 5
#define DEBUG_FILE_NAME "DEBUG.txt"
// --------------------------------------------------
// enums
// --------------------------------------------------
enum {
	DEBUG_START,
	DEBUG_ACTION,
	DEBUG_END
};

// --------------------------------------------------
// news
// --------------------------------------------------
new DebugStr[MAX_DEBUG_STRING];

// --------------------------------------------------
// statics
// --------------------------------------------------
static 
	tabcounts,
	tabs_tmp[MAX_DEBUG_FUNCS_ON],
	func_time[MAX_DEBUG_FUNCS_ON],
	File:debugfile = File:(-1),
	writes_count;

// --------------------------------------------------
// natives list (for pawno functions list)
// --------------------------------------------------
/*
native Debug(type,const format[],{Float,_}:...);
*/
	
// --------------------------------------------------
// stocks
// --------------------------------------------------
stock WriteDebug(mtype,message[])
{
	if(mtype == DEBUG_END) tabcounts--;
	
	for(new i = 0;i < tabcounts;i++) tabs_tmp[i] = '\t';
	tabs_tmp[tabcounts] = 0;
	
	switch(mtype)
	{
		case DEBUG_START: {format(message,MAX_DEBUG_STRING,"%s%s start\r\n",tabs_tmp,message);func_time[tabcounts] = GetTickCount();}
		case DEBUG_END: format(message,MAX_DEBUG_STRING,"%s%s end (%d ticks)\r\n",tabs_tmp,message,(GetTickCount() - func_time[tabcounts]));
		default: format(message,MAX_DEBUG_STRING,"%s%s\r\n",tabs_tmp,message);
	}
	
	if(int:debugfile == -1) debugfile = fopen(DEBUG_FILE_NAME,io_append);
	fwrite(debugfile,message);
	if(writes_count == MAX_DEBUG_WRITES) 
	{
		fclose(debugfile);
		debugfile = fopen(DEBUG_FILE_NAME,io_append);
		writes_count = 0;
	}
	else writes_count++;
	
	if(mtype == DEBUG_START) tabcounts++;
}

#else
	#define Debug(%1);
#endif