/* timetester.c
 *
 * $Id: timetester.c,v 1.4 2000/12/04 03:37:03 alderman Exp $
 *
 * Just something to test the timing code.
 */
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
// #include <values.h>
#include <sys/time.h>

#include "options.h"

struct timeval base_tv;

long tv_to_msec(struct timeval *t_tv) {
	long since;
	long usince;

	since = t_tv->tv_sec - base_tv.tv_sec;
	usince = (t_tv->tv_usec - base_tv.tv_usec)/1000;
	usince += since * 1000;
	return usince;
}

/* Return the number of milliseconds between chunks given
 * a chunk size in bytes, and a chunk rate in bits per second.
 */
long chunk_time(long chunk_size, long chunk_rate) {
	double rv;
	rv = 8.0 * chunk_size / chunk_rate;
	rv = rv * 1000.0;
	return (long)rv;
}

int main(int argc, char *argv[]) {
	int i = 0, sleeplen, now;
	int rv, start_ms, ctr = 0, period_end, errctr = 0;
	struct timeval now_tv;
	long chunk_ms;
	extern int blockSize;
	extern int numThreads;
	extern int bitRate;

	parseArgs(argc, argv);
	if(validateParams() != VALIDATION_SUCCESS) {
		printUsage();
		exit(1);
	}

	chunk_ms = chunk_time(blockSize, bitRate);

	printf("%d milliseconds per chunk with block size %d and rate %d.\n",
			chunk_ms, blockSize, bitRate);

	gettimeofday(&base_tv, NULL);
	base_tv.tv_usec = 0;
	gettimeofday(&now_tv, NULL);
	start_ms = tv_to_msec(&now_tv);
	

	while(1) {
		printf("Starting program.\n");
		system("/usr/bin/perl factor.pl > /dev/null");
		gettimeofday(&now_tv, NULL);
		now = tv_to_msec(&now_tv);

		period_end = start_ms + chunk_ms * ++ctr;
		printf("End: %d Now: %d\n",period_end, now);
		if(period_end < now) {
			++errctr;
			printf("Done: time exceeded!  End: %d Now: %d\n",period_end, now);
		} else {
			sleeplen = period_end - now;
			printf("Done; starting sleep for %d msec\n", sleeplen);
			usleep(1000*sleeplen);
		}
		printf("Period %d, %d errors\n",ctr,errctr);
	}	
}
