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

# include "ppImage.h"

// In this function, we perform the psphot analysis routine for the chip-mosaicked images
bool ppImagePhotom (pmConfig *config, pmFPAview *view) {

    bool status;
    pmCell *cell;
    pmReadout *readout;

    psphotModelGroupInit ();

    // find or define a pmFPAfile PSPHOT.INPUT
    pmFPAfile *input = psMetadataLookupPtr (&status, config->files, "PSPHOT.INPUT");
    if (!status) {
	psError(PSPHOT_ERR_CONFIG, false, "PSPHOT.INPUT I/O file is not defined");
	return false;
    }

    // we make a new copy of the output chip to keep psphot from modifying the output image
    pmChip *oldChip = pmFPAviewThisChip (view, input->src);
    pmChip *newChip = pmFPAviewThisChip (view, input->fpa);
    pmChipCopy (newChip, oldChip);

    // iterate over the cells and readout for this chip
    while ((cell = pmFPAviewNextCell (view, input->fpa, 1)) != NULL) {
	psLogMsg ("ppImagePhotom", 4, "Cell %d: %x %x\n", view->cell, cell->file_exists, cell->process);
	if (! cell->process || ! cell->file_exists) { continue; }

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

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

    // the PSPHOT.INPUT file is a temporary file used to carry PPIMAGE.OUTPUT.CHIP to psphotReadout
    // XXX not sure that this is needed...
    pmFPAfileActivate (config->files, false, "PSPHOT.INPUT");

    return true;
}

// XXX do we need to deactivate all files and activate the psphot ones explicitly?
