/*****************************************************************
** GraphData - applet to demonstrate graphing data
**
** The data in the EURO array are the values of the
** Euro in US dollars each hour over a 24 hr. period, Jan 3-4,
** 1999 (Source: The Globe and Mail)
**
** (c) Scott MacKenzie, 2004                             
******************************************************************/
import java.awt.*;
import java.applet.*;

public class GraphData extends Applet
{
   private static final double[] EURO = {
      1.175, 1.176, 1.179, 1.182, 1.188, 1.185, 1.187, 1.188,
      1.186, 1.184, 1.180, 1.180, 1.179, 1.180, 1.178, 1.180,
      1.180, 1.180, 1.182, 1.181, 1.182, 1.182, 1.183, 1.183
   };
   private static final int XSIZE = 500;
   private static final int YSIZE = 250;
   private static final int GAP = 50;
   private static final int WIDTH  = XSIZE - 2 * GAP;
   private static final int HEIGHT = YSIZE - 2 * GAP;

   public void paint(Graphics g)
   {
      // draw rectangle around graphics window
      g.drawRect(0, 0, XSIZE - 1, YSIZE - 1);

      // set new origin to bottom-left of graph
      g.translate(GAP, GAP + HEIGHT);

      // draw axes
      g.drawLine(0, 0, WIDTH, 0);    // x axis
      g.drawLine(0, 0, 0, -HEIGHT);  // y axis

      // find minimum and maximum values in array
      double yMin = min(EURO, EURO.length);
      double yMax = max(EURO, EURO.length);

      // label graph
      g.setFont(new Font("Helvetica", Font.PLAIN, 14));
      g.drawString("Euro value (US$) over 24 hr. Jan 3-4, 1999", 75, 16);

      // label y axis with minimum and maximum values
      g.setFont(new Font("Helvetica", Font.PLAIN, 12));
      g.drawString("" + yMax, -34, -HEIGHT + 8);
      g.drawString("" + yMin, -34, 0);

      // find first point of first line to draw
      int x2 = 0;
      int y2 = -(int)((EURO[0] - yMin) / (yMax - yMin) * HEIGHT);

      // draw graph (a series of connected lines)
      for (int i = 1; i < EURO.length; i++)
      {
         int x1 = x2;
         int y1 = y2;
         x2 = (int)((i / (EURO.length - 1.0)) * WIDTH);
         y2 = -(int)((EURO[i] - yMin) / (yMax - yMin) * HEIGHT);
         g.drawLine(x1, y1, x2, y2);
      }
   }

   // find the minimum value in a array
   public static double min(double[] n, int length)
   {
      double min = n[0];
      for (int j = 1; j < length; j++)
         if (n[j] < min)
            min = n[j];
      return min;
   }

   // find the maximum value in an array
   public static double max(double[] n, int length)
   {
      double max = n[0];
      for (int j = 1; j < length; j++)
         if (n[j] > max)
            max = n[j];
      return max;
   }
}

