
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <glib.h>
#include <sys/time.h>
#include <string>
#include <time.h>
#include <fcntl.h>

#include "debug.h"

int debug_uninit = 1;
GMutex debug_mutex;
time_t debug_time;
#define LEN 2048

void debug_init() {
	debug_uninit = 0;
	g_mutex_init (&debug_mutex);
	debug_time = time(NULL);
}

void debug_tofile(char *fname, int isheader, char *fmt, ...) {
	struct timeval tv;
	va_list args;
	char buffer[LEN];
	int fd, len;
	std::string fn;
	
	if (debug_uninit) debug_init();
	g_mutex_lock(&debug_mutex);

	// locale set to C, floating points decimals are .
	std::string s = setlocale(LC_ALL, NULL);
	setlocale (LC_ALL, "C");

	// append time to filename to the start of the filename
	struct tm *timetm = localtime(&debug_time);
	char timestr[64] = "";
	strftime(timestr, 63, "%Y%m%d-%H%M%S", timetm);
	fn = "debug-" + (std::string)timestr + "-" + (std::string)fname;

	gettimeofday(&tv,NULL);

#ifdef BUILD_WINDOWS
	fd = open(fn.c_str(), O_WRONLY | O_APPEND | O_CREAT);
#else
	fd = open(fn.c_str(), O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#endif
	if (fd < 0) errorexit((char*)"%s:%d could not open debug '%s' file. Error:%s\n", __FILE__, __LINE__, fname, strerror(errno));

	if (isheader)   snprintf (buffer, 32, "time,");
	else 			snprintf (buffer, 32, "%lld,", (long long int) (tv.tv_sec)*1000 + (long long int) tv.tv_usec/1000);
	len = strlen (buffer);
	va_start (args, fmt);
	vsnprintf (buffer+len, LEN-1-len, fmt, args);
	va_end (args);
	buffer[LEN-1] = 0;
	write (fd, buffer, strlen(buffer));
	close (fd);

	// reset locale to user setting
	setlocale (LC_ALL, s.c_str());

	g_mutex_unlock(&debug_mutex);
}
