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

# include "ppstamp.h"

bool ppstampMegacamWorkaround = false;

// Set up the ppstamp output Image file
bool setupOutput(pmConfig *config, pmFPAfile *input)
{
    pmFPAfile *output = pmFPAfileDefineSkycell(config, NULL, "PPSTAMP.OUTPUT");
    output->save = true;
    return true;
}

// This function seems mis-named. What are we doing with regards to the Camera?
// Well we are building the output image based on the camera. Is there
// something else that I'm missing?

bool ppstampParseCamera(pmConfig *config)
{
    bool status = false;

    // the input image defines the camera, and all recipes and options the follow
    pmFPAfile *input = pmFPAfileDefineFromArgs (&status, config, "PPSTAMP.INPUT", "INPUT");
    if (!status || !input) {
        psError(PS_ERR_IO, false, "Failed to build FPA from PPSTAMP.INPUT");
        return false;
    }
    if (input->type != PM_FPA_FILE_IMAGE) {
        psError(PS_ERR_IO, true, "PPSTAMP.INPUT is not of type IMAGE");
        return false;
    }

    // XXX: create a filerule for PPSTAMP.ASTROM
    pmFPAfile *astrom = pmFPAfileDefineFromArgs(&status, config, "PSWARP.ASTROM", "ASTROM");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to find astrom definitiion");
        return NULL;
    }
    if (astrom) {
        psLogMsg ("ppstamp", 3, "using supplied astrometry\n");
    } else {
        psLogMsg ("ppstamp", 3, "using header astrometry\n");
    }

#ifdef notyet
    // add recipe options supplied on command line
    psMetadata *recipe  = psMetadataLookupPtr (&status, config->recipes, RECIPE_NAME);
#endif

    // Set up the output target
    if (!setupOutput(config, input)) {
        psError(PS_ERR_UNKNOWN, false, "Unable to setup output.");
        return false;
    }

    pmFPAfile *chipImage = pmFPAfileDefineChipMosaic(config, input->fpa, "PPSTAMP.CHIP");
    if (!chipImage) {
        psError(PS_ERR_IO, false, _("Unable to generate new file from PPSTAMP.CHIP"));
        return NULL;
    }
    if (chipImage->type != PM_FPA_FILE_IMAGE) {
        psError(PS_ERR_IO, true, "PPSTAMP.CHIP is not of type IMAGE");
        return NULL;
    }

    // XXX: TODO: only do the workaround if the file level is chip, skycells should be fine
    if (!strcmp(config->cameraName, "MEGACAM")) {
        // workaround bug 986 and related
        ppstampMegacamWorkaround = true;
    }
 
    return true;
}
