/* words.c - a cheat for Yahoo's Text Twist game.
 * Written 2003-07-15 by Jonathan Gordon. Public domain. */

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

void die_usage()
{
	fprintf(stderr, "usage: words [given letters]\n");
	exit(EXIT_FAILURE);
}

void strdown(char *word)
{
	int i = 0;
	while (word[i]) {
		word[i] = tolower(word[i]);
		i++;
	}
}

void strchomp(char *word)
{
	int len = strlen(word);
	if (isspace(word[len - 1]))
		word[len - 1] = 0;
}

int valid_word(char *word)
{
	int i = 0;
	while (word[i]) {
		if (word[i] < 'a' || word[i] > 'z')
			return 0;
		else
			i++;
	}
	return 1;
}

/* Where w is the given set of letters and word is the dictionary word. 
 * Iteration fix by <haffar@excite.com>, 2004-06-15 */
int correct_letters(char *w, char *word)
{
	int letters_w[25];
	int letters_word[25];
	int i;
	
	for (i = 0; i < 26; i++) {
		letters_w[i] = 0;
		letters_word[i] = 0;
	}

	for (i = 0; i < strlen(w); i++) {
		letters_w[w[i] - 'a']++;
	}

	for (i = 0; i < strlen(word); i++) {
		letters_word[word[i] - 'a']++;
	}

	for (i = 0; i < 26; i++) {
		if (letters_word[i] > letters_w[i])
			return 0;
	}

	return 1;
}

static void check_dict(char *w)
{
	FILE *dict;
	char *word;
	int len;

	len = strlen(w);

	/* On Solaris this should be /usr/dict/words */
	dict = fopen("/usr/share/dict/words", "r");
	if (!dict) {
		fprintf(stderr, "Unable to open dictionary file!\n");
		exit(EXIT_FAILURE);
	}

	word = malloc(1024);
	while (fgets(word, 1024, dict)) {
		strchomp(word);
		if (strlen(word) > len || strlen(word) < 3)
			continue;
		strdown(word);
		if (!valid_word(word))
			continue;
		if (!correct_letters(w, word))
			continue;
		printf("%s\n", word);
	}
	free(word);
	fclose(dict);
}

int main(int argc, char **argv)
{
	if (argc != 2) die_usage();

	strdown(argv[1]);
	if (!valid_word(argv[1])) die_usage();

	check_dict(argv[1]);

	return EXIT_SUCCESS;
}
