/*
 * Utility functions
 */

#include <stdio.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>

#include "utils.h"
#include "config.h"

#include "gtk_fe.h"

char *filedir = FILEDIR;

void error_message (
#ifdef DEBUG
	char *file, int line, char *func,
#endif
	char *type, int ecode, char *fmt, ...)
{
	va_list va;
	static char buf[2048];
	
	va_start (va, fmt);
	vsnprintf (buf, 2048, fmt, va);
	va_end (va);
	
#ifdef DEBUG
	fprintf (stderr, "%s: %s at %s:%d in %s\n", type, buf, file, line,
		func);
#else
	fprintf (stderr, "%s: %s\n", type, buf);
#endif
	if (ecode)
		exit (ecode);
}

void ReadFile (char *fname, void *ptr, size_t sz, int do_rpt)
{
	FILE *f;
	char buf[1024];
	struct stat st;
	int i;
	size_t rsz;
	
	snprintf (buf, 1024, "%s/%s", filedir, fname);
	f = fopen (buf, "r");
	if (!f)
		fatal ("Unable to open file %s", fname);
	fstat (fileno (f), &st);
	if (do_rpt && st.st_size < sz)
		rsz = st.st_size;
	else
		rsz = sz;
	if (fread (ptr, rsz, 1, f) != 1)
	{
		fclose (f);
		fatal ("Unable to read all %d bytes of file %s", sz, fname);
	}
	fclose (f);
	if (do_rpt && st.st_size < sz)
	{
		for (i = 0; i < sz/st.st_size; i++)
			if (sz-(i*st.st_size)>=st.st_size)
				memcpy ((char *)(ptr)+(i*st.st_size),ptr,st.st_size);
	}
}

/**** Timing functions ****/
volatile int timer_alrm;

static void alarmsig (int sig)
{
	timer_alrm++;
}

void init_timing (void)
{
	signal (SIGALRM, alarmsig);
}

void start_timer (int usec)
{
	struct itimerval tv;
	
	timer_alrm = 0;
	tv.it_interval.tv_sec = 0;
	tv.it_interval.tv_usec = 0;
	tv.it_value.tv_sec = 0;
	tv.it_value.tv_usec = usec;
	setitimer (ITIMER_REAL, &tv, NULL);
}

void stop_timer (void)
{
	start_timer (0);
}

/**** General event function ****/
void doevents (void)
{
#ifdef INTERFACE_GTK
	gtkfe_events ();
#endif
}

/**** Debugging-related functions ****/

int trace;

#ifdef DEBUG
FILE *debug;
#endif

void sighdlr (int signum)
{
	switch (signum)
	{
		case SIGUSR1:
		trace = 1;
		break;
		
		case SIGUSR2:
		trace = 0;
		break;
	}
}

void DebugInit (void)
{
#ifdef DEBUG
	debug = fopen ("debug.out", "w");
#endif
	signal (SIGUSR1, sighdlr);
	signal (SIGUSR2, sighdlr);
}

/* End of file. */
