/******************************************
* Needle - a bitboard based chess engine. *
* (C) 2004 Mikko Nummelin                 *
******************************************/

#define _CHESSCLOCK_C

#include "needle.h"

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

#ifndef MSWINDOWS
/* Returns the value of computer's clock */
double dclock() {
        int retval;
        double timeindouble;
        struct timeval tval;

        retval=gettimeofday(&tval,NULL);
        if(retval==-1)
                return (double)-1;
        timeindouble=((double)tval.tv_sec+(double)tval.tv_usec/1000000);
        return timeindouble;
}

/* Returns the value of computer's clock in microseconds */
int iclock() {
        int retval,itime;
        struct timeval tval;

        retval=gettimeofday(&tval,NULL);
        if(retval==-1)
                return -1;
       	itime=(int)tval.tv_sec*1000000+(int)tval.tv_usec;
        return itime;
}
#else

/* Micro$oft equivalents */
double dclock() {
	FILETIME ft;
	double timeindouble;
	GetSystemTimeAsFileTime(&ft);
	timeindouble=(double)ft.dwHighDateTime*429.4967296+(double)ft.dwLowDateTime/10000000;
	return timeindouble;
}

int iclock() {
	FILETIME ft;
	int itime;
	GetSystemTimeAsFileTime(&ft);
	itime=(int)ft.dwLowDateTime*10;
	return itime;
}

#endif

/* Returns how much time is left if last_start is
*  the time when the clock was last started and
*  sl_last_start is the time what was left then */
double time_left(double last_start,double sl_last_start){
	return last_start+sl_last_start-dclock();
}

/* Returns time left in a clock */
double time_left_in_clock(Chessclock *clock){
	if(clock->stopped==TRUE){
		return clock->sl_last_start;
	}
	return(time_left(clock->last_start,clock->sl_last_start));
}

void stop_clock(Chessclock *clock){
	clock->sl_last_start=time_left_in_clock(clock);
	clock->stopped=TRUE;
}

void start_clock(Chessclock *clock){
	clock->stopped=FALSE;
	clock->last_start=dclock();
}

void set_clock(Chessclock *clock, double newtime){
	clock->sl_last_start=newtime;
	clock->last_start=dclock();
}

void addtime(Chessclock *clock, double added_time){
	clock->sl_last_start+=added_time;
}
