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

# include "dvoApplyCorr.h"

dvoApplyCorrOptions *dvoApplyCorrParseCamera (pmConfig *config) {

    bool status = false;

    // the input image defines the camera, and all recipes and options the follow
    pmFPAfile *input = pmFPAfileDefineFromArgs (NULL, config, "DVOFLAT.INPUT", "INPUT");
    if (!input) {
        psError(PS_ERR_IO, false, "Failed to build FPA from DVOFLAT.INPUT");
        return NULL;
    }

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

    // parse the options from the metadata format to the dvoApplyCorrOptions structure
    dvoApplyCorrOptions *options = dvoApplyCorrOptionsParse (config);

    // the following files are output targets
    pmFPAfile *output = pmFPAfileDefineOutput(config, input->fpa, "DVOFLAT.OUTPUT");
    if (!output) {
        psError(PS_ERR_IO, false, _("Unable to generate output file from DVOFLAT.OUTPUT"));
        psFree(options);
        return NULL;
    }

    // find the flat-field correction image (from command-line, config file, or detrend db)
    status = false;
    pmFPAfileDefineFromArgs  (&status, config, "DVOFLAT.CORR", "CORR");
    psErrorClear();
    pmFPAfileDefineFromConf  (&status, config, "DVOFLAT.CORR");
    psErrorClear();
    pmFPAfileDefineFromDetDB (&status, config, "DVOFLAT.CORR", input->fpa, PM_DETREND_TYPE_FLAT_CORRECTION);
    if (!status) {
	psError (PS_ERR_IO, false, "can't find a flat-field correction image source");
	return NULL;
    }
    
    // Chip selection: turn on only the chips specified (pass status to suppress missing-key log msg)
    status = false;
    char *chipLine = psMetadataLookupStr(&status, config->arguments, "CHIP_SELECTIONS");
    psArray *chips = psStringSplitArray (chipLine, ",", false);
    if (chips->n > 0) {
        pmFPASelectChip (output->fpa, -1, true); // deselect all chips
        for (int i = 0; i < chips->n; i++) {
            int chipNum = atoi(chips->data[i]);
            if (! pmFPASelectChip(output->fpa, chipNum, false)) {
                psError(PS_ERR_IO, false, "Chip number %d doesn't exist in camera.\n", chipNum);
                return false;
            }
        }
    }
    psFree (chips);
    return (options);
}
