#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef float floatpoint;

#ifdef AMIGA
  // This must exist to keep the linker happy
  int _gettimeofday( struct timeval *tv, void *tzvp )
  {
    //Serial.println("_gettimeofday dummy");
    uint64_t t = 0;  // get uptime in nanoseconds
    tv->tv_sec = t / 1000000000;  // convert to seconds
    tv->tv_usec = ( t % 1000000000 ) / 1000;  // get remaining microseconds
    return 0;  // return non-zero for error
  } // end _gettimeofday()
#endif

floatpoint distanceSq(floatpoint* point1, floatpoint* point2) {
	floatpoint px = point1[0] - point2[0];
	floatpoint py = point1[1] - point2[1];
	return (px * px + py * py);
}

int main(int argc, char* argv[]) {
	if(argc<4) {
		printf("usage: %s <width> <height> <no>\n", argv[0]);
		return -1;
	}
	const int WIDTH =atoi(argv[1]);
	const int HEIGHT=atoi(argv[2]);
	const int NO    =atoi(argv[3]);

	floatpoint s,w,xp,yp,xs,ys;
	floatpoint* distanceSqs=malloc(sizeof(floatpoint)*NO);
	floatpoint* a=malloc(sizeof(floatpoint)*WIDTH*HEIGHT);
	floatpoint* points=malloc(sizeof(floatpoint)*NO*3);
	floatpoint* point=malloc(sizeof(floatpoint)*3);
	time_t seconds;
	
	srand(time(0));
	for(int i=0; i<NO; i++) {
		points[i*3+0]=(floatpoint)rand() / ((floatpoint)RAND_MAX + 1.0) * (floatpoint)WIDTH;
		points[i*3+1]=(floatpoint)rand() / ((floatpoint)RAND_MAX + 1.0) * (floatpoint)HEIGHT;
		points[i*3+2]=(floatpoint)rand() / ((floatpoint)RAND_MAX + 1.0) * 256.0;
	}

	xs=WIDTH/WIDTH;
	ys=HEIGHT/HEIGHT;
	yp=0.0;
	seconds = time(NULL);
	for(int y=0; y<HEIGHT; y++) {
		printf("y=%i\n", y);
		yp+=ys;
		xp=0.0;
		for(int x=0; x<WIDTH; x++) {
			xp+=xs;
			point[0]=xp;
			point[1]=yp;
			s=0.0;
			for(int i=0; i<NO; i++) {
				distanceSqs[i]=1.0/distanceSq(point, &points[i*3]);
				s+=distanceSqs[i];
			}
			w=0.0;
			for(int i=0; i<NO; i++) {
				w+=(distanceSqs[i]/s)*points[i*3+2];
			}
			a[y*WIDTH+x]=w;
		}
	}
	printf("calculation: %i s\n", time(NULL)-seconds);

	FILE *write_ptr;
	unsigned char* grey=malloc(sizeof(unsigned char)*WIDTH*HEIGHT);
	for(int y=0; y<HEIGHT; y++) {
		for(int x=0; x<WIDTH; x++) {
			grey[y*WIDTH+x]=a[y*WIDTH+x];
		}
	}
	write_ptr = fopen("WeatherMap.raw","wb");
	int numwritten=fwrite(grey,sizeof(unsigned char),WIDTH*HEIGHT,write_ptr);
	printf("numwritten=%i\n", numwritten);
/*	fflush(write_ptr);
	fclose(write_ptr);*/

	printf("return\n");
	return 0;
}
