import java.util.*;
import java.io.*;
import java.awt.*;

public class Iris {
  public static void main(String[] args) 
    throws FileNotFoundException {
    double[ ][ ] iris = readIris( );
    printIris(iris);
    printAverages(iris);
    drawHistogram(iris);
  }
  
  // This reads iris.txt into a 2D array and returns the array.
  public static double[ ][ ] readIris( )
    throws FileNotFoundException {
    Scanner input = new Scanner(new File("iris.txt"));
    int rows = input.nextInt( );
    int columns = input.nextInt( );
    double[ ][ ] iris = new double[rows][columns];
    for (int row = 0; row < rows; row++) {
      for (int col = 0; col < columns; col++) {
        iris[row][col] = input.nextDouble( );
      }
    }
    input.close( );
    return iris;
  }
  
  // This prints the iris array.
  public static void printIris(double[ ][ ] iris) {
    System.out.println("iris looks like\n");
    for (int row = 0; row < iris.length; row++) {
      System.out.println("Row " + row + ": " + Arrays.toString(iris[row]));
    }
  }
  
  // This method prints the averages of each column.
  public static void printAverages(double[ ][ ] iris) {
    int rows = iris.length;
    int columns = iris[0].length;
    // This assignment also initializes the new array with zeroes.
    double[ ] average = new double[columns];
    for (int row = 0; row < rows; row++) {
      for (int col = 0; col < columns; col++) {
        average[col] += iris[row][col];
      }
    }
    for (int col = 0; col < columns; col++) {
      average[col] /= rows;
    }
    System.out.println("The averages are " + Arrays.toString(average));
  }
  
  // This prints a histogram of all the values.
  // The histogram is not very useful, but the code might
  // be serviceable as an example of drawing a histogram.
  // Various magic numbers were determined in advance or by trial and error.
  public static void drawHistogram(double[ ][ ] iris) {
    int rows = iris.length;
    int columns = iris[0].length;
    // This assignment also initializes the new array with zeroes.
    int[ ] counts = new int[80];
    for (int row = 0; row < rows; row++) {
      for (int col = 0; col < columns; col++) {
        int timesTen = (int) Math.round(10 * iris[row][col]);
        counts[timesTen]++;
      }
    }
    
    DrawingPanel panel = new DrawingPanel(500,500);
    Graphics g = panel.getGraphics( );
    // Draw y axis
    g.drawLine(50, 450, 50, 50);
    for (int y = 0; y <= 100; y += 10) {
      g.drawString("" + y, 20, 455 - 4 * y);
      g.drawLine(40, 450 - 4 * y, 50, 450 - 4 * y);
    }
    // Draw x axis
    g.drawLine(50, 450, 450, 450);
    for (int x = 0; x <= 8; x++) {
      g.drawString("" + (double) x, 40 + 50 * x, 480);
      g.drawLine(50 + 50 * x, 460, 50 + 50 * x, 450);
    }
    // Draw a rectangle for each count
    for (int i = 0; i < 80; i++) {
      g.fillRect(49 + 5*i, 450 - 4 * counts[i], 4, 4 * counts[i]);
    }
  }
  
}