/*******************************************************************************
 *	Debug.cpp	Debug routines
 *			T.Barnaby,	BEAM Ltd,	2007-02-07
 *******************************************************************************
 */
#include <stdio.h>
#include <stdint.h>
#include <syslog.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdarg.h>
#include <Debug.h>

int		bdebug;

void hd8(void* data, int n){
	unsigned char* d = (unsigned char*)data;
	int	i;
	
	for(i = 0; i < n; i++){
		printf("%2.2x ", *d++);
		if((i & 0xF) == 0xF)
			printf("\n");
	}
	printf("\n");
}

void hd32(void* data, int n){
	unsigned int* d = (unsigned int*)data;
	int	i;
	
	for(i = 0; i < n; i++){
		printf("%8.8x ", *d++);
		if((i & 0x7) == 0x7)
			printf("\n");
	}
	printf("\n");
}

void hd64(void* data, int n){
	uint64_t*	d = (uint64_t*)data;
	int		i = 0;
	
	printf("%8.8x: ", i);
	for(i = 0; i < n; i++){
		printf("%16.16llx ", *d++);
		if((i & 0x3) == 0x3){
			printf("\n");
			printf("%8.8x: ", (i+1));
		}
	}
	printf("\n");
}

// Get current time in seconds
double getTime()
{
	struct timeval	tp;
	
	gettimeofday(&tp, NULL);
	return ((double) tp.tv_sec + (double) tp.tv_usec * 1e-6);
}

void setDebug(int d){
	bdebug = d;
}

void tprintf(int log, const char* fmt, ...){
	va_list		args;
	char		tbuf[64];
	char		buf[4096];
	struct timeval	tv;
	
	va_start(args, fmt);
	gettimeofday(&tv, 0);

#if DEBUG_WITH_DATE
	strftime(tbuf, sizeof(tbuf), "%b %d %H:%M:%S", localtime(&tv.tv_sec));
#else
	strftime(tbuf, sizeof(tbuf), "%H:%M:%S", localtime(&tv.tv_sec));
#endif

	sprintf(buf, "%s.%3.3ld: Thread(%d) %s", tbuf, tv.tv_usec/1000, gettid(), fmt);

	vfprintf(stderr, buf, args);
	if(log)
		vsyslog(LOG_DEBUG, buf, args);
}

#include <errno.h>
#include <linux/unistd.h>

pid_t gettid(){
	return syscall(__NR_gettid);
}
