/*
 * Author:
 *         Kendy Kutzner <kutzner@ira.uka.de>
 *
 * (c) 2005 Research Group Dr. Fuhrmann, University of Karlsruhe, Germany
 * All rights reserved.
 *
 * $Id: debug.cc,v 1.10 2005/12/05 19:43:39 kutzner Exp $
 *
 */

#include <string>
using namespace std;

#include <stdio.h>
#include <stdarg.h>
#include <sys/time.h>
#include <assert.h>

#include "debug.h"
#include "utils.h"

// public functions

void
debug::conf(string c){
	int i;
	for (i = 0; i < FAC_COUNT; ++i){
		string facname = facilityname(facilities(i));
		int attrpos = c.find(facname);
		if (attrpos == -1){
			continue;
		}
		unsigned int valpos = attrpos + facname.size();
		if ((valpos + 2) > c.size()){
			continue;
		}
		string val = c.substr(valpos+1, 1);
		int level = atoi(val.c_str());
		print(DBG, 6, "set fac %s to prio %i\n", facname.c_str(), level);
		maxprio[i] = level;
	}
}

void
debug::print(int facility, int priority, char * format, ...){
	va_list ap;
	va_start (ap, format);
	do_print(facility, priority, format, ap);
	va_end(ap);
}

void
debug::print(char * format, ...){
	va_list ap;
	va_start (ap, format);
	do_print(DFLT, 5, format, ap);
	va_end(ap);
}

// private functions

void
debug::do_print(int facility, int priority, char * format, va_list ap){
	if (priority > maxprio[facilities(facility)]){
		if (facility != DBG){ // avoid infinite loop
			print(DBG, 6, "message suppressed fac %s prio %i maxprio %i\n", facilityname(facilities(facility)), priority, maxprio[facilities(facility)]);
		}
	} else {
		fprintf(_fd, "%f%5s%i:", dbltime(), facilityname(facilities(facility)), priority);
		vfprintf(_fd, format, ap);
	}
	return;
}
	

debug::debug() : _fd(stderr){
	unsigned int i;
	for (i=0; i < FAC_COUNT; i++){
		maxprio[i] = 5;
	}
}

void
debug::setfd(FILE* f){
	assert(f);
	_fd = f;
}
