#include <stdio.h>
#include <stdlib.h>
#include <graphics.h>
#include <conio.h>
#include <time.h>
#define EAST 0
#define SOUTH 1
#define WEST 2
#define NORTH 3
#define XMAX 640
#define YMAX 480
#define COUNTER_MAX 1512000
#define OUT_OF_BOUNDS 700
#define RULE_MAX 1023


main()
{
struct big {
  char a[YMAX];
  };
struct big *b[XMAX];
int x,y;
long direction=0;
int rule;
int g_driver,g_mode;
long counter;
/*  graphics setup */
int color;
	detectgraph(&g_driver,&g_mode);
	initgraph(&g_driver,&g_mode,"c:\TC");
	setbkcolor(BLACK);      /*
	setcolor(BLACK);
	bar(0,0,640,480);         */
	counter=0;
	b[0]=(struct big *) malloc(sizeof(struct big) );
	for (x=1;x<=YMAX;x++) b[0]->a[x]=0;
	for (x=1;x<=XMAX-1;x++)
	{
	     b[x]=(struct big *) malloc(sizeof(struct big) );
	     b[x] = b[0];

	}
	x=320;
	y = 200;
	srand(time(NULL) % 37);
	rule =0;
  while (1) {
       rule =rand();
       switch (direction ) /* move the ant forward one step */
	{
	case EAST:
	  if (rule > (RAND_MAX/2) ) {
		 x--;}
	  else {
		 x++;}
		 break;
	 case SOUTH:
	  if (rule > (RAND_MAX/2) ) {
		  y++;}
	  else {
		 y--;}
		 break;
	 case WEST:
	  if (rule > (RAND_MAX/2) ) {
		 x++;}
	  else {
		 x--;}
		 break;
	 case NORTH:
	  if (rule > (RAND_MAX/2) ) {
		y--;}
	  else {
		 y++;}
		 break;
	  }

	if (x < 1 || x >= XMAX || y < 1 || y >= YMAX)
					    /* is he out of bounds? */

				 {break;}   /* he is out of bounds, quit */
  color = getpixel(x,y);
  color++;
  if (color > 15) color = 15;
  switch (b[x]->a[y]) {
		  case 1:          /* he's on white */
			direction++;  /* change direction one to right */
			if (direction > NORTH) { direction = EAST;}
			putpixel(x,y,color);  /* make square black */
			b[x]->a[y]=0;
			break;
		  case 0:        /* he's on black */
			direction--;   /* change direction one to left */
			if (direction < EAST ) { direction = NORTH; }
			putpixel(x,y,color);   /* make square white */
			b[x]->a[y]=1;
			break;
			}
  counter++;
  if (counter >= COUNTER_MAX) break;

  }

  settextstyle(TRIPLEX_FONT,HORIZ_DIR,0);
  setcolor(WHITE);
  outtextxy(20,430,"Press any key");
  getche();
  closegraph();
  return;
}

