#ifndef UtlRollingAverage_HH
#define UtlRollingAverage_HH

#include <cmath>

#include "UtlAverage.hh"


class UtlRollingAverage : public UtlAverage {

public:
  
  UtlRollingAverage(unsigned l=100) : UtlAverage(), _length(l),
				      _data(new double[l]), _totalNumber(0) {
  }

  virtual ~UtlRollingAverage() {
    delete [] _data;
  }

  virtual std::ostream& print(std::ostream &o) const {
    o << "UtlRollingAverage::print()";
    o << " Rolling average over " << _length << std::endl;
    o << " Total number of values " << _totalNumber << std::endl;
    UtlAverage::print(o);
    return o;
  }

  virtual void reset() {
    _totalNumber=0;
    UtlAverage::reset();
  }

  unsigned totalNumber() const {
    return _totalNumber;
  }

  virtual void operator+=(double x) {
    const unsigned n(_totalNumber%_length);

    if(_totalNumber>=_length) {
      UtlAverage::operator-=(_data[n]);
    }
      _data[n]=x;

    UtlAverage::operator+=(_data[n]);
    _totalNumber++;
  }

  virtual void recalculate() {
    UtlAverage::print(std::cout);
    UtlAverage::reset();
    unsigned n(_length);
    if(_totalNumber<_length) n=_totalNumber;
    for(unsigned i(0);i<n;i++) UtlAverage::operator+=(_data[i]);
    UtlAverage::print(std::cout);
  }


private:
  const unsigned _length;
  double* const _data;
  unsigned _totalNumber;
};

#endif
