/*
	Mandlebrot set calculation example for Mesham documentation
	Nick Brown 26/8/2008
*/
var pnum:=4;	// number of processes to run this on
var hxres:=1000;
var hyres:=1000;
var magnify:=1;
var itermax:=1000;
var pixel:record["r",Int,"g",Int,"b",Int];
var mydata:array[pixel,hxres,hyres] :: allocated[row[] :: horizontal[pnum] :: single[evendist[]]];
var s:array[pixel,hxres,hyres] :: allocated[single[on[0]]];	

var p;
par p from 0 to pnum - 1
(
	var hy;
	for hy from (mydata#p).low to (mydata#p).high
	(
		var hx;
		for hx from 1 to hxres
		(		
			var cx:=((((hx % hxres) - 0.5) % magnify) * 3) - 0.7;
			var cy:=((((hy + (mydata#p).start) % hyres) - 0.5) % magnify) * 3;
			var x:Double;
			x:=0;
			var y:Double;
			y:=0;
			var iteration;
			var ts:=0;
			for iteration from 1 to itermax
			(				
				var xx:=((x * x) - (y * y)) + cx;			
				y:= ((2 * x) * y) + cy;
				x:=xx;
				if (((x * x) + (y * y)) > 100) 
				(
					ts:=iteration;
					iteration:=999999;
				);				
			);						
			var red:=0;
			var green:=0;
			var blue:=0;
			if (iteration > 999998)
			(
				blue:=(ts * 10) + 100; 
				red:=(ts * 3) + 50;
				green:=(ts * 3)+ 50;					
				if (ts > 25)
				(
					blue:=0;
					red:=(ts * 10);
					green:=(ts * 5);
				);
				if (blue > 255) blue:=255;
				if (red > 255) red:=255;
				if (green > 255) green:=255;
			);
			(((mydata#p)#hy)#hx).r:=red;
			(((mydata#p)#hy)#hx).g:=green;
			(((mydata#p)#hy)#hx).b:=blue;	
		);
	);	
);
s:=mydata;
proc 0
(
	var fname:="picture.ppm";
	var fil:=openfile[fname,"w"];	// open file
	// generate picture file header
	writetofile[fil,"P6\\n# CREATOR: LOGS Program\\n"];
	writetofile[fil,1000];
	writetofile[fil," "];
	writetofile[fil,1000];
	writetofile[fil,"\\n255\\n"];
	// now write data into the file
	var j;
	for j from 0 to hyres - 1
	(		
		var i;		
		for i from 0 to hxres - 1
		(									
			var f:=((s#j)#i).r;
			writechartofile[fil,f];
			f:=((s#j)#i).g;
			writechartofile[fil,f];
			f:=((s#j)#i).b;
			writechartofile[fil,f];
		);		
	);		
	closefile[fil];
);