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

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

#include "ppSub.h"

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

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

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

    // Generate binned JPEGs
    psImageMaskType maskBad = pmConfigMaskGet("BLANK", config); // Bits to mask for bad pixels

    int bin1 = psMetadataLookupS32(NULL, recipe, "BIN1"); // First binning level
    int bin2 = psMetadataLookupS32(NULL, recipe, "BIN2"); // Second binning level

    // Target cells
    pmCell *cell1 = pmFPAfileThisCell(config->files, view, "PPSUB.OUTPUT.JPEG1"); // Rebinned cell once
    pmCell *cell2 = pmFPAfileThisCell(config->files, view, "PPSUB.OUTPUT.JPEG2"); // Rebinned cell twice
    psFree(view);

    pmReadout *ro1 = pmReadoutAlloc(cell1), *ro2 = pmReadoutAlloc(cell2); // Binned readouts
    if (!pmReadoutRebin(ro1, outRO, maskBad, bin1, bin1)) {
        psError(PS_ERR_UNKNOWN, false, "Unable to bin output (1st binning)");
        psFree(ro1);
        psFree(ro2);
        return false;
    }
    if (!pmReadoutRebin(ro2, ro1, 0, bin2, bin2)) {
        psError(PS_ERR_UNKNOWN, false, "Unable to bin output (2nd binning)");
        psFree(ro1);
        psFree(ro2);
        return false;
    }
    psFree(ro1);
    psFree(ro2);

    return true;
}
