#
# mandelbrot
#
@PROBLEM mandelbrot
@LANGUAGE C
@MAJOR COL
@PATH /Mandelbrot/
@DESCRIPTION
Compute the number of iteration of the mandlebrot
recursion until either divergence has been observed, or
the maximum number of iterations has been reached.
@INPUT 7
@OBJECT SCALAR I MAX
Maximum number of iteration
@OBJECT SCALAR D X1
Xstart
@OBJECT SCALAR D DX
Xstep
@OBJECT SCALAR D X2
Xend
@OBJECT SCALAR D Y1
Ystart
@OBJECT SCALAR D DY
Ystep
@OBJECT SCALAR D Y2
Yend
@OUTPUT 1
@OBJECT MATRIX I MANDEL
For each point, the number of iterations. If this number
is equal to the max number, the the corresponding point is
assumed to belong to the Mandelbrot set. 
@COMPLEXITY 4000000,4
@CALLINGSEQUENCE
@ARG I0
@ARG I1
@ARG I2
@ARG I3
@ARG I4
@ARG I5
@ARG I6
@ARG O0

@CODE
double ceil(double);
int i,j,k;
double xa=@I1@[0];
double xd=@I2@[0];
double xb=@I3@[0];
double ya=@I4@[0];
double yd=@I5@[0];
double yb=@I6@[0];
int n1,n2;
double x,y;

n1 = (int)(ceil((xb-xa)/xd))+1;
n2 = (int)(ceil((yb-ya)/yd))+1;

#fprintf(stderr,"xa = %f\\n",xa);
#fprintf(stderr,"xd = %f\\n",xb);
#fprintf(stderr,"xb = %f\\n",xd);
#fprintf(stderr,"ya = %f\\n",ya);
#fprintf(stderr,"yd = %f\\n",yb);
#fprintf(stderr,"yb = %f\\n",yd);
#fprintf(stderr,"n1 = %d\\n",n1);
#fprintf(stderr,"n2 = %d\\n",n2);

if (n2 <= 0)
  return NS_PROT_BAD_VALUES;
if (n1 <= 0)
  return NS_PROT_BAD_VALUES;

@O0@ = (int *)calloc(n1*n2,sizeof(int));

x = xa;y = ya;
for (i=0;i<n1;i++)
{
  for (j=0;j<n2;j++)
  {
    double a=0.0;
    double b=0.0;
    for (k=0;k<=@I0@[0];k++)
    {
      double a1,b1;
      a1 = a*a - b*b + x;
      b1 = 2.0*a*b + y; 
      a = a1;
      b = b1;
      if (a*a + b*b > 4.0)
        break; 
    }
    
    @O0@[i*n2+j] = k; 
    y = y + yd;
  }
  y = ya;
  x = x +xd;
}
*@nO0@ = n1;
*@mO0@ = n2;

@END_CODE
