// (C) Copyright Jack Culpepper 1997
// This code may not be distributed without permission.
package mandel;

import java.io.*;
import java.util.*;
import java.awt.*;
import gestalt.Connection;
import gestalt.Task;
import gestalt.TaskID;
import mandel.Boundary;
import mandel.Complex;

public class MandelTask extends Task {
  private static final byte max_iter = 100;
  private static final double blow_up = 3.0;
  protected Point res;
  protected Point loc;
  protected Boundary area;
  protected byte[][] data;
  protected int cksum = 0;

  public MandelTask( TaskID id, Point res, Boundary area, Point loc ) {
    super( id );
    init( res, area, loc );
  }

  public MandelTask( Connection c, Point res, Boundary area, Point loc ) {
    super( c );
    init( res, area, loc );
  }

  private void init( Point res, Boundary area, Point loc ) {
    this.res = res;
    this.area = area;
    this.loc = loc;
    this.data = new byte[ res.x ][ res.y ];
  }

  public void run() {
    double area_width = area.right - area.left;
    double area_height = area.top - area.bottom;

    double width_step = area_width / res.x;
    double height_step = area_height / res.y;

    for ( int i = 0 ; i < res.x ; i++ ) {
      for ( int j = 0 ; j < res.y ; j++ ) {
        Complex c = new Complex( area.left + i * width_step,
          area.bottom + j * height_step );
        data[i][j] = mandel( c );
        cksum += data[i][j];
      }
    }

  }

  private byte mandel( Complex c ) {
    Complex z = new Complex( 0, 0 );
    for ( byte i = 0 ; i < max_iter ; i++ ) {
      z = ( z.mul( z ) ).add( c );
      if ( z.abs() > blow_up ) return i;
    }
    return max_iter;
  }

}

