#include <vga.h>
#include <stdlib.h>

#include "sintab.h"

#define S() (srand48(getpid()))
#define R(x) (drand48()*x)

#define XSIZE 320/XMAG
#define YSIZE 200/YMAG
#define XMAG 4
#define YMAG 4
#define SPOTS 4
#define MOVE 4
#define DIAG

int spots[SPOTS][2];
char line[XSIZE*XMAG];

int world[YSIZE][XSIZE][2];
#define W(x,y) (world[y][x][f])
#define O(x,y) (world[y][x][1-f])

frame() {
	static int f=0;
	int x,y,xx,yy,i,j;
	char *lp;


	f=1-f;
	yy=0;
	for(i=0;i<SPOTS;i++) 
	O(spots[i][0],spots[i][1])+=512;
	for(y=0;y<YSIZE;y++) {
		lp=line;
		for(x=0;x<XSIZE;x++) {
			if((y==0)||(x==0)||(y==(YSIZE-1))||(x==(XSIZE-1))) W(x,y)=0;
			else W(x,y)=(
#ifdef DIAG
				O(x-1,y-1)+O(x-1,y+1)+O(x+1,y-1)+O(x+1,y+1)+
#endif
				O(x,y+1)+O(x,y-1)+O(x-1,y)+O(x+1,y))
#ifdef DIAG
				/8-1;
#else
				/4-1;
#endif
			if (W(x,y)<0) W(x,y)=0;
			i=W(x,y); if(i>255)i=255;
			for(xx=0;xx<XMAG;xx++) *(lp++)=i;
		}
		for(xx=0;xx<YMAG;xx++) vga_drawscansegment(line,0,yy++,XSIZE*XMAG); 
	}
	for(i=0;i<SPOTS;i++) for(j=0;j<MOVE;j++) {
		spots[i][0]+=((int)R(3))-1; if(spots[i][0]<1)spots[i][0]=1; if(spots[i][0]>XSIZE-2)spots[i][0]=XSIZE-2;
		spots[i][1]+=((int)R(3))-1; if(spots[i][1]<1)spots[i][1]=1; if(spots[i][1]>YSIZE-2)spots[i][1]=YSIZE-2;
	}
}
	
main(int argc, char **argv[]) {
	int i;

	S();

	vga_setmode(G320x200x256); 
	for(i=0;i<256;i++)
		if(i<64) vga_setpalette(i,i,0,0);
		else if(i<128) vga_setpalette(i,63,i-64,0);
		else if(i<192) vga_setpalette(i,63,63,i-128);
		else vga_setpalette(i,255-i,255-i,255-i);

	for(i=0;i<SPOTS;i++) {spots[i][0]=R(XSIZE-2)+1; spots[i][1]=R(YSIZE-2)+1; }

 	while(1) frame();
}
