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

#include <stdio.h>
#include <string.h>
#include <pslib.h>
#include <psmodules.h>

#include "ppSub.h"

// Print usage information and die
static void usage(const char *program,  // Name of the program
                  psMetadata *arguments, // Command-line arguments
                  pmConfig *config      // Configuration
    )
{
    fprintf(stderr, "\nPan-STARRS PSF-matched image subtraction\n\n");
    fprintf(stderr, "Usage: %s INPUT.fits REFERENCE.fits OUTPUT_ROOT \n"
            "\t[-psf REFERENCE.psf.fits|-psflist REFERENCE.list]\n",
            program);
    fprintf(stderr, "\n");
    psArgumentHelp(arguments);
    psFree(arguments);
    psFree(config);
    pmConfigDone();
    psLibFinalize();
    exit(PS_EXIT_CONFIG_ERROR);
}

// Get a float-point value from the command-line or recipe, and add it to the arguments
#define VALUE_ARG_RECIPE_FLOAT(ARGNAME, RECIPENAME, TYPE) { \
    ps##TYPE value = psMetadataLookup##TYPE(NULL, arguments, ARGNAME); \
    if (isnan(value)) { \
        bool mdok; \
        value = psMetadataLookup##TYPE(&mdok, recipe, RECIPENAME); \
        if (!mdok) { \
            psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Unable to find %s in recipe %s", \
                RECIPENAME, PPSUB_RECIPE); \
            goto ERROR; \
        } \
    } \
    psMetadataAdd##TYPE(config->arguments, PS_LIST_TAIL, RECIPENAME, 0, NULL, value); \
}

// Get an integer value from the command-line or recipe, and add it to the arguments
#define VALUE_ARG_RECIPE_INT(ARGNAME, RECIPENAME, TYPE, UNSET) { \
    ps##TYPE value = psMetadataLookup##TYPE(NULL, arguments, ARGNAME); \
    if (value == UNSET) { \
        bool mdok; \
        value = psMetadataLookup##TYPE(&mdok, recipe, RECIPENAME); \
        if (!mdok) { \
            psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Unable to find %s in recipe %s", \
                RECIPENAME, PPSUB_RECIPE); \
            goto ERROR; \
        } \
    } \
    psMetadataAdd##TYPE(config->arguments, PS_LIST_TAIL, RECIPENAME, 0, NULL, value); \
}

// Get a mask value from the command-line or recipe, and add it to the arguments
#define VALUE_ARG_RECIPE_MASK(ARGNAME, RECIPENAME) { \
    bool mdok; \
    const char *name = psMetadataLookupStr(&mdok, arguments, ARGNAME); \
    if (!mdok || !name || strlen(name) == 0) { \
        name = psMetadataLookupStr(NULL, recipe, RECIPENAME); \
        if (!name) { \
            psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Unable to find %s in recipe %s", \
                RECIPENAME, PPSUB_RECIPE); \
            goto ERROR; \
        } \
    } \
    psMaskType value = pmConfigMask(name, config); \
    psMetadataAddU8(config->arguments, PS_LIST_TAIL, RECIPENAME, 0, NULL, value); \
}

// Get a string value from the command-line and add it to the target
static bool valueArgStr(pmConfig *config,      // Configuration
                        psMetadata *arguments, // Command-line arguments
                        const char *argName, // Argument name in the command-line arguments
                        const char *mdName, // Name for value in the metadata
                        psMetadata *target // Target metadata to which to add value
                        )
{
    psString value = psMetadataLookupStr(NULL, arguments, argName); // Value of interest
    if (value && strlen(value) > 0) {
        return psMetadataAddStr(target, PS_LIST_TAIL, mdName, 0, NULL, value);
    }
    return false;
}

// Get a vector from the command-line or recipe, and add it to the target
static bool vectorArgRecipe(pmConfig *config,   // Configuration
                            psMetadata *arguments, // Command-line arguments
                            const char *argName, // Argument name in the command-line arguments
                            const psMetadata *recipe, // Recipe
                            const char *recipeName, // Name for value in the recipe
                            psMetadata *target, // Target to which to add value
                            psElemType type // Type for vector
    )
{
    psVector *vector;                   // Vector
    psString string = psMetadataLookupStr(NULL, arguments, argName); // String from arguments
    if (string) {
        psArray *array = psStringSplitArray(string, ", ", false); // Array of strings
        vector = psVectorAlloc(array->n, PS_TYPE_F32);
        for (int i = 0; i < array->n; i++) {
            const char *subString = array->data[i]; // String with a value
            char *end;                  // Ptr to end of string parsed

            switch (type) {
              case PS_TYPE_F32:
                vector->data.F32[i] = strtof(subString, &end);
                break;
              case PS_TYPE_S32: {
                  long value = strtol(subString, &end, 10);
                  if (value > PS_MAX_S32 || value < PS_MIN_S32) {
                      psError(PS_ERR_BAD_PARAMETER_VALUE, true,
                              "%s list includes value beyond S32 representation: %s",
                              argName, string);
                      psFree(vector);
                      return false;
                  }
                  vector->data.S32[i] = value;
                  break;
              }
              default:
                psAbort("Unsupported type: %x\n", type);
            }
            if (end == subString) {
                psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Unable to decipher %s list: %s",
                        argName, string);
                psFree(vector);
                return false;
            }
        }
        psFree(array);
    } else {
        vector = psMetadataLookupPtr(NULL, recipe, recipeName);
        if (!psMemCheckVector(vector) || vector->type.type != type) {
            psError(PS_ERR_BAD_PARAMETER_TYPE, false, "%s in recipe %s is not a vector of type F32.",
                    recipeName, PPSUB_RECIPE);
            return false;
        }
        psMemIncrRefCounter(vector);
    }

    psMetadataAddVector(target, PS_LIST_TAIL, recipeName, 0, NULL, vector);
    psFree(vector);                     // Drop reference

    return true;
}

// Add a single filename to the arguments as an array, so that it can be used with pmFPAfileBindFromArgs, etc
static void fileList(const char *file, // The symbolic name for the file
                     const char *name, // The name of the file
                     const char *comment, // Description of the file
                     pmConfig *config // Configuration
    )
{
    psArray *files = psArrayAlloc(1); // Array with file names
    files->data[0] = psStringCopy(name);
    psMetadataAddArray(config->arguments, PS_LIST_TAIL, file, 0, comment, files);
    psFree(files);
    return;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool ppSubArguments(int argc, char *argv[], pmConfig *config)
{
    assert(config);

    psMetadataAddBool(config->arguments, PS_LIST_TAIL, "PHOTOMETRY", 0, "Do photometry?",
                      (psArgumentGet(argc, argv, "-psf") || psArgumentGet(argc, argv, "-psflist")) ?
                      true : false);
    pmConfigFileSetsMD(config->arguments, &argc, argv, "PSPHOT.PSF", "-psf", "-psflist");

    psMetadata *arguments = psMetadataAlloc(); // Command-line arguments
    psMetadataAddStr(arguments, PS_LIST_TAIL, "-inmask", 0, "Input mask image", NULL);
    psMetadataAddStr(arguments, PS_LIST_TAIL, "-inweight", 0, "Input weight image", NULL);
    psMetadataAddStr(arguments, PS_LIST_TAIL, "-refmask", 0, "Referencemask image", NULL);
    psMetadataAddStr(arguments, PS_LIST_TAIL, "-refweight", 0, "Referenceweight image", NULL);
    psMetadataAddStr(arguments, PS_LIST_TAIL, "-stats", 0, "Statistics file", NULL);

    psMetadataAddS32(arguments, PS_LIST_TAIL, "-size", 0, "Kernel half-size (pixels)", 0);
    psMetadataAddS32(arguments, PS_LIST_TAIL, "-order", 0, "Spatial polynomial order", 0);
    psMetadataAddStr(arguments, PS_LIST_TAIL, "-type", 0, "Kernel type (POIS or ISIS)", NULL);
    psMetadataAddStr(arguments, PS_LIST_TAIL, "-isis-widths", 0, "ISIS Gaussian widths (comma-separated)", NULL);
    psMetadataAddStr(arguments, PS_LIST_TAIL, "-isis-orders", 0, "ISIS polynomial orders (comma-separated)", NULL);
    psMetadataAddF32(arguments, PS_LIST_TAIL, "-spacing", 0, "Typical stamp spacing (pixels)", NAN);
    psMetadataAddS32(arguments, PS_LIST_TAIL, "-footprint", 0, "Stamp footprint half-size (pixels)", 0);
    psMetadataAddF32(arguments, PS_LIST_TAIL, "-threshold", 0, "Minimum threshold for stamps (ADU)", NAN);
    psMetadataAddS32(arguments, PS_LIST_TAIL, "-iter", 0, "Number of rejection iterations", 0);
    psMetadataAddF32(arguments, PS_LIST_TAIL, "-rej", 0, "Rejection thresold (sigma)", NAN);
    psMetadataAddU8(arguments,  PS_LIST_TAIL, "-mask-bad", 0, "Mask value for bad pixels", 0);
    psMetadataAddU8(arguments,  PS_LIST_TAIL, "-mask-blank", 0, "Mask value for blank region", 0);
    psMetadataAddBool(arguments,  PS_LIST_TAIL, "-reverse", 0, "Reverse sense of subtraction?", false);

    if (argc == 1 || !psArgumentParse(arguments, &argc, argv) || argc != 4) {
        usage(argv[0], arguments, config);
    }

    fileList("INPUT", argv[1], "Name of the input image",     config);
    fileList("REF",   argv[2], "Name of the reference image", config);
    psMetadataAddStr(config->arguments, PS_LIST_TAIL, "OUTPUT", 0, "Name of the output image", argv[3]);

    const char *inMask = psMetadataLookupStr(NULL, arguments, "-inmask"); // Name of input mask
    if (inMask && strlen(inMask) > 0) {
        fileList("INPUT.MASK", inMask, "Name of the input mask image", config);
    }
    const char *inWeight = psMetadataLookupStr(NULL, arguments, "-inweight"); // Name of input weight
    if (inWeight && strlen(inWeight) > 0) {
        fileList("INPUT.WEIGHT", inWeight, "Name of the input weight image", config);
    }

    const char *refMask = psMetadataLookupStr(NULL, arguments, "-refmask"); // Name of reference mask
    if (refMask && strlen(refMask) > 0) {
        fileList("REF.MASK", refMask, "Name of the reference mask image", config);
    }
    const char *refWeight = psMetadataLookupStr(NULL, arguments, "-refweight"); // Name of reference weight
    if (refWeight && strlen(refWeight) > 0) {
        fileList("REF.WEIGHT", refWeight, "Name of the reference weight image", config);
    }

    valueArgStr(config, arguments, "-stats",      "STATS",         config->arguments);

    psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PPSUB_RECIPE); // Recipe for ppSim
    if (!recipe) {
        psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to find recipe %s", PPSUB_RECIPE);
        goto ERROR;
    }

    VALUE_ARG_RECIPE_INT("-size",        "KERNEL.SIZE",     S32, 0);
    VALUE_ARG_RECIPE_INT("-order",       "SPATIAL.ORDER",   S32, 0);
    VALUE_ARG_RECIPE_FLOAT("-spacing",   "STAMP.SPACING",   F32);
    VALUE_ARG_RECIPE_INT("-footprint",   "STAMP.FOOTPRINT", S32, 0);
    VALUE_ARG_RECIPE_FLOAT("-threshold", "STAMP.THRESHOLD", F32);
    VALUE_ARG_RECIPE_INT("-iter",        "ITER",            S32, 0);
    VALUE_ARG_RECIPE_FLOAT("-rej",       "REJ",             F32);
    VALUE_ARG_RECIPE_MASK("-mask-bad",   "MASK.BAD");
    VALUE_ARG_RECIPE_MASK("-mask-blank", "MASK.BLANK");

    vectorArgRecipe(config, arguments, "-isis-widths", recipe, "ISIS.WIDTHS", config->arguments, PS_TYPE_F32);
    vectorArgRecipe(config, arguments, "-isis-orders", recipe, "ISIS.ORDERS", config->arguments, PS_TYPE_S32);

    psVector *widths = psMetadataLookupPtr(NULL, config->arguments, "ISIS.WIDTHS"); // ISIS Gaussian widths
    psVector *orders = psMetadataLookupPtr(NULL, config->arguments, "ISIS.ORDERS"); // ISIS Polynomial orders
    if (widths->n != orders->n) {
        psError(PS_ERR_BAD_PARAMETER_SIZE, true, "Size of vectors for ISIS widths and orders do not match.");
        goto ERROR;
    }

    psMetadataAddBool(config->arguments, PS_LIST_TAIL, "REVERSE", 0, "Reverse sense of subtraction",
                      psMetadataLookupBool(NULL, arguments, "-reverse"));

    // Translate the kernel type
    psString type = psMetadataLookupStr(NULL, arguments, "-type"); // Name of kernel type
    if (!type || strlen(type) == 0) {
        type = psMetadataLookupStr(NULL, recipe, "KERNEL.TYPE");
        if (!type || strlen(type) == 0) {
            psError(PS_ERR_BAD_PARAMETER_VALUE, false, "Unable to find KERNEL.TYPE specified.");
            goto ERROR;
        }
    }
    pmSubtractionKernelsType kernelType; // Type of kernel
    if (strcasecmp(type, "POIS") == 0) {
        kernelType = PM_SUBTRACTION_KERNEL_POIS;
    } else if (strcasecmp(type, "ISIS") == 0) {
        kernelType = PM_SUBTRACTION_KERNEL_ISIS;
    } else {
        psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Unrecognised kernel type: %s", type);
        goto ERROR;
    }
    psMetadataAddS32(config->arguments, PS_LIST_TAIL, "KERNEL.TYPE", 0, "Type of kernel", kernelType);

    psTrace("ppSub", 1, "Done reading command-line arguments\n");
    psFree(arguments);
    return true;

ERROR:
    psFree(arguments);
    return false;
}


