/* -----------------------------------------------------------------------------
	GSFramework
	Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */


#ifndef	__SMARTMEDIANAVG__
#define	__SMARTMEDIANAVG__


		#include "sort/sort.h"


namespace GS {

//
template <class T, int Size = 16, int SafeGuard = 4> class SmartMedianAverage
{
	T			history[Size];
	int			count;

public:

	void		LogValue(T v)
	{
		if	(count < Size)
			count++;	// fill up
		else
			for (int n = 1; n < Size; ++n)	// scroll
				history[n - 1] = history[n];

		history[count - 1] = v;
	}
	T			GetMedian() const
	{
		if	(count == 0)
			return 0;
		if	(count < Size)
			return history[0];	// unfiltered

		// Sort current histogram values.
		typename Sort <T, int> ::Entry entries[Size];
		for (int n = 0; n < Size; ++n)
			entries[n].v = history[n];
		Sort <T, int> ::QuickSort(Size, entries);

		// Compute average of the safe values.
		T avg = 0;
		for (int n = (Size / SafeGuard); n < (Size - Size / SafeGuard); ++n)
			avg += entries[n].v;

		return avg / (Size - (Size / SafeGuard) * 2);
	}
	void		Reset() { count = 0; }

	SmartMedianAverage() : count(0) {}
};

} // GS


#endif // __SMARTMEDIANAVG__
