#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>

// Only works with 2 threads for now.
// To do: generalization for N threads.

#define PARALLEL 1
#ifdef PARALLEL
#define NTHREADS 2
#else
#define NTHREADS 1
#endif

#define MAXLINE 256

typedef struct node{
	int count;
	char *word;
	struct node *left;
	struct node *right;
} node_t;

typedef struct flow {
	int thread_id;
	int offset;
	int count;
	char *curp;
	char line[MAXLINE];
} flow_t;

node_t root[NTHREADS];

flow_t flow_struct[NTHREADS];

struct stat file_info;

char *file_buffer;
int file_size;
int word_count = 0;

void count(int th);

char *get_word(flow_t *flowp);
char *get_line(flow_t *flowp);

int verbose = 0;
int silent = 0;
int timecount = 0;

main(int argc, char *argv[])
{
#ifdef PARALLEL
  	pthread_t thread1, thread2;
#endif
	FILE *file = stdin;
	double time_start, time_end;
	struct timeval tv;
	struct timezone tz;
	char *word;
	int ret;
	int i = 1;


	// Parse command line arguments
	while (i < argc) {
	  if (strcmp(argv[i], "-v") == 0) {
	    verbose = 1;
	    i++;
	    continue;
	  }
	  if (strcmp(argv[i], "-s") == 0) {
	    silent = 1;
	    i++;
	    continue;
	  }
	  if (strcmp(argv[i], "-t") == 0) {
	    timecount = 1;
	    i++;
	    continue;
	  }
	  if ((file = fopen(argv[i], "rb")) == NULL) {
	    perror(argv[i]);
	    exit(1);
	  } else {
		if (stat(argv[i], &file_info) != 0) {
			perror(argv[i]);
			exit (1);
		}
	    i++;
	    continue;
	  }
	}
    if (timecount) {
      gettimeofday(&tv, &tz);
      time_start = (double)tv.tv_sec +
			(double)tv.tv_usec / 1000000.0;
	}
	// Initialize data strucures
	for (i = 0; i < NTHREADS; i++) {
		memset(&root[i], 0, sizeof(node_t));
		memset(&flow_struct[i], 0, sizeof(flow_t));
	}
	// Open file and read content into memory
	if (file != stdin) {
		file_size = file_info.st_size;
		printf("File size: %d bytes\n", file_size);
		file_buffer = malloc(file_size);
		if (fread(file_buffer, 1, file_size, file) != file_size) {
			perror("fread");
			exit(1);
		}
		rewind(file);
	} else {
		printf("Usage %s file <options>\n", argv[0]);
		exit(1);
	}
#ifdef PARALLEL
	// Spawn thread to count A-M words
  	ret = pthread_create(&thread1, NULL, (void *)(&count), (void *)0);
  	if (ret) {
  	  perror("thread create");
  	  exit(1);
  	}
/*
	ret = pthread_create(&thread2, NULL, (void *)(&count), (void *)1);
  	if (ret) {
  	  perror("thread create");
  	  exit(1);
  	}
*/
	// Now count M-Z words in main thread
	count(1);

 	pthread_join(thread1, NULL);
//	pthread_join(thread2, NULL);
#else
	count(0); // Count all words in main thread
#endif
	printf("Words root0\n");
	list(&root[0]);
	printf("Word count root0: %d\n", word_count);
//	word_count = 0;
#ifdef PARALLEL
	printf("Words root1\n");
	list(&root[1]);
#endif
	printf("Total words: %d\n", word_count);

    if (timecount) {
      gettimeofday(&tv, &tz);
      time_end = (double)tv.tv_sec +
			(double)tv.tv_usec / 1000000.0;
#ifdef PARALLEL
	  printf("\nParallel Time Elapsed %lf sec.\n", time_end - time_start);
#else
	  printf("\nSerial Time Elapsed %lf sec.\n", time_end - time_start);
#endif
	}

}

