//This is the remote object which handles fractal calculations
package alis;

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

public class FractalComputer implements Serializable {
  
  Color[] color;

  double currentX;
  double currentY;
  double xstep;
  double ystep;
  
  double re, im, retemp;
  double pointre, pointim;
  int currentIteration;
  int MAX_STEPS;
  double a,b,c,d;

  public FractalComputer(Color[] newcolor) {
    color=newcolor;
  }

  //Calculates a portion of the fractal.  Doesn't use cs3.Complex since it is slow.
  public PixelBuffer compute(Rectangle bounds, double[] darray, Integer max) {

    a=darray[0];
    b=darray[1];
    c=darray[2];
    d=darray[3];

    currentX=a;
    currentY=b;
    xstep=c/bounds.width;
    ystep=-d/bounds.height;
    MAX_STEPS=max.intValue();

    PixelBuffer p=new PixelBuffer(bounds);

    for(int i=bounds.y; i<(bounds.y+bounds.height); i++) {
      for(int j=bounds.x; j<bounds.x+bounds.width; j++) {
	re=currentX; im=currentY;
	pointre=currentX; pointim=currentY;
	for(currentIteration=1; currentIteration<MAX_STEPS; currentIteration++) {
	  retemp=re*re-im*im+pointre;
	  im=2*re*im+pointim;
	  re=retemp;
	  if((re*re+im*im)>=4) break;
	}
	  if(currentIteration==MAX_STEPS)
	    p.plot(j,i,color[0]);
	  else
	    p.plot(j,i,color[currentIteration]);	
	currentX+=xstep;
      }
      currentY=currentY+ystep;
      currentX=a;
    }

    return p;
  }
  
}

