import java.awt.*;

// Written by Julian Devlin, 8/97, for the text book
// "Introduction to Probability," by Charles M. Grinstead & J. Laurie Snell

public class PowerGraph extends Graph {

	Rectangle myBox;
	JRandom myRand;
	int num;
	int critical;

	public PowerGraph(int n, int m) {
		minX = 0f;
		maxX = 1f;
		minY = 0f;
		maxY = 1f;
		num = n;
		critical = m;
		inset = 30;
		myRand = new JRandom();
	}
	
	public float alpha(float x) {
		float sum = 0f;
		for (int i = critical; i <= num; i++) {
			sum += Combinatorics.bernoulli(num, x, i);	
		}
		return sum;
	}
	
	// Determines size of this object, and scales the coordinates accordingly.
	public void setPoints() {
		Dimension d = size();  //getSize() in 1.1.1
		w = d.width - 2 * inset;				
		h = d.height - 2 * inset;	
		
		length = (int) ((float) w / 4f);
		xCoords = new Float[length];			// Set up arrays for x and y coordinates of data points
		yCoords = new Float[length];
		
		for(int i = 0; i < length; i++) {
			xCoords[i] = new Float(minX +  i * 4 * (float) (maxX - minX) / ((float) w - 1f));
			yCoords[i] = new Float(alpha(xCoords[i].floatValue()));	
		}
		
		pixels = new Point[length];			// Initialize array for actual points to be graphed
		
		if (maxX - minX != 0)
			scaleX = (float) w / (maxX - minX);	// Total width / range
													// = number of pixels for each point
		if (maxY - minY != 0)						// Simalarly for y scale
			scaleY = (float) h / (maxY - minY);
			
		int x, y;									// current x and y coordinates
		for (int i = 0; i < length; i++) {
			// Calculate what the coordinates of each data point should be, then add a Point object to the array
			x = adjX(xCoords[i]);
			y = adjY(yCoords[i]);
			pixels[i] = new Point(x, y);
		}
	}
	
	public void paint(Graphics g) {
		Font f;
		String fName;
		FontMetrics fm;
	
		
		f = g.getFont();
		fName = f.getName();
		f = new Font(fName, Font.PLAIN, 9);
		g.setFont(f);
		fm = g.getFontMetrics();
		
		setPoints();				// When we are ready to paint, the dimensions of the component have been
		setTicks(true, fm);			// set, so we can calculate coordinates of all the points
		g.setColor(new Color(0, 0, 0));
		for (int i = 0; i < length - 1; i++) {		// For each point
			g.drawLine(pixels[i].x, pixels[i].y, pixels[i + 1].x,
				pixels[i + 1].y);				// Connect it to the next point
		}
		
		myBox = new Rectangle(adjX(.6f), adjY(.95f), adjX(.8f) - adjX(.6f),
			 adjY(.05f) - adjY(.95f));
		// Draw the box
		g.drawRect(myBox.x, myBox.y, myBox.width, myBox.height);
		
		drawXAxis(g);
		drawYAxis(g);
		g.setColor(new Color(150, 0, 0));			// Make ticks red
		drawTicks(g);
		g.setColor(new Color(0, 0, 100));			// Make labels blue
		labelTicks(g);
		g.setColor(new Color(0, 0, 0));
	}
		
}