#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>

/**
*
*@param args takes the thread number as the args
*/
void * report(void *args) {
	int *current =  args;
	struct timespec tim;
	int number = (int) current[0];
	float seconds = current[1]/1000000.0;

	printf("Thread %i waiting for %f seconds.\n", number, seconds);
	fflush(stdout);
	if(usleep(current[1]) == 0) {
		printf("Thread %i awakened.\n", number);
		fflush(stdout);
	} else {
		printf("Sleep error.");
	}
}

int main(int argc, char *argv[]) {
	//handle too few or too many CLI args
	if(argc != 2) {
		printf("Usage: nThreads <number>\n");
		return;
	}
	
	//declare variables
	int pos;
	int randomNumber;
	int count = atoi(argv[1]);
	pthread_t threads[count];
	struct timespec theTime;
	int vars[count][2];
	
	//seed random with the current nano seconds
	clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &theTime);
	srandom(theTime.tv_nsec);
	
	//loop to create the threads
	for(pos = 0; pos < count; pos += 1) {
		//igenerate the random number and get it down to near the seconds range
		randomNumber = random() / 1000;
		//make sure it's not bigger than 3 seconds
		while(randomNumber >= 3000000) {
			randomNumber = randomNumber / 10;
		}
		
		//store the wait time for this thread and the thread number to an array
		vars[pos][0] = pos;
		vars[pos][1] = randomNumber;
		printf("Main thread: creating thread number %i\n", pos);
		fflush(stdout);
		//create the thread running report() with the arguement var[pos]
		pthread_create(&threads[pos], NULL, report, (void *) vars[pos]);
	}
	//make sure all the threads are done before we exit
	for(pos = 0; pos < count; pos += 1) {
		pthread_join(threads[pos], NULL);
	}
}
