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

FILE *logfile;

int open_log(char *filename) {
	if ((logfile = fopen(filename, "w")) != NULL)  {
		time_t hold_time;
		hold_time = time(NULL);
		fprintf(logfile, ctime(&hold_time));
		return 0;
	}
	return -1;
}

int log_print(char *format, ...) {
	va_list ptr; // arg pointer
	int status = -1;

	if (logfile != NULL) {
		// initialize ptr to point to the first argument after the format string
		va_start(ptr, format);

		// write to logfile
		status = vfprintf(logfile, format, ptr);
		va_end(ptr);

		// flush file
		fflush(logfile);
	}
	return status;
}

int log_println(char *format, ...) {
	va_list ptr;
	int status = -1;

	if (logfile != NULL) {
		va_start(ptr, format);
		status = vfprintf(logfile, format, ptr);
		fprintf(logfile, "\n");
		va_end(ptr);

		fflush(logfile);
	}
	return status;
}

int close_log(void) {
	if (logfile != NULL) {
		fflush(logfile);
		fclose(logfile);
	}
	return -1;
}
