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

# include "psphot.h"

bool psphotFitSet (pmSource *source, pmModel *oneModel, char *fitset, pmSourceFitMode mode) {

    double x, y, Io;

    FILE *f = fopen (fitset, "r");
    if (f == NULL) return false;

    psArray *modelSet = psArrayAlloc (16);
    // DROP modelSet->n = 0;

    while (fscanf (f, "%lf %lf %lf", &x, &y, &Io) == 3) {
	pmModel *model = pmModelAlloc (oneModel->type);
	
	for (psS32 i = 0; i < model->params->n; i++) {
	    model->params->data.F32[i] = oneModel->params->data.F32[i];
	    model->dparams->data.F32[i] = oneModel->dparams->data.F32[i];
	}
	model->params->data.F32[1] = Io;
	model->params->data.F32[2] = x;
	model->params->data.F32[3] = y;
	psArrayAdd (modelSet, 16, model);
    }

    pmSourceFitSet (source, modelSet, mode);

    // write out positive object
    psphotSaveImage (NULL, source->pixels, "object.fits");

    // subtract object, leave local sky
    for (int i = 0; i < modelSet->n; i++) {
	pmModel *model = modelSet->data[i];
	pmModelSub (source->pixels, source->mask, model, false, false);
    
	fprintf (stderr, "output parameters (obj %d):\n", i);
	for (int n = 0; n < model->params->n; n++) {
	    fprintf (stderr, "%d : %f\n", n, model->params->data.F32[n]);
	}
    }

    // write out 
    psphotSaveImage (NULL, source->pixels, "resid.fits");
    psphotSaveImage (NULL, source->mask, "mask.fits");
    return true;
}

