#include "includes.h"
#include "knightcap.h"

static FILE *logfile;
static FILE *sfile;
static FILE *cfile;
static FILE *dfile;

void log_close(void)
{
	fclose(logfile);
	logfile = NULL;
}

int lprintf(int level, char *format_str, ...)
{
	va_list ap;  
	char fmt[1024];
	char *p;

	if (!logfile) {
#if APLINUX
		logfile = fopen("/ddv/data/tridge/knightcap.log","w");
#else
		logfile = fopen("knightcap.log","w");
#endif
	}

	va_start(ap, format_str);


	strcpy(fmt, format_str);
	if (sizeof(short) == sizeof(etype)) {
		while ((p = strstr(fmt, "%e"))) {
			p[1] = 'd';
		}
	} else {
		while ((p = strstr(fmt, "%e"))) {
			p[1] = 'd';
		}
	}


	if (level == 0) {
		vfprintf(stdout,fmt,ap);
		if (fmt[strlen(fmt)-1] == '\n')
			fflush(stdout);
	}

	if (logfile) {
		vfprintf(logfile,fmt,ap);
		if (level == 0)
			if (fmt[strlen(fmt)-1] == '\n')
				fflush(logfile);
	}

	va_end(ap);


	return(0);
}

int status_printf(int rew, char *format_str, ...)
{
	va_list ap;  
	char fmt[1024];
	char *p;

	if (!sfile) {
#if USE_APPLET		
		sfile = fopen("/export/pasiphae/status.txt","w");
#else 
		sfile = fopen("status.txt","w");
#endif
	}

	if (rew) 
		rewind(sfile);

	va_start(ap, format_str);


	strcpy(fmt, format_str);
	if (sizeof(short) == sizeof(etype)) {
		while ((p = strstr(fmt, "%e"))) {
			p[1] = 'd';
		}
	} else {
		while ((p = strstr(fmt, "%e"))) {
			p[1] = 'd';
		}
	}


	if (sfile) {
		vfprintf(sfile,fmt,ap);
		if (fmt[strlen(fmt)-1] == '\n')
			fflush(sfile);
	}

	va_end(ap);


	return(0);
}

void lindent(int level, int ply)
{
	while (ply--) 
		lprintf(level, "\t");
}

int cprintf(int level, char *format_str, ...)
{
	va_list ap;  


	if (!cfile) {
		cfile = fopen("wnorm.dat", "w");
	}

	va_start(ap, format_str);
	
	vfprintf(cfile,format_str,ap);
	fflush(cfile);

	va_end(ap);


	return(0);
}

int ddprintf(int level, char *format_str, ...)
{
	va_list ap;  


	if (!dfile) {
		dfile = fopen("/usr/local/chess/bad_grad.dat", "a");
	}

	va_start(ap, format_str);
	
	vfprintf(dfile,format_str,ap);
	fflush(dfile);

	va_end(ap);


	return(0);
}
