package maps;

import java.io.*;
import java.util.*;

//----------------------------------------------------------

public class Maps {

	BufferedReader reader;
	Map<String, Integer> WordCount;

//----------------------------------------------------------

	// opens a file and attaches reader to it
	
	Maps(String fileName)
	{
		WordCount = new TreeMap<String, Integer>();  // could be HashMap...but this will be sorted by key
		 
		try {
			
			// set input and output filenames
			
			File inFile = new File(fileName);
			FileReader fileReader = new FileReader(inFile);	
			reader = new BufferedReader(fileReader);
			
		} catch (Exception ex) {
			System.out.println("Exception handler!");
			ex.printStackTrace();
		}	
	}
	
//----------------------------------------------------------

	// update frequency for this word
	
	void count_one_word(String word)
	{
		Integer Count = WordCount.get(word);
		if (Count == null) 
			WordCount.put(word, 1);
		else
			WordCount.put(word, Count + 1);
	}

//----------------------------------------------------------

	void count_all_words()
	{
		try {
									
			// line by line

			while (true) {

				// get entire line as one String

				String line = reader.readLine();

				// end of file?

				if (line == null)
					break;

				// split line into words 

				String[] words = line.split("[()_:;\"\\?\\!\\.\\-,\\s]+");

				// iterate over words on *this* line, writing each to output file

				for (String word : words)
					if (word.length() > 0 && Character.isLetter(word.charAt(0)))
						count_one_word(word.toLowerCase());

			}

			reader.close();

		} catch (Exception ex) {
			System.out.println("Exception handler!");
			ex.printStackTrace();
		}	
	}
	
//----------------------------------------------------------

	public static void main(String[] args) {
	
		/*
		Map<String, Integer> HM = new HashMap<String, Integer>();  
			 
		HM.put("Bob", 22);
		HM.put("Dan", 30);
		HM.put("Sarah", 26);
		HM.put("Jen", 22);
		
		
		System.out.println(HM);
//		System.out.println(HM.get("Dan"));
	//	System.out.println(HM.get("John"));
		//	System.out.println(HM.containsValue(22));
		System.out.println(HM.values());
		// HM.values(), etc.
		
		System.exit(1);
		*/
		
		Maps M = new Maps("getty.txt");
//		Maps M = new Maps("bts.txt");
		M.count_all_words();
		
		System.out.println(M.WordCount);
	
	}

}

