#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 bad flat corrections
    options->flatMask = pmConfigMaskGet("FLAT", config);
    psAssert (options->flatMask, "flat mask not set");

    // mask for bad dark corrections
    options->darkMask = pmConfigMaskGet("DARK", config);
    psAssert (options->darkMask, "dark 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->lowMask = pmConfigMaskGet("LOW", config);
    if (!options->lowMask) {
        // look up old name for backward compatability
        options->lowMask = pmConfigMaskGet("BAD", config);
    }
    psAssert (options->lowMask, "low mask not set");

    // mask for suspect regions due to burntool
    options->burntoolMask = pmConfigMaskGet("BURNTOOL",config);
    psAssert (options->burntoolMask, "burntool 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;
}
