import java.io.*;
import java.util.*;
import javax.swing.JFileChooser;

/**
 * Simple demo of Map classes to track
 * how many times every word in a file occurs.
 * @author Owen Astrachan
 */

public class MapDemo
{
    public static double testMap(BufferedReader r, Map map) throws IOException
    {
		double start = System.currentTimeMillis();
		String line;
		while ((line = r.readLine()) != null)
		{
			StringTokenizer toks = new StringTokenizer(line);
			while (toks.hasMoreTokens())
			{
				String s = toks.nextToken().toLowerCase();
				Counter c = (Counter) map.get(s);
				if (c == null)
					map.put(s,new Counter());
				else
					c.increment();
			}
		}
		
		double end = System.currentTimeMillis();
		return (end - start)/1000;
	}

    /**
     * Returns the maximally occurring string in map
     * @returns the word that occurs more frequently than any other
     */
    public static String mostFrequent(Map map)
    {
		Iterator it = map.keySet().iterator();
		int max = 0;
		String smax = null;
		while (it.hasNext())
		{
			String s = (String)it.next();
			int count = ((Counter)map.get(s)).getValue();
			if (count > max)
			{
				max = count;
				smax = s;
			}
		}
		return smax;
    }

    public static void main(String[] args) throws IOException
    {
		String filename = null;

		if (args.length > 0)
	    	filename = args[0];
		else
		{
			JFileChooser chooser = new JFileChooser(".");
			int retval = chooser.showOpenDialog(null);	    
			if (retval == JFileChooser.APPROVE_OPTION)
			{
				filename = chooser.getSelectedFile().getPath();
				System.out.println("testing "+filename);
			}
	    	else
				filename = "MapDemo.java";
		}
	
		BufferedReader reader = new BufferedReader(new FileReader(filename));
		TreeMap tmap = new TreeMap();
		double treeTime = testMap(reader,tmap);

		reader = new BufferedReader(new FileReader(filename));
	    
		HashMap hmap = new HashMap();
		double hashTime = testMap(reader,hmap);

		String max = mostFrequent(tmap);
		System.out.print("TreeMap size = " + tmap.size());
		System.out.println(" in time " + treeTime);
		System.out.println("most frequent word is: " + max);

		max = mostFrequent(hmap);
		System.out.print("HashMap size = " + hmap.size());
		System.out.println(" in time " + hashTime);
		System.out.println("most frequent word is: " + max);

		System.exit(0);   // need this to close JFileChooser
	}
}
