# include "psphot.h"

// save as static values so they may be set externally
static psF32 PM_SOURCE_FIT_MODEL_NUM_ITERATIONS = 15;
static psF32 PM_SOURCE_FIT_MODEL_TOLERANCE = 0.1;
// static psF32 PM_SOURCE_FIT_MODEL_WEIGHT = 1.0;
// static bool  PM_SOURCE_FIT_MODEL_PIX_WEIGHTS = true;

// input source has both modelPSF and modelEXT.  on successful exit, we set the
// modelConv to contain the fitted parameters, and the modelFlux to contain the 
// convolved model image.
bool psphotPSFConvModel (pmSource *source, psMetadata *recipe, psMaskType maskVal) {
    
    bool status;

    int psfSize = psMetadataLookupS32 (&status, recipe, "PCM_BOX_SIZE");
    if (!status) {
	psfSize = 2;
    }

    // make sure we save a cached copy of the psf flux
    pmSourceCachePSF (source, maskVal);

    // convert the cached cached psf model for this source to a psKernel
    // XXX for the moment, hard-wire the kernel to be 5x5 (2 pix radius)
    // XXX for the moment, hard-wire the kernel to be 9x9 (4 pix radius)
    psKernel *psf = psphotKernelFromPSF (source, psfSize);

    // psf must be normalized (integral = 1.0)
    double sum = 0.0;
    for (int i = 0; i < psf->image->numRows; i++) {
	for (int j = 0; j < psf->image->numCols; j++) {
	    sum += psf->image->data.F32[i][j];
	}
    }
    assert (sum > 0.0);
    for (int i = 0; i < psf->image->numRows; i++) {
	for (int j = 0; j < psf->image->numCols; j++) {
	    psf->image->data.F32[i][j] /= sum;
	}
    }

# if (0)
    // XXX sanity check: convolve with delta function should behave like unconvolved version
    for (int i = 0; i < psf->image->numRows; i++) {
	for (int j = 0; j < psf->image->numCols; j++) {
	    psf->image->data.F32[i][j] = 0.0;
	}
    }
    psf->image->data.F32[2][2] = 1.0;
# endif

    // generate copy of the model
    // XXX we could modify the parameter values or even the model 
    // here based on the observed seeing (some lookup table...)
    pmModel *modelConv = pmModelCopy (source->modelEXT);
    psVector *params  = modelConv->params;
    psVector *dparams = modelConv->dparams;

    // create the minimization constraints
    psMinConstraint *constraint = psMinConstraintAlloc();
    constraint->paramMask = psVectorAlloc (params->n, PS_TYPE_U8);
    constraint->checkLimits = modelConv->modelLimits;

    // set parameter mask based on fitting mode
    // we fit a model without a floating sky term
    int nParams = params->n - 1;
    psVectorInit (constraint->paramMask, 0);
    constraint->paramMask->data.U8[PM_PAR_SKY] = 1;

    // force the floating parameters to fall within the contraint ranges
    for (int i = 0; i < params->n; i++) {
	modelConv->modelLimits (PS_MINIMIZE_PARAM_MIN, i, params->data.F32, NULL);
	modelConv->modelLimits (PS_MINIMIZE_PARAM_MAX, i, params->data.F32, NULL);
    }

    // set up the minimization process
    psMinimization *myMin = psMinimizationAlloc (PM_SOURCE_FIT_MODEL_NUM_ITERATIONS, PM_SOURCE_FIT_MODEL_TOLERANCE);

    psImage *covar = psImageAlloc (params->n, params->n, PS_TYPE_F32);

    bool fitStatus = psphotModelWithPSF_LMM (myMin, covar, params, constraint, source, psf, modelConv->modelFunc);
    for (int i = 0; i < dparams->n; i++) {
        if (psTraceGetLevel("psphot") >= 4) {
            fprintf (stderr, "%f ", params->data.F32[i]);
        }
        if ((constraint->paramMask != NULL) && constraint->paramMask->data.U8[i])
            continue;
        dparams->data.F32[i] = sqrt(covar->data.F32[i][i]);
    }
    psTrace ("psphot", 4, "niter: %d, chisq: %f", myMin->iter, myMin->value);

    // renormalize output model image
    float Io = params->data.F32[PM_PAR_I0];
    for (int iy = 0; iy < source->modelFlux->numRows; iy++) {
	for (int ix = 0; ix < source->modelFlux->numCols; ix++) {
	    source->modelFlux->data.F32[iy][ix] /= Io;
	}
    }

    // save the resulting chisq, nDOF, nIter
    modelConv->chisq = myMin->value;
    modelConv->nIter = myMin->iter;

    // XXX I actually need to count the number of unmasked pixels here
    modelConv->nDOF  = source->pixels->numCols*source->pixels->numRows  -  nParams;

    modelConv->flags |= PM_MODEL_STATUS_FITTED;
    if (!fitStatus) modelConv->flags |= PM_MODEL_STATUS_NONCONVERGE;

    // models can go insane: reject these
    bool onPic = true;
    onPic &= (params->data.F32[PM_PAR_XPOS] >= source->pixels->col0);
    onPic &= (params->data.F32[PM_PAR_XPOS] <  source->pixels->col0 + source->pixels->numCols);
    onPic &= (params->data.F32[PM_PAR_YPOS] >= source->pixels->row0);
    onPic &= (params->data.F32[PM_PAR_YPOS] <  source->pixels->row0 + source->pixels->numRows);
    if (!onPic) {
        modelConv->flags |= PM_MODEL_STATUS_OFFIMAGE;
    }

    source->mode |= PM_SOURCE_MODE_FITTED;
    source->modelConv = modelConv;

    psFree(myMin);
    psFree(covar);
    psFree(constraint);

    bool retval = (onPic && fitStatus);
    psTrace("psphot", 5, "---- %s(%d) end ----\n", __func__, retval);
    return(retval);
}
