#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdint.h>
#include <inttypes.h>

#include "../../src/util/error.h"
#include "../../src/util/memory.h"
#include "../../src/util/timer.h"


static int err;


// Quite short delay corresponding to 20 Hz.
#define DELAY_MS 50

/**
 * Test timer against the sleep() function on a short delay. Measured delay
 * should be close to the issued delay time.
 */
static void testSleep()
{
	timer_Type *t = timer_new();
	timer_start(t);
	timer_sleepMilliseconds(DELAY_MS);
	timer_stop(t);
	
	int ms = timer_getElapsedMilliseconds(t);
	int64_t us = timer_getElapsedMicroseconds(t);
	int64_t ns = timer_getElapsedNanoseconds(t);
	
	// The time module should round ns to get ms and us -- check:
	if( !(ms == (ns + 500000)/1000000 && us == (ns + 500)/1000) ){
		err++;
		printf("ERROR: timings units mismatch, bad rounding:"
			" %d ms, %" PRId64 " us, %" PRId64 " ns\n",
			ms, us, ns);
	}
	
	int delta = ms - DELAY_MS;
	if( !(-5 <= delta && delta <= 10) ){
		err++;
		printf("ERROR timing the 'sleep' function: expected %d ms, got %d ms (%+d ms)\n",
			DELAY_MS, ms, delta);
		printf("This may happen if the system is busy -- check for running processes and try again.\n");
	}
	
	memory_dispose(t);
};


#define granularity_N 100

/**
 * Check timer granularity better than 1 ms.
 */
static void testGranularity()
{
	timer_Type *t = timer_new();
	int i, min, max, sum = 0;
	for(i = 0; i < granularity_N; i++){
		
		// Get a sample of the smaller detectable time interval:
		timer_reset(t);
		timer_start(t);
		int64_t dt_ns = 0;
		do {
			dt_ns = timer_getElapsedNanoseconds(t);
		} while(dt_ns <= 0);
		
		// Update the statistics:
		sum += dt_ns;
		if( i == 0 ){
			min = max = dt_ns;
		} else if( dt_ns < min ){
			min = dt_ns;
		} else if( dt_ns > max ){
			max = dt_ns;
		}
	}
	
	if( max >= 1000000 ){
		err++;
		printf("ERROR: coarse timer granularity detected on %d samples: min=%d ns, max=%d ns, avg=%g ns\n",
			granularity_N, min, max, (double)sum/granularity_N);
	}
	memory_dispose(t);
}


int main(int argc, char** argv)
{
	testSleep();
	testGranularity();
	err += memory_report();
	return err == 0? 0 : 1;
};
