/*
 * $Id$
 *
 * Code (c)2006 Bruno Cornec <bruno@mondorescue.org>
 *
 *     Main file of mr_msg : a very small and simple
 *     library for messages management
 *
 * Provided under the GPLv2
 */

#include <stdio.h>
#include <stdarg.h>

static int mr_loglevel = 0;
static char *mr_logfile = NULL;

/* Initialization function for messages */
void mr_msg_init(void) {

}

/*
 * Function that log a message. Not called directly 
 * but through macros in mr_msg.h
 */
void _mr_msg(int debug, const char *file, const char *function, int line, const char *fmt, ...) {

	va_list args;
	int i = 0;
	int res = 0;
	FILE *fout = NULL;

	if (debug <= mr_loglevel) {
		va_start(args, fmt);
		if (!(fout = fopen(mr_logfile, "a"))) {
			fprintf(stderr,"Unable to append to %s\n",mr_logfile);
			return;
		}

		// add 2 spaces to distinguish log levels
		if (debug > 0) {
			for (i = 1; i < debug; i++)
				fprintf(fout, "  ");
			fprintf(fout, "%s->%s#%d: ", file, function, line);
		}
		vfprintf(fout, fmt, args);

		va_end(args);
		fprintf(fout, "\n");
		if ((res = fclose(fout)) != 0) {
			fprintf(stderr,"Unable to close %s\n",mr_logfile);
		}
	}
}
