/**
 * \file histogram.c
 * \brief This file contains the histogram structure functions
 *
 *
 *  \ingroup corefiles
 * \date Jul 10, 2009
 * \author: Alexander Pimenov
 */

#include "global.h"
#include "histogram.h"
#include <stdlib.h>

Histogram *histogramCreateFromG12Buffer(G12Buffer *buf)
{
	int i,j;
	Histogram *toReturn = (Histogram *)dv_calloc(1,sizeof(Histogram));

	for (i = 0; i < buf->h; i++)
		for (j = 0; j < buf->w; j++)
		{
			uint16_t value = G12ELEM(buf, j, i);
			// TODO: Correct this!!!
			if (value < G12BUFFER_MAX_VALUE)
			{
				toReturn->data[value]++;
			}
		}
	return toReturn;
}

void histogramDelete(Histogram *toDelete)
{
	dv_free(toDelete);
}

uint32_t histogramGetMaximum(Histogram *hist)
{
	int i;
	uint32_t max = 0;
	for (i = 0; i < G12BUFFER_MAX_VALUE; i++)
	{
		if (hist->data[i] > max)
			max = hist->data[i];
	}
	return max;
}

uint32_t histogramGetIntervalSum(Histogram *hist, uint16_t start, uint16_t end)
{
	int i;
#ifdef ASSERTS
	if (start < 0 || start > G12BUFFER_MAX_VALUE || end < 0 || end > G12BUFFER_MAX_VALUE)
		DOASSERT("Error");
#endif
	uint32_t sum = 0;
	for(i = start; i < end; i++)
	{
		sum += hist->data[i];
	}
	return sum;
}
