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

#include "ppImage.h"

// write stats to output file 
bool ppImageStatsOutput (pmConfig *config, const ppImageOptions *options) {

    bool mdok;

    // measure statistics, or ignore?
    if (!options->doStats) return true;
	
    // PPIMAGE.STATS is stored on PPIMAGE.OUTPUT
    pmFPAfile *output = psMetadataLookupPtr(&mdok, config->files, "PPIMAGE.OUTPUT");
    if (!output) {
	psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find PPIMAGE.OUTPUT entry in config file.\n");
	return false;
    }

    // select the fpa-level analysis stats metadata:
    psMetadata *stats = psMetadataLookupPtr (&mdok, output->fpa->analysis, "PPIMAGE.STATS");
    if (!stats) {
	psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find PPIMAGE.STATS entry in output fpa analysis.\n");
	return false;
    }

    // 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;
    } 

    // get the output stats filename
    const char *statsName = psMetadataLookupStr(&mdok, config->arguments, "STATS"); // Filename for statistics
    if (!statsName && !strlen(statsName)) {
	psError (PS_ERR_UNEXPECTED_NULL, false, "missing STATS entry in arguments list.");
	psFree(statsMDC);
	return false;
    }

    // convert to a real UNIX filename
    psString resolved = pmConfigConvertFilename(statsName, config, true); // 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(statsMDC);
	psFree(resolved);
	return false;
    }
    psFree(resolved);

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

    psFree(statsMDC);
    fclose(statsFile);
    return true;
}
