#include "../ninox.h"

main(int argc, char *argv[])
	{
	FILE *z;
	struct Image *img;
	double dval;
	int npix,i,ref_width,ref_height;
	char *dst_fname,line[81];
	unsigned short *udata;
	double *fdata;

	if (argc != 4) {
	   printf("Usage: fits_gaincomp ref-image srcimage.fit dstimage.fit\n");
	   exit(1);
	   }

	z = fopen(argv[1],"rb");
	if (!z) { printf("Cannot open reference image %s\n",argv[1]); exit(1);}
	fgets(line,80,z);
	if (sscanf(line,"%d %d",&ref_width,&ref_height) != 2) {
	   printf("cannot parse reference file %s\n",argv[1]);
	   exit(1);
	   }
	printf("Reference: (%d x %d)\n",ref_width,ref_height);
	npix = ref_width * ref_height;
	fdata = (double *)Malloc(npix * sizeof(double));
	for(i=0; i<npix; ++i) {
	   if (! fgets(line,80,z)) {
		printf("Line %d: Unexpected eof reading gain data from %s\n",i,argv[1]);
		exit(1);
		}
	   if (sscanf(line,"%lf",fdata+i) != 1) {
		printf("Line %d: Error parsing compensation values from %s\n",i,argv[1]);
		exit(1);
		}
	   }

	printf("Loaded %d compensation values from %s\n",npix,argv[1]);
	fclose(z);
		
	dst_fname = strdup(argv[3]);

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

	if (img->width != ref_width || img->height != ref_height) {
	   printf("Error: image dimensions (%dx%d) do not match reference image dimensions (%dx%d)\n",
		img->width,img->height,ref_width,ref_height);
	   exit(1);
	   }

	if (img->depth == 16) {
	   udata = (unsigned short *)img->data;
	   for(i=0; i<npix; ++i) {
		dval = udata[i] * fdata[i];
		if (dval<0) dval=0;
		if (dval > 65535) dval=65535;
		udata[i] = dval;
		}
	   }
	else {
	   printf("Depth %d unsupported\n",img->depth);
	   exit(1);
	   }

	printf("Writing %s\n",dst_fname);
	if (! WriteImage(img)) {
		printf("Failed to write image %s\n",dst_fname);
		exit(1);
		}

	exit(0);
	}
