# include "psastroInternal.h"

bool psastroMetadataStats (pmConfig *config) {

    bool status;

    char *filename = psMetadataLookupStr (&status, config->arguments, "STATS");
    if (!filename) return true; // stats not requested

    // Extract statistics from the last output fpa
    pmFPAfile *output = psMetadataLookupPtr(&status, config->files, "PSASTRO.OUTPUT");

    if (!output) {
	psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find output file (PSASTRO.OUTPUT).");
	return false;
    }

    // create output stats metadata
    psMetadata *stats = psMetadataAlloc ();

    // extract stats for the complete fpa 
    pmFPAview *view = pmFPAviewAlloc(0);

    if (!ppStatsMetadata(stats, output->fpa, view, 0, config)) {
	psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to generate stats for image.");
	psFree(view);
	psFree(stats);
	return false;
    }

    // if we did not request any specific stats, the structure is empty
    if (stats && stats->list->n == 0) {
	psWarning ("stats output specified, but no requested stats entries in headers");
	psFree(view);
	psFree(stats);
	return true;
    }

    // convert the stats MDC to a string
    char *statsMDC = psMetadataConfigFormat(stats);
    if (!statsMDC || strlen(statsMDC) == 0) {
	psError(PS_ERR_IO, false, "Unable to serialize stats metadata.\n");
	return false;
    } 

    // convert to a real UNIX filename
    psString resolved = pmConfigConvertFilename(filename, config, true, false); // Resolved filename
    FILE *statsFile = fopen (resolved, "w");
    if (!statsFile) {
	psError(PS_ERR_IO, true, "Unable to open statistics file %s for writing.\n", resolved);
	psFree(stats);
	psFree(view);
	psFree(statsMDC);
	psFree(resolved);
	return false;
    }

    // write the stats MDC to a file
    // XXX why does this not call psMetadataConfigPrint?
    fprintf(statsFile, "%s", statsMDC);
    fclose(statsFile);

    psFree(resolved);
    psFree(statsMDC);
    psFree(view);
    psFree(stats);
    return true;
}
