/* Problem 2--Spell Check
   This problem wasn't a difficult one.  Just go through the dictionary
   word by word to see which words match. */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE *in, *out;

char Dict[1001][22];
int wct=0;

int main (int argc, char **argv);
void Process (char *word);
int Match (char *a, char *b);

int main (int argc, char **argv) {

  char word[22];

 in = fopen ("prob2.in","r");
 out = fopen ("prob2.out","w");
 while (1) {
  fgets (Dict[wct],22,in);
  Dict[wct][strlen (Dict[wct])-1] = 0; /* Read dictionary */
  if (Dict[wct][0]==0) break;
  wct++;
 }
 while (1) {
  fgets (word,22,in);
  word[strlen (word)-1] = 0; /* Get Gilligan words */
  if (word[0]==0) break;
  Process (word);
 }
 fclose (in);
 fclose (out);
 return EXIT_SUCCESS;
}

/* Process prints out the matches for the given Gilligan word. */
void Process (char *word) {

  int i;

 fprintf (out,"Matches for %s:\n",word);
 for (i=0; i < wct; i++) /* If it matches, print it. */
  if (Match (Dict[i],word)) fprintf (out,"%s\n",Dict[i]);
 fprintf (out,"\n");
}

/* Match determines if two words match */
int Match (char *a, char *b) {

  int i, ct;

 if (strlen (a) != strlen (b)) return 0; /* Differing lengths */
 ct = 0; /* count differing letters */
 for (i=0; i < (int)strlen (b); i++) ct += a[i] != b[i];
 return ct <= 1; /* good if 1 or 0 differing letters */
}
