//
// This class takes the computed histogram as an input 
// and displays the graph on to the screen.
//


import Imager;
import java.awt.*;

class HistogramFrame extends Frame
{
  Imager applet;
  int graph[] = new int[256];
  int max, mousex = 0;

  public HistogramFrame() {}
  public HistogramFrame(String title, int histogram[],int x, int y, Imager applet)
  {
    this.applet = applet;	
	setBackground(new Color(16777215));   
    setBounds(x,y,575,300);
    setResizable(false);
    setLayout(new BorderLayout());
    setTitle(title); 
	normalize(histogram);
	show();
  }

  public void normalize(int hist[])
  {
	float factor;
	
	max = 0;		//Normalize for display	
	for (int x = 0; x < 256; x++)   	
  		if (hist[x] > max)
			max = hist[x];
	factor = (float)(250.0/(float)max);
	for (int x = 0; x < 256; x++)
		graph[x] = (int)((float)hist[x] * factor);
	
	repaint();
  }

  public boolean handleEvent(Event event)
  {
    if (event.id == Event.WINDOW_DESTROY)
    {
      dispose();
      return true;
    }
    else if (event.id == Event.MOUSE_UP)
    {
		mousex = event.x;
		if ((getTitle() == "Global histogram") || (getTitle() == "Local histogram"))
		{
			applet.threshold1.setText(Integer.toString((mousex/2)-20));
			applet.threshold2.setText(Integer.toString((mousex/2)-20));
			applet.threshold3.setText(Integer.toString((mousex/2)-20));
			applet.threshold4.setText(Integer.toString((mousex/2)-20));
		}
		else if (getTitle() == "NE Histogram")
			applet.threshold1.setText(Integer.toString((mousex/2)-20));
		else if (getTitle() == "NW Histogram")
			applet.threshold2.setText(Integer.toString((mousex/2)-20));
		else if (getTitle() == "SW Histogram")
			applet.threshold3.setText(Integer.toString((mousex/2)-20));
		else if (getTitle() == "SE Histogram")
			applet.threshold4.setText(Integer.toString((mousex/2)-20));
			
		applet.updateStatus("Threshold set");
		repaint();
		return true;
    }
    return super.handleEvent(event);
  }

  public void paint(Graphics g)
  {
	g.drawLine(0,280,575,280);
	g.drawLine(35,0,35,300);
	g.drawString("0",37,293);
	g.drawString("128",289,293);
	g.drawString("255",541,293);
	g.drawString(Integer.toString(max),4,40);
	g.setColor(Color.red);
	g.drawString("X Axis = Intensity",380,40);
	g.drawString("Y Axis = Number of pixels",380,55);
	g.drawString("Threshold = "+Integer.toString((mousex/2)-20),50,40);
	g.drawString("Click mouse to select threshold and exit",50,55);
	g.setColor(Color.blue);
	for (int x = 20; x < 276; x++)
		g.drawLine(2*x,280,2*x,280 - graph[x-20]);
  	g.setColor(Color.green);
	g.drawLine(mousex,0,mousex,280);
  }
}
