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

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

#include "ppStac.h"

bool ppStacCombine(ppStacOptions *options)
{
    PS_ASSERT_PTR_NON_NULL(options, false);

    psArray *inputs = psArrayAlloc(options->inFiles->n); // Input images
    psRegion region = psRegionSet(0, 0, 0, 0); // Region to read
    for (int i = 0; i < inputs->n; i++) {
        psImage *image = psFitsReadImage(options->inFiles->data[i], region, 0);
        if (!image) {
            psError(PS_ERR_IO, false, "Unable to read image %d\n", i);
            return false;
        }
        inputs->data[i] = image;
    }

    psImage *output = pmCombineImages(NULL, NULL, inputs, NULL, NULL, options->maskVal, NULL,
                                      options->iter, options->rej);

    if (!output) {
        psError(PS_ERR_UNKNOWN, false, "Unable to combine images.\n");
        return false;
    }

    if (!psFitsWriteImage(options->outFile, NULL, output, 0, NULL)) {
        psError(PS_ERR_UNKNOWN, false, "Unable to write output image.\n");
        return false;
    }
    psFree(output);

    return true;
}
