import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;

public class WordFreq2 {
    private ArrayList<Word> words;
	private int totalWords;

	public WordFreq2(String fileName) {
	    this.words = new ArrayList<Word>();
	    this.totalWords = 0;
	    
	    try {
	        Scanner infile = new Scanner(new File(fileName));
	        while (infile.hasNext()) {
	            String nextWord = infile.next().toLowerCase();
	            int index = this.findWord(nextWord); 
	            if (index >= 0) {
	                this.words.get(index).increment();
	            }
	            else {
	                this.words.add(new Word(nextWord));
	            }
	            this.totalWords++;
	        }
	    }
	    catch (java.io.FileNotFoundException e) {
	        System.out.println("FILE NOT FOUND: " + fileName);
	    }
	}
	   
    public int getCount(String str) {
	    int index = this.findWord(str.toLowerCase());
        if (index >= 0) {
	        return this.words.get(index).getFrequency();
	    }
	    else {
	        return 0;
	    }
	}
	
	public double getPercentage(String str) {
	    int index = this.findWord(str.toLowerCase()); 
	    if (index >= 0) {
	        return 100.0*this.words.get(index).getFrequency()/this.totalWords;
	    }
	    else {
	        return 0.0;
	    }
	}	    
	    
	public void showCounts() {
	    for (Word nextWord : this.words) {
	        System.out.format("%-20s (%5.1f%%)%n", nextWord,     
	                          this.getPercentage(nextWord.getWord()));

	    }
	}
	
	////////////////////////////////////
	
	private int findWord(String desiredWord) {
        for (int i = 0; i < this.words.size(); i++) {
            if (this.words.get(i).getWord().equals(desiredWord)) {
                return i;
            }
        }
        return -1;
    }
}