#include <stdio.h>
#include "pslib.h"
#include "stac.h"

psArray *stacErrorImages(psArray *inputs, // Array of input images
			 stacConfig *config // Configuration details
    )
{
    float invGain = 1.0/config->gain;	// Inverse square root of gain
    float rn = config->readnoise/config->gain; // Read noise in ADU
    psArray *errors = psArrayAlloc(inputs->n);

    psTrace("stac.errors", 1, "Calculating error images....\n");

    // Iterate over the input images
    for (int i = 0; i < inputs->n; i++) {
	psTrace("stac.errors",5,"Working on image #%d\n",i);

	psImage *image = inputs->data[i]; // Pull out the image of interest
	int numRows = image->numRows;	// Number of rows
	int numCols = image->numCols;	// Number of columns	
	psImage *error = psImageAlloc(numCols, numRows, PS_TYPE_F32); // The error image

	// Iterate over the pixels
	for (int r = 0; r < numRows; r++) {
	    for (int c = 0; c < numCols; c++) {
		// We actually calculate the variance
		error->data.F32[r][c] = image->data.F32[r][c]*invGain + rn*rn;
	    }
	}

	// Put image onto the array
	errors->data[i] = error;
 
#ifdef TESTING
	// Write error image out to check
	char errfile[MAXCHAR];		// Filename of error image
	sprintf(errfile,"%s.err",config->inputs->data[i]);
	psImageWriteSection(error,0,0,0,NULL,0,errfile);
#endif

    }

    return errors;
}
