/* wordsquare-finding code modified for Lonestar MPI system */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>

#ifndef TRUE
#define TRUE (0==0)
#define FALSE (!TRUE)
#endif

NODE *rootdawg;
INDEX nedges;

static char *dawg_w(NODE *dawg, INDEX node, int len, int *count, int target)
{
  static char word[MAX_WORD_LEN];
  NODE *edge;

  for (edge = (NODE *)&dawg[node]; ; edge++) {
    long c;
    c = *edge;           /* Don't rewrite this - its avoiding a MSC bug */
    c = c >> V_LETTER;
    c = c & M_LETTER;
    word[len] = (char)c;
    if ((*edge & M_END_OF_WORD) != 0) {
      word[len+1] = '\0';
      (*count) += 1; // fprintf(stdout, "%s\n", word);
      if (*count == target) return(word);
    }
    c = *edge & M_NODE_POINTER;
    if ((*edge & M_NODE_POINTER) != 0) {
      char *w = dawg_w (dawg, c, len + 1, count, target);
      if (w) return w;
    }
    if ((*edge & M_END_OF_NODE) != 0) break; /* End of node */
  }
  return NULL;
}

char *wordno(NODE *dawg, int no) // 1..count(dawg) inclusive
{
  int i = 0;
  return dawg_w(dawg, ROOT_NODE, 0, &i, no);
}

int main(int argc, char **argv) {
  char fname[256], rfname[256], *topline;
  char w1[MAX], w2[MAX];
  int rank = 0, size = 1;
  int row, col;
  int hi, lo;
  int word, words;
  int found;
  NODE *vnode;
  int ch;

  if (argc == 1) {
    max = 10;
  } else if (argc == 2) {
    max = *argv[1];
    if (isdigit(max)) max = max - '0'; else max = 4;
  } else {
    fprintf(stderr, "syntax: ws 7\n        (or any number 2-9)\n");
    exit(1);
  }

  sprintf(fname, "dawg.%0d", max);
  if (!dawg_init(fname, &rootdawg, &nedges)) {
    fprintf(stderr, "Cannot open %s\n", fname);
    exit(1);
  }

  words = count(rootdawg);

  for (word = lo; word <= hi; word++) { // range is inclusive
    topline = wordno(rootdawg, word); // this is not efficient but we'll live with it...
  }

  exit(0);
  return(0);
}
