
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#ifdef __GNUC__
#include <pthread.h>
#else
#include <windows.h>
#endif


#ifdef __GNUC__
#define time_zone() ((long) timezone)
#else
#define time_zone() ((long) _timezone)
#endif


unsigned long trot = 24 * 3600;
int done = 0;



void *test_time(void *ptr) {
	unsigned long tloc, tval;
	time_t tcur, rott;
	struct tm tml, tmr;

	if (ptr)
		tzset();
	tcur = time(NULL);
	tml = *localtime(&tcur);
	tloc = (unsigned long) tcur - time_zone() + tml.tm_isdst * 3600;
	tval = (tloc / trot) * trot + time_zone() - tml.tm_isdst * 3600;
	rott = (time_t) tval;
	tmr = *localtime(&rott);
	printf("time     = %s"
	       "timezone = %ld\n"
	       "isdst    = %d\n"
	       "tutc     = %lu\n"
	       "tloc     = %lu\n"
	       "tval     = %lu\n"
	       "rotstr   = %04d%02d%02d%02d%02d\n",
	       ctime(&tcur), time_zone(), tml.tm_isdst, (unsigned long) tcur, tloc, tval,
	       tmr.tm_year + 1900, tmr.tm_mon + 1,
	       tmr.tm_mday, tmr.tm_hour, tmr.tm_min);

	done++;
	return NULL;
}


#ifdef __GNUC__

int run_thread(void *(*proc)(void *), void *ptr) {
	pthread_attr_t thattr;
	pthread_t thid;

	pthread_attr_init(&thattr);
	pthread_attr_setdetachstate(&thattr, PTHREAD_CREATE_DETACHED);

	if (pthread_create(&thid, &thattr, proc, ptr) != 0) {
		perror("pthread_create()");
		exit(1);;
	}
	pthread_attr_destroy(&thattr);

	return 0;
}


void tmsleep(int msec) {

	usleep(msec * 1000);
}

#else

int run_thread(void *(*proc)(void *), void *ptr) {
	unsigned int tid;
	unsigned long thr = _beginthreadex(NULL, 0, (unsigned (__stdcall *) (void *)) proc, ptr,
					   0, &tid);

	return 0;
}


void tmsleep(int msec) {

	Sleep(msec);
}

#endif



int main(int argc, char *argv[]) {

	if (argc > 1)
		trot = 3600 * atoi(argv[1]);
	tzset();
	printf("** From Main **\n");
	test_time((void *) 1);

	printf("** From Thread (No tzset) **\n");
	done = 0;
	run_thread(test_time, (void *) 0);
	while (!done)
		tmsleep(200);

	printf("** From Thread (tzset) **\n");
	done = 0;
	run_thread(test_time, (void *) 1);
	while (!done)
		tmsleep(200);

	return 0;
}

