#ifndef _OT_BOILER_H
#define _OT_BOILER_H

#include "Arduino.h"

#include "BoilerDefinition.h"

/*
 *	Simple Moving Average
 */

template <class V, class M> class SMA {

protected:
	size_t		order;
	size_t		load;
	size_t		last_;
	size_t		first_;
	V		*value;
	M		mean_;

public:
	SMA (size_t order);
	~SMA ();

	bool		loaded () const { return (load == order); }

	SMA&		push (const V& value);

	const V&	first () const { return value[first_]; }
	const V&	last () const { return value[last_]; }

	M		calc () const;
	M		slope () const;

	const M&	mean () const { return mean_; }

	operator	M () const { return mean(); }
};

template <class V, class M>	SMA<V,M>::SMA (size_t o)
:
	order(o),
	load(0),
	last_(0),
	first_(0),
	mean_(0)
{
	value = new V[order];
	value[0] = 0;	// pre-init first element in case of access before loaded...
}

template <class V, class M>	SMA<V,M>::~SMA ()
{
	delete value;
}

template <class V, class M> SMA<V,M>&	SMA<V,M>::push (const V& v)
{
	if (load < order) {
		last_= load++;
		first_ = load;
		value[last_] = v;
		mean_ = calc();
	} else {
		last_ = first_++;
		V drop(value[last_]);
		value[last_] = v;
		// m(t) = m(t-1) + x(t)/n - x(t-n)/n
		mean_ += M(v-drop)/M(order);
	}
	first_ %= order;
	return *this;
}

template <class V, class M> M	SMA<V,M>::calc () const
{
	M m(0);
	for (int i=0; i<load; i++) {
		m += M(value[i]);
	}
	return m/M(load);
}

template <class V, class M> M	SMA<V,M>::slope () const
{
	return (load > 1) ? M(value[last_]-value[first_])/M(load-1) : M(0);
}

#endif
