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


// WordStat application
// public class WordStat {
public class Question5 {

	public static void main(String[] args) {
		
		// Instantiate File and Scanner objects
		File foobar;
		Scanner input;
		
		// Set up file
		//foobar = new File ("files\\Question5.txt");
		foobar = new File ("files\\callw10.txt");
		
		// Read file 
		try {
			
			// Set up Scanner and delimiter
			input = new Scanner(foobar);
			// The below line took _forever_ to perfect;
			// see the java.util.regex.Pattern API docs for details
			input.useDelimiter("([^a-zA-Z']+)"); // Non-alphabetic characters
			
			// Set up variables
			String buffer;
			ArrayList<String> words = new ArrayList<String>();
			ArrayList<Integer> counts = new ArrayList<Integer>();
			
			// Add the word and increase respective counter
			while (input.hasNext()) {
				
				// Set line to buffer
				buffer = input.next().toLowerCase();

				// If buffer word not in list
				if (words.indexOf(buffer)==-1) {
					if (words.isEmpty()) { // If empty list
						words.add(buffer); // First word!
						counts.add(1); // Count 1 of first word!
					} else { // If not empty list
						// Loop check from 0 to end
						int i = 0;
						while (i <= words.size()) {
							// Past last element
							if (i >= words.size()) {
								// Add word to end
								words.add(buffer);
								counts.add(1);
								break;
							// Buffer word comes before checking word
							} else if (buffer.compareTo(words.get(i)) < 0) {
								// Add word in front of checking word
								words.add(i,buffer);
								counts.add(i,1);
								break;
							// Go to the next word for checking
							} else {
								i++;
							}
						}
					}
				} else { // If buffer word is in list
					// Increase word's count
					counts.set(words.indexOf(buffer),counts.get(words.indexOf(buffer))+1);
				}
			}
			
			// Clean up
			input.close();
			
			// Report results
			// Format for style!
			System.out.format("%-20s %-1s\n", "WORD", "OCCURENCES");
			for (int i = 0; i < words.size(); i++) {
				System.out.format("%-20s %-1s\n", words.get(i), counts.get(i));
			}
			
		} catch (java.io.FileNotFoundException e) {
			
			// From "input = new Scanner(foobar);"
			System.err.println("Error: file " + foobar + " not found.");
			e.getMessage();
			System.exit(1);
		}

	}

}
