#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

# include "psphot.h"

// XXX where do we load optional mask and weight input images?
bool psphotImageLoop (pmConfig *config) {

    bool status;
    pmChip *chip;
    pmCell *cell;
    pmReadout *readout;

    pmFPAfile *input = psMetadataLookupPtr (&status, config->files, "PSPHOT.INPUT");
    if (!status) {
	psError(PS_ERR_IO, false, "Can't find input data!");
	return false;
    }

    pmFPAview *view = pmFPAviewAlloc (0);
    
    // files associated with the science image
    if (!pmFPAfileIOChecks (config, view, PM_FPA_BEFORE)) {
	psFree(view);
	return false;
    }
    while ((chip = pmFPAviewNextChip (view, input->fpa, 1)) != NULL) {
        psLogMsg ("psphot", 4, "Chip %d: %x %x\n", view->chip, chip->file_exists, chip->process);
        if (! chip->process || ! chip->file_exists) { continue; }
	pmFPAfileIOChecks (config, view, PM_FPA_BEFORE);

	while ((cell = pmFPAviewNextCell (view, input->fpa, 1)) != NULL) {
            psLogMsg ("psphot", 4, "Cell %d: %x %x\n", view->cell, cell->file_exists, cell->process);
            if (! cell->process || ! cell->file_exists) { continue; }
	    pmFPAfileIOChecks (config, view, PM_FPA_BEFORE);

	    // process each of the readouts
	    while ((readout = pmFPAviewNextReadout (view, input->fpa, 1)) != NULL) {
		pmFPAfileIOChecks (config, view, PM_FPA_BEFORE);
		if (! readout->data_exists) { continue; }

		// run the actual photometry analysis
		psphotReadout (config, view);

		pmFPAfileIOChecks (config, view, PM_FPA_AFTER);
	    }
	    pmFPAfileIOChecks (config, view, PM_FPA_AFTER);
	}
	pmFPAfileIOChecks (config, view, PM_FPA_AFTER);
    }
    pmFPAfileIOChecks (config, view, PM_FPA_AFTER);

    psFree (view);
    return true;
}

// I/O files related to psphot:
// PSPHOT.INPUT   : input image file(s)
// PSPHOT.RESID   : residual image
// PSPHOT.OUTPUT  : output object tables (object)

// PSPHOT.BACKSUB : background subtracted image
// PSPHOT.BACKGND : background model (full-scale image?)
// PSPHOT.BACKMDL : background model (binned image?)
// PSPHOT.PSF     : sample PSF images

