/* --- Copyright University of Sussex 1996. All rights reserved. ----------
 * File:			C.win32/extern/src/time.c
 * Purpose:			Time and date functions
 * Author:			Robert John Duncan, Jun 14 1994 (see revisions)
 * Documentation:
 * Related Files:
 */

#include "popcore.h"

	/*	Start a millisecond counter
	*/
DWORD pop_counter_start() {
	return GetTickCount();
}

	/*	Return current value of millisecond counter
	*/
DWORD pop_counter_diff(DWORD *count) {
	DWORD start = *count;
	*count = GetTickCount();
	if (*count > start)
		return *count - start;
	else
		/* assume one wrap-around */
		return (0xFFFFFFFFU - start) + *count + 1;
}

DWORD pop_get_process_time(void)
	/*	Returns the CPU time used by the current process in 1/100th
		second intervals
	*/
{
	FILETIME creation_time;
	FILETIME exit_time;
	FILETIME kernel_time;
	FILETIME user_time;

	return GetProcessTimes(GetCurrentProcess(), &creation_time, &exit_time,
			&kernel_time, &user_time)
		? pop_sum_process_times(&kernel_time, &user_time)
		: 0;
}

DWORD pop_get_real_time(DWORD *usecs)
	/*	Returns the current time in the Poplog/Unix style of number of
		seconds since 00:00:00 on 01/01/1970. If USECS is non-null,
		its value is set to the number of microseconds.
	*/
{
	DWORD time;
	SYSTEMTIME st;
	FILETIME ft;

	GetSystemTime(&st);
	if (SystemTimeToFileTime(&st, &ft)) {
		DWORD rem = pop_time_from_file_time(&time, &ft);
		if (usecs != NULL) {
			*usecs = rem;
		}
		else if (rem >= 500000) {
			/* round up */
			time++;
		}
	}
	else {
		time = POP_TIME_ERROR;
	}

	return time;
}

DWORD pop_convert_date(BOOL local, DWORD time, TCHAR *buffer, DWORD len)
	/*	Converts a pop TIME value into a date string in the given
		BUFFER of length LEN and returns the number of characters in
		the date. The flag LOCAL determines whether the time value is
		interpreted in local time or UCT.
			For now this uses a fixed format for the date; it possibly
		should use the user-preferred format from the registry.
	*/
{
	static TCHAR template[] = TEXT("DD/MM/YYYY HH:MM:SS");
	static TCHAR format[] = TEXT("%.2d/%.2d/%.4d %.2d:%.2d:%.2d");

	DWORD nchars;
	SYSTEMTIME st;
	FILETIME ft;
	pop_time_to_file_time(time, &ft);
	if (local)
	{
		FILETIME lft;
		FileTimeToLocalFileTime(&ft, &lft);
		FileTimeToSystemTime(&lft, &st);
	}
	else
		FileTimeToSystemTime(&ft, &st);

	nchars = wsprintf(template, format, st.wDay, st.wMonth, st.wYear,
		st.wHour, st.wMinute, st.wSecond);
	CopyMemory(buffer, template, (len <= nchars ? len : nchars+1)*sizeof(TCHAR));

	return nchars;
}

void pop_sleep(DWORD millisecs)
	/*	Suspend execution for a given time; a value of 0 yields execution
		to any other thread of the same priority waiting to run
	*/
{
	Sleep(millisecs);
}


/* --- Revision History ---------------------------------------------------
--- Robert Duncan, May 24 1996
		Added millisecond timer functions
 */
