#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;
    }

    // set maskValue and markValue in the psphot recipe
    psMaskType maskValue = pmConfigMaskGet("BLANK", config); // Bits to mask
    psMaskType markValue = pmConfigMaskGet("MARK.VALUE", config); // Bits to use for marking
    psMetadataAddU8 (recipe, PS_LIST_TAIL, "MASK.PSPHOT", PS_META_REPLACE, "Bits to mask", maskValue);
    psMetadataAddU8 (recipe, PS_LIST_TAIL, "MARK.PSPHOT", PS_META_REPLACE, "Bits to use for mark", markValue);

    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;
}
