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

# include "psphot.h"

// XXX we can probably move this into pmGrowthCurve.c
// XXX need to change the way we grab an image, or else use
//     the 'center' option

bool psphotGrowthCurve (pmReadout *readout, pmPSF *psf) { 

    // bool status;
    float xc, yc, dx, dy;
    float fitMag, apMag;
    float radius;

    // create template model
    pmModel *modelRef = pmModelAlloc(psf->type);

    // use center of the image 
    xc = 0.5*readout->image->numCols + readout->image->col0;
    yc = 0.5*readout->image->numRows + readout->image->row0;
    dx = psf->growth->maxRadius + 1;
    dy = psf->growth->maxRadius + 1;

    // assign the x and y coords to the image center
    // create an object with center intensity of 1000
    modelRef->params->data.F32[0] = 0;
    modelRef->params->data.F32[1] = 1000;
    modelRef->params->data.F32[2] = xc;
    modelRef->params->data.F32[3] = yc;

    // create modelPSF from this model
    pmModel *model = pmModelFromPSF (modelRef, psf);

    // generate working image for this source
    psRegion region = {xc - dx, xc + dx, yc - dy, yc + dy};
    psImage *view = psImageSubset (readout->image, region);
    psImage *image = psImageCopy (NULL, view, PS_TYPE_F32);
    psImage *mask = psImageCopy (NULL, view, PS_TYPE_U8);
    psImageInit (mask, 0);

    // loop over a range of source fluxes
    for (int i = 0; i < psf->growth->radius->n; i++) {

	psImageInit (image, 0.0);

	radius = psf->growth->radius->data.F32[i];

	psImageKeepCircle (mask, xc, yc, radius, "OR", PM_MASK_MARK);

	pmModelAdd (image, mask, model, false, false);

	pmSourcePhotometryAper (&apMag, model, image, mask);

	psImageKeepCircle (mask, xc, yc, radius, "AND", NOT_U8(PM_MASK_MARK));
	psf->growth->apMag->data.F32[i] = apMag;
    }

    pmSourcePhotometryModel (&fitMag, model);
    psf->growth->fitMag = fitMag;

    psf->growth->apRef = psVectorInterpolate (psf->growth->radius, psf->growth->apMag, psf->growth->refRadius);
    psf->growth->apLoss = psf->growth->fitMag - psf->growth->apRef;

    psLogMsg ("psphot.growth", 4, "GrowthCurve : apLoss : %f\n", psf->growth->apLoss);
    
    psFree (view);
    psFree (image);
    psFree (mask);
    psFree (model);
    psFree (modelRef);

    return true;
}
