import java.util.Map;
import java.util.TreeMap;
import java.util.Scanner;
import java.io.File;

/**
 * Simple class that reads in words and keeps track of word frequencies
 * in a Map.
 * @author Dave Reed
 * @version 9/10/10
 */
public class WordFreq {
    private Map<String, Integer> words;

    /**
     * Constructs an empty WordFreq object.
     */
    public WordFreq() {
        words = new TreeMap<String, Integer>();
    }

    /**
     * Constructs a WordFreq object and initializes it by reading words from
     * a file.
     * @param filename the name of the file to be read from
     */
    public WordFreq(String filename) {
        this();
        try {
            Scanner infile = new Scanner(new File(filename));
            while (infile.hasNext()) {
                String nextWord = infile.next();
                this.add(nextWord);
            }
        }
        catch (java.io.FileNotFoundException e) {
            System.out.println("FILE NOT FOUND");
        }
    }

    /**
     * Adds to the word frequency count for a particular word.
     * @param newWord the word to be counted
     */
    public void add(String newWord) {
        String cleanWord = newWord.toLowerCase();
        if (words.containsKey(cleanWord)) {
            words.put(cleanWord, words.get(cleanWord)+1);
        }
        else {
            words.put(cleanWord, 1);
        }
    }

    /**
     * Displays all of the words and their associated frequencies.
     */
    public void showAll() {
        for (String str : words.keySet()) {
            System.out.println(str + ": " + words.get(str));
        }
    }
}
