#ifdef WIN32
#include <windows.h>
#endif

#ifndef WIN32
#ifndef USE_CTIME
#define USE_R 1
#endif
#endif

#ifndef DONE_INCLUDES
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <errno.h>
#include "safelib.h"

#ifdef WIN32
#include <windows.h>
#endif
#endif

#undef ctime
#undef localtime
#undef asctime
#undef readdir
#undef gmtime

static int in_crash;
static char lastbf[BFSZ];
void set_in_crash(int x)
{
	in_crash = x;
}
char *safe_ctime(const time_t *clock, char *bf)
{
#ifdef USE_R
	char *z;
#ifdef SOLARISx
	z = ctime_r(clock,bf,27);
#else
	z = ctime_r(clock,bf);
#endif
	if (z==NULL) return "";
	return z;
#else
	char *p;

	if (in_crash) {
		strncpy(bf, lastbf,30);
		return bf;
	}

	p = ctime(clock);
	if (p) strncpy(bf,p,27);
	else memset(bf,0,27);
	strncpy(lastbf, bf, 30);
	return bf;
#endif
}
char *safe_asctime(const struct tm *t, char *bf)
{
#ifdef USE_R
#ifdef SOLARISx
	return asctime_r(t,bf,27);
#else
	return asctime_r(t,bf);
#endif
#else
	strncpy(bf,asctime(t),27);
	return bf;
#endif
}
struct tm *safe_localtime_real(const time_t *clock,struct tm *result, int line)
{
#ifdef USE_R
	return localtime_r(clock,result);
#else
	struct tm *t;
	t = localtime(clock);
	if (t==NULL) return NULL;
#ifdef WIN32
		{
			int r;
			TIME_ZONE_INFORMATION tzi;

			r = GetTimeZoneInformation(&tzi);
			if (r==TIME_ZONE_ID_DAYLIGHT) {
				t->tm_isdst = 1;
			} else {
				t->tm_isdst = 0;
			}
		}



#endif
	memcpy(result,t,sizeof(struct tm));
	return result;
#endif
}
struct tm *safe_gmtime(const time_t *clock,struct tm *result)
{
#ifdef USE_R
	return gmtime_r(clock,result);
#else
	struct tm *t;
	t = gmtime(clock);
	if (t==NULL) return NULL;
	memcpy(result,t,sizeof(struct tm));
	return result;
#endif
}
#ifndef WIN32
	int safe_readdir(DIR *dirp, char *dresult, struct dirent **result)
	{
#ifdef USE_R
		*result = NULL;
#	ifdef SOLARISx
		*result = readdir_r(dirp,(struct dirent *) dresult);
		return 0;
#	else
		return readdir_r(dirp,(struct dirent *) dresult,result);
#	endif
#else
		struct dirent *r;
		*result = NULL;
		r = readdir(dirp);
		if (r==NULL) {
			return 0;
		}
		memcpy(dresult,r,sizeof(struct dirent));
		*result = (struct dirent *) dresult;
		return 0;
#endif
	}
#endif
