/* Plots fractal n-gons 
 * Jepler
 * Thu Jun 30 01:30:20 CDT 1994
 */
#include <math.h>
#include <memory.h>
#include <vga.h>

#ifdef CRAPPY_GRAFIX
#define SX 320
#define SY 200
#else
#define SX 640
#define SY 480
#endif
int x,y;
int *xp,*yp;
int p,q,c;
int r,s;
double rr;
double dx0=0,dy0=0,dx1=0,dy1=0;
int points=2<<20;

#define MIN(a,b) ((a)<(b)?(a):(b))
#define MAX(a,b) ((a)<(b)?(b):(a))

main(int argc, char **argv) {
	vga_init();

	if (argc!=2) {
		printf("usage: %s #\nTo draw n-sided polygonal fractal",argv[0]);
		return 1;
	}

	p=atoi(argv[1]);
	
	if(!(xp=malloc((p)*sizeof(int)))||!(yp=malloc((p)*sizeof(int))))  {
		printf("Malloc error.  Sorry!\n");
		return 1;
	}


	rr=M_PI/p;
	for(q=0;q<p;q++) { /* Determine how to scale it */
		dx0=MIN(dx0,sin(rr+2*M_PI*q/p)); dx1=MAX(dx1,sin(rr+2*M_PI*q/p));
		dy0=MIN(dy0,cos(rr+2*M_PI*q/p)); dy1=MAX(dy1,cos(rr+2*M_PI*q/p));
	}

	for(q=0;q<p;q++) { /* And now in screen coords */
		xp[q]=(sin(rr+2*M_PI*q/p)-dx0)/(dx1-dx0)*SX;
		yp[q]=(cos(rr+2*M_PI*q/p)-dy0)/(dy1-dy0)*SY;
		printf("%d %d\n",xp[q],yp[q]);
	}

	rr=0;
	for(q=0;q<((p+3)/4);q++)
		rr+=cos(2*M_PI*q/p);

	rr=1-.5/rr;

	r=rr*32768;
	s=32768-r;

	x=*xp; y=*yp;

#ifdef CRAPPY_GRAFIX
	vga_setmode(G320x200x256);
	gl_setcontextvga(G320x200x256);
#else
	vga_setmode(G640x480x256);
	gl_setcontextvga(G640x480x256);
#endif

	for(q=0;q<128;q++)  {
		gl_setpalettecolor(q,q/2,q/2,q/2);
	}

	while(points--) {
		q=rand()%p;
		x=(s*x+r*xp[q])/32768;
		y=(s*y+r*yp[q])/32768;
		c=((int)gl_getpixel(x,y))+1;
		gl_setpixel(x,y,c>127?127:c);
	}

	vga_setmode(TEXT);
}
