# include "ppSim.h"

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

    bool status;
    pmCell *cell;
    pmReadout *readout;

    psMetadata *recipe = psMetadataLookupMetadata(&status, config->recipes, PPSIM_RECIPE); // Recipe

    bool doPhotom = psMetadataLookupBool(&status, recipe, "PHOTOM"); // Density of fakes
    if (!doPhotom) return true;
    
    psphotInit ();

    psImageMaskType blankMask = 1;		// XXX not sure what this should be set to...
    ppSimMosaicChip(config, blankMask, view, "PPSIM.FORCE.CHIP", "PPSIM.INPUT");
    ppSimMosaicChip(config, blankMask, view, "PPSIM.FAKE.CHIP", "PPSIM.OUTPUT");

    // use PPSIM.FAKE.CHIP as the base since it is guaranteed to exist (derived from PPSIM.OUTPUT)
    pmFPAfile *input = psMetadataLookupPtr (&status, config->files, "PPSIM.FAKE.CHIP");
    if (!status) {
        psError(PSPHOT_ERR_CONFIG, false, "PPSIM.FAKE.CHIP I/O file is not defined");
        return false;
    }

    // XXX If we want to be able to write out both the positive and residual images, we will
    // need to define an additional pmFPAfile container, and then make a copy as is done for
    // PPIMAGE.CHIP -> PSPHOT.INPUT in ppImage.  At the moment, PPSIM.CHIP will write out the
    // mosaicked image with the sources subtracted.

    // XXX if input -> PSPHOT.INPUT, which is tied to PPSIM.CHIP with pmFPAfileDefineFromFile,
    // then the following code creates the chip copy:
    // 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 ("ppSimPhotom", 5, "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
            if (!ppSimPhotomReadoutFake (config, view)) {
                psError(psErrorCodeLast(), false, "failure in psphotReadout for chip %d, cell %d, readout %d\n", view->chip, view->cell, view->readout);
                return false;
            }
            if (!ppSimPhotomReadoutForce (config, view)) {
                psError(psErrorCodeLast(), false, "failure in psphotReadout for chip %d, cell %d, readout %d\n", view->chip, view->cell, view->readout);
                return false;
            }
	    // ppSimDetectionLimits (config, view);
        }
    }

    return true;
}
