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

#include "ppImage.h"

bool ppImageSetMaskBits (pmConfig *config, ppImageOptions *options) {

    if (!pmConfigMaskSetBits(&options->maskValue, &options->markValue, config)) {
        psError (PS_ERR_UNKNOWN, true, "Unable to define the mask bit values");
        return false;
    }

    // at this point we know we have valid values for required entries SAT, BAD, FLAT, BLANK:

    // mask for non-linear flat corrections
    options->flatMask = pmConfigMaskGet("FLAT", config);
    psAssert (options->flatMask, "flat mask not set");

    // mask for non-existent data  (default to DETECTOR if not defined)
    options->blankMask = pmConfigMaskGet("BLANK", config);
    psAssert (options->blankMask, "blank mask not set");

    // mask for saturated data  (default to RANGE if not defined)
    options->satMask = pmConfigMaskGet("SAT", config);
    psAssert (options->satMask, "sat mask not set");

    // mask for below-range data  (default to RANGE if not defined)
    options->badMask = pmConfigMaskGet("BAD", config);
    psAssert (options->badMask, "bad mask not set");

    // save MASK and MARK on the PSPHOT recipe
    psMetadata *recipe = psMetadataLookupPtr (NULL, config->recipes, PSPHOT_RECIPE);
    if (!recipe) {
        psError(PSPHOT_ERR_CONFIG, false, "missing recipe %s", PSPHOT_RECIPE);
        return false;
    }

    // set maskValue and markValue in the psphot recipe
    psMetadataAddImageMask(recipe, PS_LIST_TAIL, "MASK.PSPHOT", PS_META_REPLACE, "user-defined mask",
                           options->maskValue);
    psMetadataAddImageMask(recipe, PS_LIST_TAIL, "MARK.PSPHOT", PS_META_REPLACE, "user-defined mask",
                           options->markValue);

    return true;
}
