import java.awt.Color;
import java.awt.Graphics;
import java.io.FileReader;
import java.util.Hashtable;
import java.util.Iterator;

import javax.swing.JFrame;
import javax.swing.JPanel;


public class Histogram extends JPanel {
	public static final int WINDOW_WIDTH = 640;
	public static final int WINDOW_HEIGHT = 480;

	private Hashtable<Character, Integer> counts = new Hashtable<Character, Integer>();
	
	public static void main(final String[] args) {
   		if (args.length == 0) {
   			System.out.println("You must specify a filename!");
   			return;
   		}
		
		JFrame frame = new JFrame("Character Histogram");
      	frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
   		frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
  	 	frame.setLocationRelativeTo(null);
       		
		Histogram graph = new Histogram();
		frame.setContentPane(graph);
		graph.init(args[0]);
		
		frame.setVisible(true);
	}
	
	public void init(String fileName) {
		try {
			FileReader in = new FileReader(fileName);
			int next;
			while ((next = in.read()) != -1) {
				char nextChar = (char)next;
				Integer count = counts.get(nextChar);
				if (count != null) {
					counts.put(nextChar, count.intValue() + 1);
				} else {
					counts.put(nextChar, 1);
				}
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void paint(Graphics g) {
		super.paint(g);
		int barWidth = WINDOW_WIDTH / 26;
		int maxCount = 0;
		Iterator<Integer> values = counts.values().iterator();
		while (values.hasNext()) {
			int next = values.next();
			if (next > maxCount) {
				maxCount = next;
			}
		}
		g.setColor(Color.red);
		for (int i = 0; i < 26; i++) {
			Integer count = counts.get((char)('a' + i));
			if (count != null) {
				int height = (int)(((double)count.intValue() / maxCount) * WINDOW_HEIGHT);
				g.fillRect(i * barWidth, WINDOW_HEIGHT - height - 50, barWidth, height);
				g.drawString((char)('a' + i) + " = " + count.intValue(), i * barWidth, WINDOW_HEIGHT - height - 70); 
			}
		}
	}
	
	
}

