/** @file ppSubDefineOutput.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 "ppSub.h"

bool ppSubDefineOutput(pmConfig *config, const pmFPAview *view)
{
    psAssert(config, "Require configuration");
    psAssert(view, "Require view");

    // generate an output readout
    pmCell *outCell = pmFPAfileThisCell(config->files, view, "PPSUB.OUTPUT"); // Output cell
    pmReadout *outRO = pmReadoutAlloc(outCell); // Output readout: subtraction
    pmFPA *outFPA = outCell->parent->parent; // Output FPA
    pmHDU *outHDU = outFPA->hdu; // Output HDU
    if (!outHDU->header) {
        outHDU->header = psMetadataAlloc();
    }

    // convolved input images
    pmReadout *inConv = pmFPAfileThisReadout(config->files, view, "PPSUB.INPUT.CONV"); // Input readout
    pmReadout *refConv = pmFPAfileThisReadout(config->files, view, "PPSUB.REF.CONV"); // Reference readout

    // Add kernel descrption to header.
    // We don't know which readout has the kernels because it depends on which PSF is larger
    bool mdok;                          // Status of MD lookup
    psMetadata *analysis = inConv->analysis; // Analysis metadata with kernel information
    pmSubtractionKernels *kernels = psMetadataLookupPtr(&mdok, analysis,
                                                        PM_SUBTRACTION_ANALYSIS_KERNEL); // Subtraction kernel
    if (!kernels) {
        analysis = refConv->analysis;
        kernels = psMetadataLookupPtr(&mdok, analysis, PM_SUBTRACTION_ANALYSIS_KERNEL);
    }
    if (!kernels) {
        psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find SUBTRACTION.KERNEL");
        psFree(inConv);
        psFree(refConv);
        psFree(outRO);
        return false;
    }
    psMetadataAddStr(outHDU->header, PS_LIST_TAIL, "PPSUB.KERNEL", 0, "Subtraction kernel",
                     kernels->description);

    outRO->analysis = psMetadataCopy(outRO->analysis, analysis);

#ifdef TESTING
    {
        psImage *kernelImage = psMetadataLookupPtr(&mdok, analysis,
                                                   "SUBTRACTION.KERNEL.IMAGE"); // Image of kernel
        psFits *fits = psFitsOpen("kernel.fits", "w");
        psFitsWriteImage(fits, NULL, kernelImage, 0, NULL);
        psFitsClose(fits);
    }
#endif

    return true;
}
