# include "psphotInternal.h"

// aperture-like measurements for extended sources
bool psphotExtendedSourceAnalysis (pmReadout *readout, psArray *sources, psMetadata *recipe) {

    bool status;
    int Next = 0;
    int Npetro = 0;
    int Nisophot = 0;
    int Nannuli = 0;
    int Nkron = 0;

    // user-defined masks to test for good/bad pixels (build from recipe list if not yet set)
    psMaskType maskVal = psMetadataLookupU8(&status, recipe, "MASK.PSPHOT"); // Mask value for bad pixels
    assert (maskVal);

    // perform full non-linear fits / extended source analysis?
    if (!psMetadataLookupBool (&status, recipe, "EXTENDED_SOURCE_ANALYSIS")) {
	psLogMsg ("psphot", PS_LOG_INFO, "skipping extended source measurements\n");
	return true;
    }

    // option to limit analysis to a specific region
    char *region = psMetadataLookupStr (&status, recipe, "ANALYSIS_REGION");
    psRegion AnalysisRegion = psRegionForImage (readout->image, psRegionFromString (region));
    if (psRegionIsNaN (AnalysisRegion)) psAbort("analysis region mis-defined");

    // S/N limit to perform full non-linear fits
    float SN_LIM = psMetadataLookupF32 (&status, recipe, "EXTENDED_SOURCE_SN_LIM");

    // which extended source analyses should we perform?
    bool doPetrosian    = psMetadataLookupBool (&status, recipe, "EXTENDED_SOURCE_PETROSIAN");
    bool doIsophotal    = psMetadataLookupBool (&status, recipe, "EXTENDED_SOURCE_ISOPHOTAL");
    bool doAnnuli       = psMetadataLookupBool (&status, recipe, "EXTENDED_SOURCE_ANNULI");
    bool doKron         = psMetadataLookupBool (&status, recipe, "EXTENDED_SOURCE_KRON");

    // source analysis is done in S/N order (brightest first)
    sources = psArraySort (sources, pmSourceSortBySN);

    // XXX some init functions for the extended source recipe options?

    // choose the sources of interest
    for (int i = 0; i < sources->n; i++) {

	pmSource *source = sources->data[i];

	// skip PSF-like and non-astronomical objects
	if (source->type == PM_SOURCE_TYPE_STAR) continue;
	if (source->type == PM_SOURCE_TYPE_DEFECT) continue;
	if (source->type == PM_SOURCE_TYPE_SATURATED) continue;

	// limit selection to some SN limit
	assert (source->peak); // how can a source not have a peak?
	if (source->peak->SN < SN_LIM) continue;

	// limit selection by analysis region
	if (source->peak->x < AnalysisRegion.x0) continue;
	if (source->peak->y < AnalysisRegion.y0) continue;
	if (source->peak->x > AnalysisRegion.x1) continue;
	if (source->peak->y > AnalysisRegion.y1) continue;

	// replace object in image
	if (source->mode & PM_SOURCE_MODE_SUBTRACTED) {
	    pmSourceAdd (source, PM_MODEL_OP_FULL, maskVal);
	}
	Next ++;

	// if we request any of these measurements, we require the radial profile
	if (doPetrosian || doIsophotal || doAnnuli || doKron) {
	    if (!psphotRadialProfile (source, recipe, maskVal)) {
		// all measurements below require the radial profile; skip them all
		// re-subtract the object, leave local sky
		psTrace ("psphot", 5, "failed to extract radial profile for source at %7.1f, %7.1f", source->moments->x, source->moments->y);
		pmSourceSub (source, PM_MODEL_OP_FULL, maskVal);
		source->mode |= PM_SOURCE_MODE_SUBTRACTED;
		continue;
	    }
	}

	// Isophotal Mags
	if (doIsophotal) {
	    if (!psphotIsophotal (source, recipe, maskVal)) {
		psTrace ("psphot", 5, "failed to measure isophotal mags for source at %7.1f, %7.1f", source->moments->x, source->moments->y);
	    } else {
		psTrace ("psphot", 5, "measured isophotal mags for source at %7.1f, %7.1f", source->moments->x, source->moments->y);
		Nisophot ++;
	    }
	}

	// Petrosian Mags
	if (doPetrosian) {
	    if (!psphotPetrosian (source, recipe, maskVal)) {
		psTrace ("psphot", 5, "measured petrosian flux & radius for source at %7.1f, %7.1f", source->moments->x, source->moments->y);
	    } else {
		psTrace ("psphot", 5, "measured petrosian flux & radius for source at %7.1f, %7.1f", source->moments->x, source->moments->y);
		Npetro ++;
	    }
	}

	// Kron Mags
	if (doKron) {
	    if (!psphotKron (source, recipe, maskVal)) {
		psTrace ("psphot", 5, "failed to measure kron mags for source at %7.1f, %7.1f", source->moments->x, source->moments->y);
	    } else {
		psTrace ("psphot", 5, "measure kron mags for source at %7.1f, %7.1f", source->moments->x, source->moments->y);
		Nkron ++;
	    }
	}

	// Radial Annuli
	if (doAnnuli) {
	    if (!psphotAnnuli (source, recipe, maskVal)) {
		psError(PSPHOT_ERR_UNKNOWN, false, "failure in Annuli analysis");
		return false;
	    } 
	    psTrace ("psphot", 5, "measured annuli for source at %7.1f, %7.1f", source->moments->x, source->moments->y);
	    Nannuli ++;
	}

	// re-subtract the object, leave local sky
	pmSourceSub (source, PM_MODEL_OP_FULL, maskVal);
	source->mode |= PM_SOURCE_MODE_SUBTRACTED;
    }

    psLogMsg ("psphot", PS_LOG_INFO, "extended source analysis: %f sec for %d objects\n", psTimerMark ("psphot"), Next);
    psLogMsg ("psphot", PS_LOG_INFO, "  %d petrosian\n", Npetro);
    psLogMsg ("psphot", PS_LOG_INFO, "  %d isophotal\n", Nisophot);
    psLogMsg ("psphot", PS_LOG_INFO, "  %d annuli\n", Nannuli);
    psLogMsg ("psphot", PS_LOG_INFO, "  %d kron\n", Nkron);
    return true;
}
