#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#define BUFF_HEIGHT 480
#define BUFF_WIDTH 640

#ifdef BUFF_WIDTH
#define XSIZE BUFF_WIDTH
#else
#define XSIZE 320
#endif

#ifdef BUFF_HEIGHT
#define YSIZE BUFF_HEIGHT
#else
#define YSIZE 244
#endif

#define BSIZE (XSIZE*YSIZE)

#if (BSIZE > 65535)
#define MS SL
#else
#define MS SS
#endif

typedef int * trans_map;

#ifdef MAC
// these are for reading fucked up Little Endian files from fucked up Little Endian machines
#define SS(s) (((s) & 0xff) << 8 | ((s) & 0xff00) >> 8)
#define SL(l) (((l) & 0xff) << 24 | ((l) & 0xff00) << 8 | ((l) & 0xff0000) >> 8 | ((l) & 0xff000000) >> 24)
#else
#define SS(s)  (s)
#define SL(l)  (l)
#endif

#ifndef PI
#define PI 3.14159265399
#endif

main(int argc, char *argv[])
{
	int i,j,k,dx,dy,size,cx,cy,dist;
	int *theTab;
	long lineOut[XSIZE];
	FILE *f;
	float q,ang,p;
	long lOffset, lFull, lBlend, Blend=12;
	
	printf("Making downward spiral tab for %dx%d buffer...\n",XSIZE,YSIZE);
	
	theTab = (int*) malloc(sizeof(int)*BSIZE);
	if (!theTab) {
		printf("Not enough memory!\n");
		exit(1);
	}

	cx = XSIZE / 2;
	cy = YSIZE / 2;
	q = 3.14159265399 / 2;
	p = (float)45 / 180 * PI;
	
	for (j=0;j<YSIZE;j++) {
	
		for (i=0;i<XSIZE;i++) {
		
			if (j==0 || j == YSIZE) {
			
				dx = (float)(cx - i) * 0.75;
				dy = cy - j;
			
			} else {
			
				dist = sqrt((i-cx)*(i-cx) + (j-cy)*(j-cy));
				
				if (i==cx) {
					if (j>cx)
						ang = q;
					else
						ang = -q;
				} else
					ang = atan((float)(j-cy)/(i-cx));
	
				if (i<cx)
					ang += PI;

				dx = ceil(-sin(ang-p)*dist/10.0);
				dy = ceil(cos(ang-p)*dist/10.0);
			
				if (i==0 || i==XSIZE) {
					dx = cx - i;
					dy = (float)(cy - j) * 0.75;
				}
			}

			lOffset = abs(i+dx + ((j+dy)*XSIZE)) % BSIZE;
			lBlend = Blend;
			lFull = lOffset + (lBlend << 24 );

			theTab[i+j*XSIZE] = lFull;
		
		}
		printf(".");
		fflush(stdout);
	
	}
	
	
	printf("\nSaving...\n");
	
	if (!(f = fopen( (argc>1)?argv[1]:"downspiral.tab","wb"))) {
		printf("Error opening downspiral.tab for writing binary\n%s\n",strerror(errno));
		exit(1);
	}
	
	for (j=0;j<YSIZE;j++) {
		
		for (i=0;i<XSIZE;i++)
			lineOut[i] = MS(theTab[i+j*XSIZE]);
	
		fwrite(lineOut,sizeof(long)*XSIZE,1,f);
	}
	
	fclose(f);
	
	printf("Done.\n");
}
