/** @file ppSubMakePSF.c
 *
 *  @brief
 *
 *  @ingroup ppSub
 *
 *  @author IfA
 *  @version $Revision: 1.3 $ $Name: not supported by cvs2svn $
 *  @date $Date: 2009-02-18 00:31:20 $
 *  Copyright 2009 Institute for Astronomy, University of Hawaii
 */

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

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

#include "ppSub.h"

bool ppSubMakePSF(ppSubData *data)
{
    psAssert(data, "Require processing data");
    pmConfig *config = data->config;    // Configuration
    psAssert(config, "Require configuration");

    if (!data->photometry) {
        return true;
    }

    psTimerStart("PPSUB_PHOT");

    psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PPSUB_RECIPE); // Recipe for ppSub
    psAssert(recipe, "We checked this earlier, so it should be here.");

    if (!psMetadataLookupBool(NULL, recipe, "PHOTOMETRY")) {
        return true;
    }

    bool reverse = psMetadataLookupBool(NULL, config->arguments, "REVERSE"); // Reverse sense of subtraction?

    bool mdok = false;                  // Status of MD lookup
    pmReadout *minuend = NULL;          // Image that will be positive following subtraction
    pmFPAfile *minuendFile = NULL;      // File for minuend image
    pmFPAview *view = ppSubViewReadout(); // View to readout
    if (reverse) {
        minuend = pmFPAfileThisReadout(config->files, view, "PPSUB.REF.CONV");
        minuendFile = psMetadataLookupPtr(&mdok, config->files, "PPSUB.REF.CONV");
    } else {
        minuend = pmFPAfileThisReadout(config->files, view, "PPSUB.INPUT.CONV");
        minuendFile = psMetadataLookupPtr(&mdok, config->files, "PPSUB.INPUT.CONV");
    }

    pmFPAfile *photFile = psMetadataLookupPtr(&mdok, config->files, "PSPHOT.INPUT"); // Photometry file
    if (!pmFPACopy(photFile->fpa, minuendFile->fpa)) {
        psError(PS_ERR_UNKNOWN, false, "Unable to copy FPA for photometry");
        psFree(view);
        return false;
    }
    pmReadout *photRO = pmFPAviewThisReadout(view, photFile->fpa); // Readout to photometer
    if (psMetadataLookup(photRO->analysis, "PSPHOT.SOURCES")) {
        psMetadataRemoveKey(photRO->analysis, "PSPHOT.SOURCES");
    }

    // Extract the loaded sources from the associated readout, and generate PSF
    // Here, we assume the image is background-subtracted
    psArray *sources = psMetadataLookupPtr(&mdok, minuend->analysis, "PSPHOT.SOURCES");
    if (!psphotReadoutFindPSF(config, view, sources)) {
        // This is likely a data quality issue
        // XXX Split into multiple cases using error codes?
        psErrorStackPrint(stderr, "Unable to determine PSF");
        psWarning("Unable to determine PSF --- suspect bad data quality.");
        ppSubDataQuality(data, PSPHOT_ERR_PSF, PPSUB_FILES_PHOT_SUB | PPSUB_FILES_PHOT_INV);
        psFree(view);
        return true;
    }

    // Get rid of the generated header; it will be regenerated by the real photometry run
    psMetadataRemoveKey(photRO->analysis, "PSPHOT.HEADER");

    if (!data->quality) {
        data->psf = psMemIncrRefCounter(psMetadataLookupPtr(NULL, photRO->parent->parent->analysis,
                                                            "PSPHOT.PSF"));
    }

    psFree(view);

    return true;
}
