#include <exec/types.h>
#include <intuition/intuition.h>
#include <stdio.h>
#include <graphics/gfxmacros.h>
#include <math.h>

/* 
might be some extra system stuff defined
due to block cut'n paste overkill...
*/

/* system functions */
extern struct Window *OpenWindow();
extern struct Library *OpenLibrary();

/* system variables */
struct IntuitionBase *IntuitionBase;
struct GfxBase *GfxBase;
struct Window *w;
struct IntuiMessage *msg;
struct RastPort *rp;


void open_all(), close_all(), draw_tile();

struct NewWindow myWindow =
{
      0,0,
      640, 200,
      0,
      1,
      CLOSEWINDOW,
      SMART_REFRESH | WINDOWCLOSE | ACTIVATE | BORDERLESS | GIMMEZEROZERO,
      NULL,
      NULL,
      (UBYTE *)"Truchet Tiles",
      NULL,
      NULL,
      40, 20,
      640, 200,
      WBENCHSCREEN
};

/* area fill patterns for tiles */
UWORD tile0[] = 
{
	0x0080,0x0100,0x0600,0xf80f,
	0x0030,0x0040,0x0080,0x0080
};


UWORD tile1[] = 
{
	0x0080,0x0040,0x0030,0xf80f,
	0x0600,0x0100,0x0080,0x0080
};


main()
{
	short i, j, bit, seed;
	double rnum;
	printf("Enter a number between 1 and 1000.\n");
	scanf("%h",&seed);
	
	open_all();

	SetAPen(rp,2);
	SetBPen(rp,3);
	SetDrMd(rp,JAM2);
	
	if (seed < 1 || seed > 1000) seed = 1;  
	for (i = 0; i <= seed; ++i) rnum = drand48(); /*pseudo randomizer*/
		for (i = 0; i <= 624; i += 16)        /* x loop */
	{
		for (j = 0; j <= 176; j += 16)        /* y loop */
		{
			rnum = drand48();  /* drand48() is a Lattice */
			if (rnum <= 0.5)   /* random number function */
			{
				bit = 0; 
			}
			else   /* bit picks one of the 2 tile types */
			{
				bit = 1;
			}
			
			draw_tile(i,j,bit);  /* draws the proper tile */
		}
	}
	
	Wait (1 << w->UserPort->mp_SigBit);  /* wait for close gadget */
	close_all();                         /* close up shop */
}





void draw_tile(x,y,b)
short x, y, b;
{

	if(b) 
	{
		SetAfPt(rp,tile1,3);	/*the bit flag (b here) picks one*/
	}				/*type of tile or the other      */
	else 
	{
		SetAfPt(rp,tile0,3);
	}
			
	RectFill(rp,x,y,x+15,y+15);	/* area fill using pattern */
}



void open_all()
{
	if((IntuitionBase = (struct IntuitionBase *)
	  	OpenLibrary("intuition.library", 0L)) == NULL)
			exit(1);
	if ((GfxBase = (struct GfxBase *)
		OpenLibrary("graphics.library", 0L)) == NULL)
			exit(1);
	
	
	if ((w = OpenWindow(&myWindow)) == NULL)
		exit(1);
	rp = w->RPort;

}


void close_all()
{
	if (w) CloseWindow(w);
	if (GfxBase) CloseLibrary(GfxBase);
	if (IntuitionBase) CloseLibrary(IntuitionBase);
}



