# include "psphotInternal.h"

bool psphotStackReadout (pmConfig *config, const pmFPAview *view) {

    psTimerStart ("psphotReadout");

    pmModelClassSetLimits(PM_MODEL_LIMITS_LAX); // allow models to have ugly fits (eg, central cusp)

    // select the current recipe
    psMetadata *recipe = psMetadataLookupPtr (NULL, config->recipes, PSPHOT_RECIPE);
    if (!recipe) {
        psError(PSPHOT_ERR_CONFIG, false, "missing recipe %s", PSPHOT_RECIPE);
        return false;
    }
    // optional break-point for processing
    char *breakPt = psMetadataLookupStr (NULL, recipe, "BREAK_POINT");
    PS_ASSERT_PTR_NON_NULL (breakPt, false);

    // set the photcode for each image
    if (!psphotAddPhotcode (config, view)) {
        psError (PSPHOT_ERR_CONFIG, false, "trouble defining the photcode");
        return false;
    }

    // Generate the mask and weight images
    if (!psphotSetMaskAndVariance (config, view)) {
	return psphotReadoutCleanup (config, view);
    }
    if (!strcasecmp (breakPt, "NOTHING")) {
	return psphotReadoutCleanup (config, view);
    }

    // generate a background model (median, smoothed image)
    // XXX I think this is not defined correctly for an array of images.
    if (!psphotModelBackground (config, view)) {
	return psphotReadoutCleanup (config, view);
    }
    if (!psphotSubtractBackground (config, view)) {
	return psphotReadoutCleanup (config, view);
    }
    if (!strcasecmp (breakPt, "BACKMDL")) {
	return psphotReadoutCleanup (config, view);
    }

    // load the psf model, if suppled.  FWHM_X,FWHM_Y,etc are determined and saved on
    // readout->analysis XXX this function currently only works with a single PSPHOT.INPUT
    if (!psphotLoadPSF (config, view)) {
        psError (PSPHOT_ERR_UNKNOWN, false, "error loading psf model");
        return psphotReadoutCleanup (config, view);
    }

    if (!psphotStackChisqImage(config, view)) {
        psError (PSPHOT_ERR_UNKNOWN, false, "failure to generate chisq image");
        return psphotReadoutCleanup (config, view);
    }
    if (!strcasecmp (breakPt, "CHISQ")) {
	return psphotReadoutCleanup (config, view);
    }

    // find the detections (by peak and/or footprint) in the image.
    // This finds the detections on Chisq image as well as the individuals
    if (!psphotFindDetections (config, view, true)) { // pass 1
        // this only happens if we had an error in psphotFindDetections
        psError (PSPHOT_ERR_UNKNOWN, false, "failure in peak analysis");
        return psphotReadoutCleanup (config, view);
    }

    // construct sources and measure basic stats (saved on detections->newSources)
    // only run this on detections from the input images, not chisq image
    if (!psphotSourceStats (config, view, true)) { // pass 1
        psError(PSPHOT_ERR_UNKNOWN, false, "failure to generate sources");
        return psphotReadoutCleanup (config, view);
    }

    // *** generate the objects (which unify the sources from the different images)
    psArray *objects = psphotMatchSources (config, view);

    // construct sources for the newly-generated sources (from other images)
    if (!psphotSourceStats (config, view, false)) { // pass 1
        psError(PSPHOT_ERR_UNKNOWN, false, "failure to generate sources");
        return psphotReadoutCleanup (config, view);
    }

    // find blended neighbors of very saturated stars (detections->newSources)
    // if (!psphotDeblendSatstars (config, view)) {
    //     psError (PSPHOT_ERR_UNKNOWN, false, "failed on satstar deblend analysis");
    //     return psphotReadoutCleanup (config, view);
    // }

    // mark blended peaks PS_SOURCE_BLEND (detections->newSources)
    // if (!psphotBasicDeblend (config, view)) {
    //     psError (PSPHOT_ERR_UNKNOWN, false, "failed on deblend analysis");
    //     return psphotReadoutCleanup (config, view);
    // }

    // classify sources based on moments, brightness
    // only run this on detections from the input images, not chisq image
    if (!psphotRoughClass (config, view)) {
        psError (PSPHOT_ERR_UNKNOWN, false, "failed to determine rough classifications");
	return psphotReadoutCleanup (config, view);
    }
    // if we were not supplied a PSF model, determine the IQ stats here (detections->newSources)
    // only run this on detections from the input images, not chisq image
    if (!psphotImageQuality (config, view)) { // pass 1
        psError (PSPHOT_ERR_UNKNOWN, false, "failed to measure image quality");
        return psphotReadoutCleanup(config, view);
    }
    if (!strcasecmp (breakPt, "MOMENTS")) {
	return psphotReadoutCleanup (config, view);
    }

    // use bright stellar objects to measure PSF if we were supplied a PSF for any input file,
    // this step is skipped
    if (!psphotChoosePSF (config, view)) { // pass 1
        psLogMsg ("psphot", 3, "failure to construct a psf model");
        return psphotReadoutCleanup (config, view);
    }
    if (!strcasecmp (breakPt, "PSFMODEL")) {
        return psphotReadoutCleanup (config, view);
    }

    // include externally-supplied sources
    // XXX fix this in the new multi-input context
    // psphotLoadExtSources (config, view); // pass 1

    // construct an initial model for each object, set the radius to fitRadius, set circular fit mask
    psphotGuessModels (config, view);

    // merge the newly selected sources into the existing list
    // NOTE: merge OLD and NEW
    psphotMergeSources (config, view);

    // linear PSF fit to source peaks, subtract the models from the image (in PSF mask)
    psphotFitSourcesLinearStack (config, objects, FALSE);
    psFree (objects);

    // identify CRs and extended sources
    psphotSourceSize (config, view, TRUE);

    // measure aperture photometry corrections
    if (!psphotApResid (config, view)) {
        psLogMsg ("psphot", 3, "failed on psphotApResid");
	return psphotReadoutCleanup (config, view);
    }

    // calculate source magnitudes
    psphotMagnitudes(config, view);

    if (!psphotEfficiency(config, view)) {
        psErrorStackPrint(stderr, "Unable to determine detection efficiencies from fake sources");
        psErrorClear();
    }

    // replace failed sources?
    // psphotReplaceUnfitSources (sources);

    // replace background in residual image
    psphotSkyReplace (config, view);

    // drop the references to the image pixels held by each source
    psphotSourceFreePixels (config, view);

    // remove chisq image from config->file:PSPHOT.INPUT (why?)
    psphotStackRemoveChisqFromInputs(config);

    // create the exported-metadata and free local data
    return psphotReadoutCleanup (config, view);
}

