#!/usr/local/bin/cz --
use b
use ccomplex

cstr usage[] = { "x y r max_i rb_i w h", NULL }

Main()
	bm_start()
	num outside = 4 # 16
	long i
	num ox = -0.5, oy = 0, r = 1.5
	long max_i = 100, rb_i = 30, W=0, H=0
	getargs(float, ox, oy, r)
	getargs(long, max_i, rb_i, W, H)
	if args
		usage()
	pr(float, ox, oy, r)
	Pr(long, max_i, rb_i, W, H)
	if W
		space(W, H)
	 else
		space()
	rainbow_init()
	with_pixel_type(mandelbrot)
	bm(program)

def mandelbrot(pixel_type)
	pixel_type *px = pixel()
	num d = 2*r/h, x0 = ox-d*w_2, y0 = oy+d*h_2
#	int smooth_n = 1
	smooth_init()
	cmplx c = x0 + y0*I
	for(y, 0, h)
		repeat(w)
			cmplx w = c
			for i=0; i < max_i; ++i
				w = w*w + c
				if cabs(w) > outside
					break
			smooth_i(i, w)
			*px++ = i < max_i*smooth_n ? rb[i*359 / (rb_i*smooth_n) % 360] : black
			c += d
		if y % 3 == 0
			Paint()
		c = creal(x0) + (cimag(c)-d)*I

def smooth_init()
	int smooth_n = 8 # 32
	num smooth_fac = pow(2, 1.0/smooth_n)
	num smooth_outside[smooth_n]
	for(j, 0, smooth_n)
		smooth_outside[j] = pow(outside, pow(smooth_fac, j))

def smooth_i(i, w)
	num a = cabs(w)
	i = i * smooth_n + smooth_n-1
	for(j, 1, smooth_n)
		if a < smooth_outside[j]
			break
		--i
