import daj.*;
import java.math.*;

public class ConvexHull extends Application {
  public static int n;
  public static int N;

  Node nodes[][];

  public static void main(String[] args) {
    n = 4;
    N = 4;

    if(args.length > 0) {
      n = Integer.parseInt(args[0]);
    }
    if(args.length > 1) {
      N = Integer.parseInt(args[1]);
    }

    if(N < 4) {
      System.err.println("need at least 4x4 nodes.");
      N = 4;
    }
    if(n % N != 0) {
      n = n + (n % N);
      System.err.println("nr. of points must divide N. Using " + n + " points");
    }
      
    new ConvexHull().run();
  }
  
  public ConvexHull() {
    super("Convex Hull", 400, 400);
    n = 60;
    N = 4;
  }

  void makeLink(int i, int root, boolean row) {
    int c1 = root * 2 + 1;
    int c2 = root * 2 + 2;

    if(c1 < N) {
      if(row) {
	link(nodes[i][root], nodes[i][c1]);
	link(nodes[i][c1], nodes[i][root]);
      } else {
	link(nodes[root][i], nodes[c1][i]);
	link(nodes[c1][i], nodes[root][i]);
      }
    }

    if(c2 < N) {
      if(row) {
	link(nodes[i][root], nodes[i][c2]);
	link(nodes[i][c2], nodes[i][root]);
      } else {
	link(nodes[root][i], nodes[c2][i]);
	link(nodes[c2][i], nodes[root][i]);
      }
    }

    if(c1 < N) 
      makeLink(i, c1, row);
    if(c2 < N)
      makeLink(i, c2, row);
  }
  
  public void construct() {

    DrawWindow window = new DrawWindow("ConvexHull", 400,400);

    nodes = new Node[N][N];

    // create nodes
    for(int i=0; i < N; i++) 
      for(int j=0; j < N; j++) {
	int x = 50 + (int)( 300.0 * (double)(j) / (double)(N-1));
	int y = 50 + (int)( 300.0 * (double)(i) / (double)(N-1));
	nodes[i][j] = node(new ConvexHullNode(window, j, i, n, N), ""+i+","+j, x, y);
      }
    
    // make tree connections
    for(int i=0; i < N; i++) {
      makeLink(i, 0, true);
    }
    for(int i=0; i < N; i++) {
      makeLink(i, 0, false);
    }

    //	  link(nodes[i], nodes[j]);
  }
  
  public String getText() {
    return "Compute the Convex Hull of a set of points in paralle.";
  }
}

