#include "../ninox.h"

main(int argc, char *argv[])
	{
	FILE *z;
	struct Image *img;
	double total,avg;
	int npix,i;
	char *dst_fname;
	unsigned short *udata;
	double *fdata;

	if (argc != 2) {
	   printf("Usage: fits_avg image.fit\n");
	   exit(1);
	   }

	dst_fname = Malloc(strlen(argv[1]) + 32);
	strcpy(dst_fname,argv[1]);
	i = strlen(dst_fname)-1;
	while(i && dst_fname[i] != '.') --i;
	sprintf(dst_fname+i,"-avg.fit");

	img = LoadImage(argv[1],dst_fname);
	if (! img) {
	   printf("Loading image '%s' failed\n",argv[1]);
	   exit(1);
	   }

	// Average the pixels
	total=0;
	npix = img->width * img->height;
	fdata = (double *)Malloc(npix * sizeof(double));

	// first 2 pixels are special, do not change them or count them
	fdata[0]=1; fdata[1]=1;

	if (img->depth == 16) {
	   udata = (unsigned short *)img->data;
	   for(i=2; i<npix; ++i) total += udata[i];

	   avg = total / (npix-2);
	   printf("Average = %-5.2f\n",avg);

	   for(i=2; i<npix; ++i) {
	      double diff = udata[i];
	      if (diff==0) fdata[i]=1;
	      else fdata[i] = avg / diff;
	      }
	   }
	else {
	   printf("Unsupported depth %d\n",img->depth);
	   exit(1);
	   }

	printf("Writing %s\n",dst_fname);
	z = fopen(dst_fname,"wb");
	fprintf(z,"%d %d\n",img->width,img->height);
	for(i=0; i<npix; ++i) fprintf(z,"%f\n",fdata[i]);
	fclose(z);
	}
