#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <errno.h>

#include "die.h"

static pthread_mutex_t die_mutex = PTHREAD_MUTEX_INITIALIZER;

void lwt::die(const char *fmt, ...)
{
    va_list args;
	int myerrno = errno;

	pthread_mutex_lock(&die_mutex);
	fprintf(stderr, "LWT ERROR: ");
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
	fprintf(stderr, "\n");
	fprintf(stderr, "perror: ");

	errno = myerrno;
	perror(NULL);
	pthread_mutex_unlock(&die_mutex);
}

void lwt::fatal(const char *fmt, ...)
{
    va_list args;
	int myerrno = errno;

	fprintf(stderr, "LWT FATAL ERROR: ");
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
	fprintf(stderr, "\n");
	fprintf(stderr, "perror: ");

	errno = myerrno;
	perror(NULL);
	exit(EXIT_FAILURE);
}
