// Michael Tartaglia
// Program reads in parameters from HTML and spits out information
//		as part of a bar graph


import java.awt.*;
import java.applet.Applet;

public class BarGraph extends Applet {
 private int numToGraph = 0,		// NUMBER OF ELEMENTS TO GRAPH
             MAX_ARRAY = 10,		// MAXIMUM ELEMENTS TO GRAPH
             i = 0,					// INDEX
				 total;					// SUM OF ALL ELEMENTS VALUES (USED TO CALC %)
 private int[] values = new int[MAX_ARRAY];	// VALUES TO GRAPH

 public void init() {
    setBackground(Color.white);
 }

 public void start() {
    try {
	 	 // READ IN PARAMETERS FROM HTML WHILE THEY EXIST
       while (getParameter("row"+(i+1)) != null) {
          numToGraph++;
          values[i] = Integer.parseInt(getParameter("row"+(i+1)));
          i++;
       }
    } catch (NumberFormatException nfe) {numToGraph--;}
      catch (ArrayIndexOutOfBoundsException aioobe) {numToGraph--;}
		total = getTotal();
      repaint();
 }

 public void paint(Graphics g) {
    int y = 0, x = 10, percent,
        red,grn,blu;
    String what;

	 // SET FONT AND POST QUESTION TO USER
    g.setFont(new Font("Arial",Font.BOLD+Font.ITALIC,12));
    if ((what = getParameter("question")) != null)
       g.drawString(what,x,16);
    
	 // PRINT OUT EACH BAR IN GRAPH
    for (int i = 0; i < numToGraph; ++i) {
       y += 25;	// SET UP FOR NEXT ROW
       percent = (int)Math.round(100*((double)values[i]/(double)total));
       red = (int)(Math.random()*155);
       grn = (int)(Math.random()*155);
       blu = (int)(Math.random()*155);

       g.setFont(new Font("Courier",Font.BOLD,14));
       g.setColor(new Color(red,grn,blu));		// SET VALUE OF GRAPH
       g.fill3DRect(x,y,values[i]*25,22,true);	// DRAW ACTUAL BAR

       g.setColor(Color.white);					// # COLOR FOR BAR
       g.drawString(percent+"%",10+5,y+15);	// # REPRESENTED BY BAR

       if ((what = getParameter(""+(1+i))) != null) {
          g.setColor(Color.black);				// LABEL COLOR FOR BAR
          g.setFont(new Font("Arial",Font.PLAIN,14));
          what += " (" + values[i] + " votes)";
          g.drawString(what,values[i]*25+15,y+15); // PRINT LABEL AND # OF VOTES
       }
    }
    try {Thread.sleep(2500);}		// WAIT 2.5 SECONDS
    catch (InterruptedException ie) {}
    repaint();			// RECYCLE METHOD TO CYCLE COLORS OF BARS
 }

 public int getTotal() {
  // FUNCTION: returns the total value of the array
  int totalOfValues = 0;
  for (int i = 0; i < MAX_ARRAY; ++i)
   totalOfValues += values[i];
  return totalOfValues;
 }

}
