#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define MAX_WORDS 50000
#define WORD_LENGTH 25

FILE *fp;
char word [MAX_WORDS][WORD_LENGTH];
int total = 0;    // total words
int counter = 0;

void swap (char *s, int s1, int s2)
{
  char temp;
  temp = s [s2];
  s [s2] = s [s1];
  s [s1] = temp;
}

int compar (char *key, char *member) 
{
//  printf ("key: %s  member: %s\n", key, member);
  return strcmp (key, member);
}

// s is the scrambled word to be checked against all words in the dictionary
void test (char *s) 
{
  char *out;
  int i = 0;

  // printf ("testing %s from a total of %d words\n", s, total);
   out = bsearch (s, word, total, WORD_LENGTH, compar);
  if (out == NULL)
    ; // printf ("out is null\n");
  else {
    printf ("%s found in the dictionary in %d iterations!\n", s, counter);
    exit (0);
  }
  
}

void lw ()
{
  int i = 0, j;
  char c;

  printf ("loading dictionary...\n");
  fp = fopen ("dict", "r");
  while (!feof (fp)) {
    j = 0;
    do {
      c = fgetc (fp);
      if (c != '\n' && !feof (fp)) {
	word [i][j] = c;  
	j++;
      }
    } while ( c != '\n' && !feof (fp));
    for ( ; j < WORD_LENGTH; j++) {
      word[i][j]='\0';
    }
    //    printf ("%s\n", word [i]);
    i++;
  }
  total = i - 1;
  printf ("dictionary loaded...\n");
}

int main (int c, char *argv[])  
{
  char *s = (char *) malloc (strlen (argv[1]) + 10);
  int s1, s2;
  
  srand ( getpid() );

  strcpy (s, argv[1]);
  printf ("unscrambling %s\n", s);

  lw();           // load words

  while (1) {
    counter++;
    s1 = (int) (  (float) strlen (s) * rand() / (RAND_MAX+1.0));
    s2 = (int) (  (float) strlen (s) * rand() / (RAND_MAX+1.0));
    if (s1 != s2) {
      swap (s, s1, s2);
      test (s);
    }
  }    

  return 0;
}

