# include "ppStatsInternal.h"

// calculate the stats for the non-constant entries (already calculated)
bool ppStatsFromMetadataStats(psArray *entries)
{
    for (int i = 0; i < entries->n; i++) {
        ppStatsEntry *entry = entries->data[i];

        if (!strcasecmp (entry->statistic, "constant")) continue;

        // XXX skip or warn on missing stats?
        if (!entry->vector) continue;

        psStatsOptions option;
        if (!strcasecmp (entry->statistic, "RMS")) {
            option = psStatsOptionFromString ("SAMPLE_MEAN");
            goto got_stats;
        }
        if (!strcasecmp (entry->statistic, "SUM")) {
            option = psStatsOptionFromString ("SAMPLE_MEAN");
            goto got_stats;
        }
        if (!strcasecmp (entry->statistic, "UQ")) {
            option = psStatsOptionFromString ("ROBUST_QUARTILE");
            goto got_stats;
        }
        if (!strcasecmp (entry->statistic, "LQ")) {
            option = psStatsOptionFromString ("ROBUST_QUARTILE");
            goto got_stats;
        }

        option = psStatsOptionFromString (entry->statistic);

    got_stats:
        if (entry->vector->n == 0) {
            continue;
        }

        psStats *stats = psStatsAlloc(option);
        if (!psVectorStats(stats, entry->vector, NULL, NULL, 0)) {
	    psError(PS_ERR_UNKNOWN, false, "failure to measure stats for %s", entry->statistic);
	    continue;
	}

        double value;
        if (!strcasecmp (entry->statistic, "RMS")) {
            value = sqrt(stats->sampleMean);
            goto got_value;
        }
        if (!strcasecmp (entry->statistic, "SUM")) {
            value = stats->sampleMean * entry->vector->n;
            goto got_value;
        }
        if (!strcasecmp (entry->statistic, "UQ")) {
            value = stats->robustUQ;
            goto got_value;
        }
        if (!strcasecmp (entry->statistic, "LQ")) {
            value = stats->robustLQ;
            goto got_value;
        }
        value = psStatsGetValue(stats, option);

    got_value:
        entry->value = psMetadataItemAllocF32(entry->keyword, entry->statistic, value);
        psFree(stats);
    }
    return true;
}
