# include "pswarp.h"
# include <glob.h>

pmConfig *pswarpArguments (int argc, char **argv) {

    bool status;
    int N;

    if (argc == 1) {
        psError(PSWARP_ERR_ARGUMENTS, true, "No arguments supplied");
        return NULL;
    }

    // load config data from default locations
    pmConfig *config = pmConfigRead(&argc, argv, PSWARP_RECIPE);
    if (config == NULL) {
        psError(PSWARP_ERR_CONFIG, false, "Can't read site configuration");
        return NULL;
    }

    // save the following additional recipe values based on command-line options
    // these options override the PSWARP recipe values loaded from recipe files
    pmConfigRecipeOptions (config, PSWARP_RECIPE);

    pmConfigFileSetsMD(config->arguments, &argc, argv, "ASTROM",   "-astrom", "-astromlist");

    // chip selection is used to limit chips to be processed
    if ((N = psArgumentGet(argc, argv, "-chip"))) {
        psArgumentRemove(N, &argc, argv);
        psMetadataAddStr(config->arguments, PS_LIST_TAIL, "CHIP_SELECTIONS", PS_DATA_STRING,
                         "Only process these chips", argv[N]);
        psArgumentRemove(N, &argc, argv);
    }

    // Statistics file
    if ((N = psArgumentGet(argc, argv, "-stats"))) {
        psArgumentRemove(N, &argc, argv);
        psMetadataAddStr(config->arguments, PS_LIST_TAIL, "STATS", PS_DATA_STRING,
                         "Filename for statistics of output image", argv[N]);
        psArgumentRemove(N, &argc, argv);
    }

    // Number of threads
    if ((N = psArgumentGet(argc, argv, "-threads"))) {
        psArgumentRemove(N, &argc, argv);
        int nThreads = atoi(argv[N]);
        psMetadataAddS32(config->arguments, PS_LIST_TAIL, "NTHREADS", 0, "number of warp threads", nThreads);
        psArgumentRemove(N, &argc, argv);

        // create the thread pool with number of desired threads, supplying our thread launcher function
        // XXX need to determine the number of threads from the config data
        psThreadPoolInit (nThreads);
    }
    pswarpSetThreads ();

    // PSF determination?
    if ((N = psArgumentGet(argc, argv, "-psf"))) {
        psArgumentRemove(N, &argc, argv);
        psMetadataAddBool(config->arguments, PS_LIST_TAIL, "PSF", 0, "Do PSF determination?", true);
    }
    if ((N = psArgumentGet(argc, argv, "-dumpconfig"))) {
        psArgumentRemove(N, &argc, argv);
        psMetadataAddStr(config->arguments, PS_LIST_TAIL, "DUMP_CONFIG", PS_META_REPLACE,
                         "Filename for configuration dump", argv[N]);
        psArgumentRemove(N, &argc, argv);
    }


    if (!pmConfigFileSetsMD (config->arguments, &argc, argv, "INPUT", "-file", "-list")) {
        psError(PSWARP_ERR_ARGUMENTS, true, "Missing -file (input) or -list (input)");
        return NULL;
    }

    // the mask and weight entries are optional (build from gain?)
    pmConfigFileSetsMD (config->arguments, &argc, argv, "MASK",   "-mask",   "-masklist");
    pmConfigFileSetsMD (config->arguments, &argc, argv, "WEIGHT", "-weight", "-weightlist");

    if (argc != 3) {
        psError(PSWARP_ERR_ARGUMENTS, true, "Incorrect arguments supplied");
        return NULL;
    }


    psArray *array;

    // output position is fixed
    psMetadataAddStr (config->arguments, PS_LIST_TAIL, "OUTPUT", 0, "", argv[1]);

    // skycell position is fixed
    array = psArrayAlloc(1);
    array->data[0] = psStringCopy (argv[2]);
    status = psMetadataAddPtr (config->arguments, PS_LIST_TAIL, "SKYCELL", PS_DATA_ARRAY, "", array);
    psFree (array);

    psTrace("pswarp", 1, "Done with pswarpArguments...\n");
    return (config);
}

