\ctxlua{metapost.showlog=true}
\def\N{7}
\usemodule[graph]
\startMPinclusions[+]
	PI:=355/113;
	ax:=-3/2;
	bx:=3/2;
	ay:=-5/4;
	by:=5/4;
	R:=2/(1+sqrt(5));

	u:=216/(bx-ax);
	v:=216/(by-ay)*R;

	path p,q;
	numeric W,H;

	numeric freq[];
	freq:=\N;
	freq[0]:=1;
	freq[1]:=2;
	freq[2]:=4;
	freq[3]:=8;
	freq[4]:=16;
	freq[5]:=32;
	freq[6]:=60;

	vardef base =
		currentpicture:=currentpicture shifted (-ax*u,-ay*v);
		draw begingraph((bx-ax)*u,(by-ay)*v);
			setrange(ax,ay,bx,by);
%			autogrid(otick.bot,otick.lft); % Automatically draw ticks and labels on left and bottom
		endgraph;
		currentpicture:=currentpicture shifted (ax*u,ay*v);
		draw (ax*u,ay*v)--(bx*u,ay*v)--(bx*u,by*v)--(ax*u,by*v)--cycle;
		dx:=ax*u-xpart llcorner bbox currentpicture; % Distance between ax and left edge of picture
		dy:=ay*v-ypart llcorner bbox currentpicture; % Distance between ay and bottom edge of picture
	enddef;

\stopMPinclusions

\starttext
	\startMPpage
		base;
		q:=(ax*u-dx,ay*v-dy)--(bx*u+dx,ay*v-dy)--(bx*u+dx,by*v+dy)--(ax*u-dx,by*v+dy)--cycle;
		currentpicture:=nullpicture;
		fill q withcolor 0.99*white;
		draw (-3/2*u,-v)--(-u/2,v) withcolor red;
		draw (-u/2,-v)--(u/2,v) withcolor red;
		draw (u/2,-v)--(3/2*u,v) withcolor red;
		base;
		setbounds currentpicture to q; % "Center" picture by padding right and top
		W:=ceiling(xpart urcorner bbox currentpicture - xpart llcorner bbox currentpicture); % Width of picture
		H:=ceiling(ypart urcorner bbox currentpicture - ypart llcorner bbox currentpicture); % Heigh of picture
	\stopMPpage
	\dorecurse{\N}{
		\startMPpage
			j:=\recurselevel-1;
			N:=1024;
			K:=freq[j];
			x:=-3/2+1/N*3; y:=0;
			for k=1 upto K: y:=y-2*cosd(180*k)/k/PI*sind(k*360*x); endfor;
			p:=(-3/2,0)--(x,y);
			for n=2 upto N:
				x:=-3/2+n/N*3; y:=0;
				for k=1 upto K: y:=y-2*cosd(180*k)/k/PI*sind(k*360*x); endfor;
				p:=p--(x,y);
			endfor;
			fill q withcolor 0.99*white;
			draw p xscaled u yscaled v withcolor blue;
			draw (-3/2*u,-v)--(-u/2,v) withcolor red;
			draw (-u/2,-v)--(u/2,v) withcolor red;
			draw (u/2,-v)--(3/2*u,v) withcolor red;
			base;
			setbounds currentpicture to q; % "Center" picture by padding right and top
		\stopMPpage
	}
\stoptext
