#include <gnome.h>

#include "support.h"
#include "main.h"
#include "prefs.h"
#include "log.h"

G_LOCK_DEFINE_STATIC(log_mutex);
static FILE *logfile = NULL;
static gchar *logfilename = NULL;

/* ---------------------------------------------------------------------- */

void log_to_file(const gchar *s)
{
	G_LOCK(log_mutex);
	if (logfile) {
		if (fputs(s, logfile) == EOF || fflush(logfile) == EOF) {
			errmsg("Error writing to log file: %m");
			fclose(logfile);
			logfile = NULL;
			g_free(logfilename);
			logfilename = NULL;
		}
	}
	G_UNLOCK(log_mutex);
}

gint log_to_file_start(const gchar *name)
{
	gint ret = 0;

	G_LOCK(log_mutex);
	if (!logfile) {
		if ((logfile = fopen(name, "a")) == NULL)
			ret = -1;
		else
			logfilename = g_strdup(name);
	}
	G_UNLOCK(log_mutex);

	return ret;
}

void log_to_file_stop(void)
{
	G_LOCK(log_mutex);
	if (logfile) {
		fclose(logfile);
		logfile = NULL;
		g_free(logfilename);
		logfilename = NULL;
	}
	G_UNLOCK(log_mutex);
}

gchar *log_to_file_get_name(void)
{
	gchar *name;

	G_LOCK(log_mutex);
	name = logfilename;
	G_UNLOCK(log_mutex);

	return name;
}

/* ---------------------------------------------------------------------- */

