// produce a list of random words
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>

// create a "random" seed for random number generation
int make_seed() {
  // use current time in second * processor time
  time_t now = time(NULL);
  clock_t ticks = clock();
  
  return now * ticks;
}

// trim of leading/trailing punctuation and digits, convert to lower case
char * fixed(char *s) {
  if (s == NULL) return NULL;

  // find beginning of string - skip past non-alpha
  char * begin = s;
  while (*begin && ! isalpha(*begin)) begin++;

  // last character in the string
  char * last = begin + strlen(begin) - 1;
  
  // decrease last as long as it is non-alpha and not before begin
  while (begin <= last && ! isalpha(*last)) {
    *last = '\0';
    last--;
  }

  // if went past beginning of string
  if (last < begin) return begin;

  // everything in between begin and last - tolower them
  for(char *p=begin; p <= last; p++)
    *p = tolower(*p);

  return begin;
}

int main(int argc, char * argv[]) {
  // usage statement
  if (argc < 3) {
    printf("Usage: ./randomWords howMany wordsFile.txt [seed]\n");
    printf("  randomWords will choose howMany random words, which are each\n"
	   "  chosen from the words in wordsFile.txt.\n"
	   "  If a seed is given as input it is used to seed the pseudorandom number generator\n"
	   "  (so you can use the same seed and get the same \"random\" list each time you\n"
	   "  run the program.  If no seed given, then a seed is used based on\n"
	   "  the current time in seconds and the # clock cycles elapsed in the program\n"
	   "  generating the numbers.  Note - srand and rand from the C standard library\n"
	   "  are used for generating the pseudorandom #'s.\n\n");
    exit(0);
  }

  // get args 
  int howMany = atoi(argv[1]);
  const char * wordsFile = argv[2];

  // seed the random number generator
  int seed;
  if (argc > 3) seed = atoi(argv[3]);
  else seed = make_seed();
  srand(seed);

  // read words from file
  int sizeArray = 1000;
  int numWords = 0;
  char **words = (char **) malloc(sizeof(char *) * sizeArray);

  // note that we store duplicate words multiple times
  FILE * f = fopen(wordsFile, "r");
  assert(f != NULL);
  char s[100];
  while (fscanf(f, "%99s", s) == 1) {
    char * s_fixed = fixed(s);
    
    if (strlen(s_fixed) <= 0) continue;
    
    if (numWords >= sizeArray) {
      words = realloc(words, sizeArray*2*sizeof(char *));
      sizeArray *= 2;
    }
    words[numWords++] = strdup(s_fixed);
  }
  fclose(f);

  assert(numWords > 0);

  // how pick random words
  for(int i=0; i < howMany; i++) {
    // pseudorandom int
    int r = rand();

    r = (r % numWords);
    printf("%s\n", words[r]);
  }
  return 0;
}