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

/**
 * Class that stores words and their frequencies.
 *   @author Dave Reed
 *   @version 11/5/16
 */
public class WordFreq {
    private Map<String, Integer> words;
    
    public WordFreq() {
        this.words = new TreeMap<String, Integer>();
    }
    
    public WordFreq(String filename) {
        this();
        try {
            Scanner infile = new Scanner(new File(filename));
            while (infile.hasNext()) {
                String nextWord = infile.next();
                this.add(nextWord);
            }
            infile.close();
        }
        catch (java.io.FileNotFoundException e) {
            System.out.println("FILE NOT FOUND");
        }
    }
    
    public void add(String newWord) {
        String cleanWord = this.clean(newWord);
        if (this.words.containsKey(cleanWord)) {
            this.words.put(cleanWord, this.words.get(cleanWord)+1);
        }
        else {
           this.words.put(cleanWord, 1);
        }
    }

    public void showAll() {
        for (String str : words.keySet()) {
            System.out.println(str + ": " + words.get(str));
        }
    }
    
    private String clean(String word) {
        word = word.toLowerCase();
        
        int front = 0;
        while (front < word.length() && !Character.isLetterOrDigit(word.charAt(front))) {
            front++;
        }
    
        int back = word.length();
        while (back > 0 && !Character.isLetterOrDigit(word.charAt(back-1))) {
            back--;
        }
        
        if (front < back) {
            return word.substring(front, back);
        }
        return "";
    }
    ////////////////////////////////////////////////////////
    
    public static void main(String[] args) {
    	WordFreq freq = new WordFreq("shakespeare.txt");
        
        freq.showAll();
    }
}