void count(int th)
{
	char *word;
	unsigned char first;
	flow_t *flowp;

	if (verbose)
		printf("Thread %d started\n", th);
	flowp = &flow_struct[th];
	flowp->thread_id = th;
	while (1) {
	  word = get_word(flowp);
	  if (word == (char *)NULL)
	    continue;
	  if (word == (char *)EOF)
	    break;
#ifdef PARALLEL
	  first = word[0]|0x20; // Convert all to lower case
	  if (th == 0) {
	  	if (first <= 'm')
	  		insert(&root[th], word); // count A-M words
	  } else if (th == 1) {
	  	if (first > 'm')
	  		insert(&root[th], word); // count N-Z words
	  }
#else
	insert(&root[th], word);
#endif
  }
}

insert(node_t *node, char *word)
{
    int position;

	if (node == (node_t *) NULL) {
	  node = (node_t *) calloc(1, sizeof(node_t));
	}
	if (node->word == (char *) NULL) {
	  if (verbose)
	    printf("Inserting %s\n", word);
	  node->word = word;
	  node->count = 1;
	  return;
	}
	position = strcmp(word, node->word);
	if (position == 0) {
	  node->count++;
	  if (verbose)
	    printf("Adding %s count %d\n", word, node->count);
	  return;
	} else if (position < 0) {
	  if (node->left == (node_t *)NULL)
	    node->left = (node_t *) calloc(1, sizeof(node_t));
	  insert(node->left, word);
	} else if (position > 0) {
	  if (node->right == (node_t *)NULL)
	    node->right = (node_t *) calloc(1, sizeof(node_t));
	  insert(node->right, word);
	}
}

list(node_t *node)
{
	if (node->word != (char *)NULL) {
	  if (silent == 0)
		printf("%s %d\n", node->word, node->count);
	  word_count++;
	}
	if (node->left != (node_t *)NULL)
		list(node->left);
	if (node->right != (node_t *)NULL)
		list(node->right);
}

char *get_word (flow_t *flowp)
{
	char word[32];
	int count = 0;
	char *p;
	char *q;
	int size, inword = 0;

	if (flowp->count == 0 && flowp->offset >= file_size) {
		if (verbose)
			printf("Thread %d reached EOF at %d size %d\n", flowp->thread_id, flowp->offset, file_size);
	    return (char*)EOF;
	}
	memset(word, 0, sizeof(word));
	if (flowp->count == 0) { /* Read more from file */
	  memset(flowp->line, 0, MAXLINE);
	  p = get_line(flowp);
	  if (p == NULL)
	    return (char*)EOF;
	  count = strlen(p);
	  if (count == 1 && (*p == '\n' || *p == '\r')) {
		  // Empty line
			flowp->count = 0;
	      	return (char*)NULL;
	  }
	  inword = 0;
	} else {
	// Restore previous location on flow
	  p = flowp->curp;
	  count = flowp->count;
    }
	q = &word[0];
	while (count) {
	  unsigned char c = *p|0x20;
	  if (c < 'a' || c > 'z' ) {
	    p++; // skip all chars but literals
	    count--;
	    if (inword == 1)
	      break;
	  	else
	      continue;
	  }
	  *q++ = *p++;
	  count--;
	  inword = 1;
	}
	*q = '\0';
	size = strlen(word);
	if (size == 0) {
		flowp->count = 0;
	  	return (char*)NULL;
	}
	q = (char *) calloc(1, size+1);
	strncpy(q, word, size+1);
	// Save current location on flow
	flowp->count = count;
	flowp->curp = p;
	return q;
}

char *get_line(flow_t *flowp)
{
	int size = 0;
	int startline = 0;
	char *p = file_buffer + flowp->offset; // start at offset
	char *q = flowp->line;
	char *eof = file_buffer + file_size;

	while(size < MAXLINE - 1 && p < eof) {
		if (*p == '\n' || *p == '\r') {
			p++;
			size++;
	    	if (startline)
	    	  break;
	    	else
	    	  continue;
	 	}
	 	startline = 1;
		*q++ = *p++;
		size++;
	}
	*q = '\0';
	flowp->offset += size; // increment file offset for this flow
//	printf("offset: %x %d line %s\n", flowp->offset, flowp->offset, flowp->line);
	return flowp->line;
}
