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

#include <stdio.h>
#include <pslib.h>
#include <psmodules.h>
#include <psphot.h>

#include "ppStack.h"

bool ppStackPhotometry(pmConfig *config, const pmReadout *readout, const pmFPAview *view)
{
    pmFPAfile *photFile = psMetadataLookupPtr(NULL, config->files, "PSPHOT.INPUT");
    pmFPACopy(photFile->fpa, readout->parent->parent->parent);

    {
        // Need to ensure aperture residual is not calculated
        psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PSPHOT_RECIPE); // Recipe
        psMetadataItem *item = psMetadataLookup(recipe, "MEASURE.APTREND"); // Item determining aptrend
        if (!item) {
            psWarning("Unable to find MEASURE.APTREND in psphot recipe");
            psErrorClear();
        } else {
            item->data.B = false;
        }
    }

    if (!psphotReadout(config, view)) {
        // Clear the error, so that the output files are written.
        psWarning("Unable to perform photometry on stacked image.");
        psErrorStackPrint(stderr, "Error stack from photometry:");
        psErrorClear();
    }

    pmFPAfileActivate(config->files, false, "PSPHOT.INPUT");

    return true;
}
