# include "psphotInternal.h"

// psphotReadoutCleanup is called on exit from psphotReadout.  If the last raised error is
// not a DATA error, then there was a serious problem.  Only in this case, or if the fail
// on the stats measurement, do we return false
bool psphotReadoutCleanup (pmConfig *config, pmReadout *readout, psMetadata *recipe, pmDetections *detections, pmPSF *psf, psArray *sources) {

    // remove internal pmFPAfiles, if created
    bool status = true;
    status &= pmFPAfileDropInternal (config->files, "PSPHOT.BACKMDL");
    status &= pmFPAfileDropInternal (config->files, "PSPHOT.BACKMDL.STDEV");
    status &= pmFPAfileDropInternal (config->files, "PSPHOT.BACKGND");
    if (!status) {
	psError(PSPHOT_ERR_PROG, false, "trouble dropping internal files");
	psFree (psf);
	psFree (sources);
	psFree (detections);
	return false;
    }

    if (psErrorCodeLast() == PSPHOT_ERR_DATA) {
        psErrorStackPrint(stderr, "Error in the psphot readout analysis");
	psErrorClear();
    } 
    if (psErrorCodeLast() != PS_ERR_NONE) { 
	psFree (psf);
	psFree (sources);
	psFree (detections);
	return false;
    }

    // use the psf-model to measure FWHM stats
    if (psf) {
        if (!psphotPSFstats (readout, recipe, psf)) {
            psError(PSPHOT_ERR_PROG, false, "Failed to measure PSF shape parameters");
	    psFree (psf);
	    psFree (sources);
	    psFree (detections);
            return false;
        }
    }
    // otherwise, use the source moments to measure FWHM stats
    if (!psf && sources) {
        if (!psphotMomentsStats (readout, recipe, sources)) {
            psError(PSPHOT_ERR_PROG, false, "Failed to measure Moment shape parameters");
	    psFree (psf);
	    psFree (sources);
	    psFree (detections);
            return false;
        }
    }

    // write NSTARS to the image header
    psphotSetHeaderNstars (recipe, sources);

    // create an output header with stats results
    psMetadata *header = psphotDefineHeader (recipe);

    // save the results of the analysis
    psMetadataAdd (readout->analysis, PS_LIST_TAIL, "PSPHOT.HEADER",  PS_DATA_METADATA, "header stats", header);
    if (sources) {
	psMetadataAdd (readout->analysis, PS_LIST_TAIL, "PSPHOT.SOURCES", PS_DATA_ARRAY, "psphot sources", sources);
    }
    if (psf) {
	// save the psf for possible output.  if there was already an entry, it was loaded from external sources
	// the new one may have been updated or modified, so replace the existing entry.  We
	// are required to save it on the chip, but this will cause problems if we ever want to
	// run psphot on an unmosaiced image
	pmCell *cell = readout->parent;
	pmChip *chip = cell->parent;
	psMetadataAdd (chip->analysis, PS_LIST_TAIL, "PSPHOT.PSF", PS_DATA_UNKNOWN | PS_META_REPLACE,  "psphot psf", psf);
    }

    if (psErrorCodeLast() != PS_ERR_NONE) {
        psErrorStackPrint(stderr, "unexpected remaining errors");
	abort();
    }

    // XXX move this to top of loop?
    pmKapaClose ();

    psFree (detections);
    psFree (psf);
    psFree (header);
    psFree (sources);

    return true;
}
