// P0402.java:$B%^%s%G%k%V%m=89g(B f(z)=z*z+a

import java.awt.*;
import java.awt.event.*;
import Glib.*;

public class P0402 extends xApplet
	implements ActionListener
{	Button bt;
	xGraphics G;
	int NL=1000,PW=320,step=1,flag;
	double Div=4.0;
	xComplex cc=new xComplex(-1.479,0.0);
	double cw=0.015;
	xComplex z0=new xComplex(0.0,0.0);
	xComplex[]Z=new xComplex[NL+1];
	xComplex c;

	public void init()
	{	setLayout(new FlowLayout(FlowLayout.LEFT));
		bt=new Button("$BIA2h(B");
		bt.addActionListener(this);
		add(bt);
		app_init(7);
		G=new xGraphics(getGraphics());
		G.set0(CA,1);
		G.setcycspectra(6);
	}

	public void actionPerformed(ActionEvent evt)
	{	if(evt.getSource()==bt)
			paint2();
	}

	private void paint2()
	{	xTimer t=new xTimer();
		t.settimer();
		Point p=new Point();
		for(p.x=-PW;p.x<=PW;p.x=p.x+step)
		{	double x=cw/PW*p.x+cc.x;
			for(p.y=0;p.y<=PW;p.y=p.y+step)
			{	double y=cw/PW*p.y+cc.y;
				c=new xComplex(x,y);
				int n=mandelbrot();
				if(n>=0)
				{	G.putpixel(p.x,p.y,getspectrum(n));
					G.putpixel(p.x,-p.y,getspectrum(n));
				}
				else
				{	G.putpixel(p.x,p.y,240);
					G.putpixel(p.x,-p.y,240);
				}
			}
		}
		t.gettimer();
		G.textout(10,60,"$BIA2h;~4V(B="+t.Time,240,16);
		G.textout(10,80,"z0="+z0.x+"+"+z0.y+"i",240,16);
		double c0=xMath.fdouble(cc.x-cw,3);
		double c1=xMath.fdouble(cc.x+cw,3);
		G.textout(10,100,"a="+c0+"$B!A(B"+c1,240,16);
		c0=xMath.fdouble(cc.y-cw,3);
		c1=xMath.fdouble(cc.y+cw,3);
		G.textout(10,120,"b="+c0+"$B!A(B"+c1,240,16);
	}

	private xComplex recur(xComplex z)
	{	xComplex zz=xMath.plus(xMath.mlt(z,z),c);
		double s=xMath.abs2(zz);
		if(s>Div)
			flag=-1;
		else
			flag=1;
		return zz;
	}

	private int mandelbrot()
	{	Z[0]=z0;
		for(int n=0;n<NL;n++)
		{	Z[n+1]=recur(Z[n]);
			if(flag<0)
				return n;
		}
		return -1;
	}

	private int getspectrum(int n)
	{	if(n<240)
			return n;
		else
			return 239;
	}
}
