/* On brain-dead PC's, with MICROSOFT, link with /ST:30000 */
/*

    File:          cross.c
    Author:        Graham Toal
    Purpose:       match words with single-char wildcards (cr?ssw?rd p?zzl?s)
    Creation date: 28/06/90 14:01:34
    Lastedit:      28/06/90 14:05:45

    Description:

    (The nice thing about the dawg structure is that it makes utilities
     like this easy to write; none of these small programs has taken
     more than about an hour. This one took five minutes ;-))

*/


/* Manadatory header files */
#include <stdio.h>
#include "dawg.h"
#include "grope.h"
#include "utils.c"

/* Headers here as needed on per-program basis */

/* Spelling library utilities */
#include "init.c"      /* Loading dicts */

#ifdef SYS_MAC
/* To compile with THINK C 4.0, place all the relevant .h and .c
   files in a folder.  Then create a project which contains this main.c
   and the libraries unix and ANSI.
*/
#include <unix.h>
#include <stdlib.h>
#include <console.h>
#endif

/* This one just gets wrong letters */
int
#ifdef PROTOTYPES
fix_cross(
  NODE PCCRAP *dawg, INDEX i,
  char *word, char *res,
  int len, int *found)
#else
fix_cross(dawg, i, word, res, len, found)
NODE PCCRAP *dawg;
INDEX i;
char *word;
char *res;
int len;
int *found;
#endif
{
int endsword, last, ch, target;
NODE node;
INDEX link;

  for (;;) {
    node = dawg[i++];
    ch = (int)((node >> V_LETTER) & M_LETTER);
    last = ((node & (INDEX)M_END_OF_NODE) != 0);
    endsword = ((node & M_END_OF_WORD) != 0);
    link = node & M_NODE_POINTER;

    res[len] = ch; res[len+1] = '\0';
    target = ((int)*word)&255;
    if (ch != 0) {
    if (ch == target || target == '?') {
      if (endsword && *(word+1) == '\0') {
        fprintf(stdout, "word: %s\n", res); (*found)++;
      }
      if (*(word+1) != '\0' && link != 0)
        (void) fix_cross(dawg, link, word+1, res, len+1, found);
    }
    }
    if (last) break;
  }
  return(0==0);
}

int
#ifdef PROTOTYPES
crossword(NODE PCCRAP *dawg, char *word)
#else
crossword(dawg, word)
NODE PCCRAP *dawg;
char *word;
#endif
{
char result[MAX_WORD_LEN];
int i = 0;
  (void)fix_cross(dawg, (INDEX)ROOT_NODE, word, result, 0, &i);
  return(i);
}

int
#ifdef PROTOTYPES
main(int argc, char **argv)
#else
main(argc, argv)
int argc;
char **argv;
#endif
{
NODE PCCRAP *dawg;
INDEX edges;
int each;

#ifdef SYS_MAC
  argc = ccommand(&argv);
#endif

  /* Your program goes here... */
  if (argc == 1) {
    fprintf(stderr, "usage: %s mispeled wurdz\n", argv[0]);
    exit(EXIT_ERROR);
  }
  if (!dawg_init("", &dawg, &edges)) exit(EXIT_ERROR);
  for (each = 1; each < argc; each++) {
    fprintf(stderr, "* Matches:\n");
    if (!crossword(dawg, argv[each])) {
      fprintf(stderr, "(none found)\n");
    }
    if (each+1 != argc) fprintf(stderr, "\n");
  }

  exit(EXIT_OK);
}