// Parse the recipe and format into the arguments
bool pswarpOptions(pmConfig *config)
{
    // Select the appropriate recipe
    psMetadata *recipe  = psMetadataLookupPtr(NULL, config->recipes, PSWARP_RECIPE);
    if (!recipe) {
        psError(PSWARP_ERR_CONFIG, true, "Can't find %s recipe!\n", PSWARP_RECIPE);
        return false;
    }

    // Get grid size
    bool status;                        // Status of MD lookup
    int nGridX = psMetadataLookupS32(&status, recipe, "GRID.NX");
    if (!status || nGridX <= 0) {
        nGridX = 128;
        psWarning("GRID.NX is not set in the recipe --- defaulting to %d", nGridX);
    }
    int nGridY = psMetadataLookupS32(&status, recipe, "GRID.NY");
    if (!status) {
        nGridY = 128;
        psWarning("GRID.NY is not set in the recipe --- defaulting to %d", nGridY);
    }

    // Get interpolation mode
    const char *name = psMetadataLookupStr (&status, recipe, "INTERPOLATION.MODE"); // Name of interp mode
    if (!name) {
        name = "BILINEAR";
        psLogMsg("pswarp", 3, "defaulting to %s interpolation", name);
    }
    psImageInterpolateMode interpolationMode = psImageInterpolateModeFromString(name); // Mode for interp.
    if (interpolationMode == PS_INTERPOLATE_NONE) {
        interpolationMode = PS_INTERPOLATE_BILINEAR;
        psLogMsg ("pswarp", 3,
                  "Unknown interpolation mode %s, defaulting to bilinear interpolation\n", name);
        name = "BILINEAR";
    }

    float poorFrac = psMetadataLookupF32(&status, recipe, "POOR.FRAC"); // Frac of bad flux for a "poor"
    if (!status) {
        poorFrac = 0.0;
        psWarning("POOR.FRAC is not set in the %s recipe --- defaulting to %f.", PSWARP_RECIPE, poorFrac);
    }

    float acceptFrac = psMetadataLookupF32(&status, recipe, "ACCEPT.FRAC"); // Min fraction of good pixels
    if (!status) {
        acceptFrac = 0.0;
        psWarning("ACCEPT.FRAC is not set in the %s recipe --- defaulting to %f.", PSWARP_RECIPE, poorFrac);
    }

    // Set recipe values in the recipe (since we've possibly altered some)
    psMetadataAddS32(recipe, PS_LIST_TAIL, "GRID.NX", PS_META_REPLACE,
                     "Iso-astrom grid spacing in x", nGridX);
    psMetadataAddS32(recipe, PS_LIST_TAIL, "GRID.NY", PS_META_REPLACE,
                     "Iso-astrom grid spacing in y", nGridY);
    psMetadataAddStr(recipe, PS_LIST_TAIL, "INTERPOLATION.MODE", PS_META_REPLACE,
                     "Interpolation mode", name);
    psMetadataAddF32(recipe, PS_LIST_TAIL, "POOR.FRAC", PS_META_REPLACE,
                     "Fraction of bad flux for a pixel to be marked as poor", poorFrac);
    psMetadataAddF32(recipe, PS_LIST_TAIL, "ACCEPT.FRAC", PS_META_REPLACE,
                     "Minimum fraction of good pixels for result to be accepted", acceptFrac);

    // Set recipe values in the arguments
    psMetadataAddS32(config->arguments, PS_LIST_TAIL, "GRID.NX", 0,
                     "Iso-astrom grid spacing in x", nGridX);
    psMetadataAddS32(config->arguments, PS_LIST_TAIL, "GRID.NY", 0,
                     "Iso-astrom grid spacing in y", nGridY);
    psMetadataAddS32(config->arguments, PS_LIST_TAIL, "INTERPOLATION.MODE", 0,
                     "Interpolation mode", interpolationMode);
    psMetadataAddF32(config->arguments, PS_LIST_TAIL, "POOR.FRAC", 0,
                     "Fraction of bad flux for a pixel to be marked as poor", poorFrac);
    psMetadataAddF32(config->arguments, PS_LIST_TAIL, "ACCEPT.FRAC", 0,
                     "Minimum fraction of good pixels for result to be accepted", acceptFrac);

    psTrace("pswarp", 1, "Done with pswarpArguments...\n");

    // Dump configuration, now that's it's settled
    psString dump_file =  psMetadataLookupStr(&status, config->arguments, "DUMP_CONFIG");
    if (dump_file) {
        const char *skyCamera = psMetadataLookupStr(NULL, config->arguments,
                                                    "SKYCELL.CAMERA");  // Name of camera for skycell
        pmConfigCamerasCull(config, skyCamera);
        pmConfigRecipesCull(config, "PSWARP,PPSTATS,PSPHOT,MASKS");

        pmFPAfile *input = psMetadataLookupPtr(NULL, config->files, "PSWARP.INPUT"); // Input file
        pmConfigDump(config, input->fpa, dump_file);
    }

    return (config);
}
