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

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

#include "ppSub.h"

bool ppSubReadoutInverse(pmConfig *config)
{
    psAssert(config, "Require configuration");

    pmFPAview *view = ppSubViewReadout(); // View to readout
    pmReadout *outRO = pmFPAfileThisReadout(config->files, view, "PPSUB.OUTPUT");
    pmReadout *invRO = pmFPAfileThisReadout(config->files, view, "PPSUB.INVERSE");

    invRO->image = (psImage*)psBinaryOp(invRO->image, outRO->image, "*", psScalarAlloc(-1.0, PS_TYPE_F32));
    invRO->mask = psMemIncrRefCounter(outRO->mask);
    invRO->variance = psMemIncrRefCounter(outRO->variance);
    invRO->covariance = psMemIncrRefCounter(outRO->covariance);

    invRO->data_exists = invRO->parent->data_exists = invRO->parent->parent->data_exists = true;

    pmChip *outChip = outRO->parent->parent;       // Output chip
    pmFPA *outFPA = outChip->parent;               // Output FPA
    pmFPA *invFPA = invRO->parent->parent->parent; // Inverse FPA

    pmConceptsCopyFPA(invFPA, outFPA, true, true);

    pmChip *invChip = invRO->parent->parent; // Inverse chip
    pmHDU *invHDU = invFPA->hdu;          // Inverse HDU
    if (!pmAstromWriteWCS(invHDU->header, outFPA, outChip, WCS_TOLERANCE)) {
        psError(PS_ERR_UNKNOWN, false, "Unable to write WCS astrometry to PPSUB.INVERSE.");
        return false;
    }
    // Read from newly written astrometry so that it exists in the "inverse" FPA (for sources)
    if (!pmAstromReadWCS(invFPA, invChip, invHDU->header, 1.0)) {
        psError(PS_ERR_UNKNOWN, false, "Unable to read WCS astrometry.");
        return false;
    }

    return true;
}
