#ifndef HstAverage_HH
#define HstAverage_HH

#include <cmath>


class HstAverage {

public:
  
  HstAverage() {
    reset();
  }

  std::ostream& print(std::ostream &o) const {
    o << "HstAverage::print()" << std::endl;
    o << " Number " << _number << ", sum " << _sum 
      << ", sum of squares " << _sumOfSquares << std::endl;
    o << " Average = " << average() << " +/- " << errorOnAverage() << std::endl;
    o << " Sigma = " << sigma() << " +/- " << errorOnSigma() << std::endl;
    return o;
  }

  void reset() {
    _number=0;
    _sum=0.0;
    _sumOfSquares=0.0;
  }

  void operator+=(double x) {
    _number++;
    _sum+=x;
    _sumOfSquares+=x*x;
  }

  void operator-=(double x) {
    _number--;
    _sum-=x;
    _sumOfSquares-=x*x;
  }

  void operator+=(const HstAverage &a) {
    _number+=a._number;
    _sum+=a._sum;
    _sumOfSquares+=a._sumOfSquares;
  }

  void event(double x) {
    operator+=(x);
  }

  unsigned number() const {
    return _number;
  }

  double average() const {
    if(_number==0) return 0.0;
    return _sum/_number;
  }

  double sigma() const {
    if(_number<=1) return -1.0;
    double dNumber(_number); // _number > 65k doesn't work due to being squared
    return sqrt((dNumber*_sumOfSquares-_sum*_sum)/(dNumber*(dNumber-1.0)));
  }

  double errorOnAverage() const {
    if(_number<=1) return 0.0;
    double dNumber(_number);
    return sigma()/sqrt(dNumber);
  }

  double errorOnSigma() const {
    if(_number<=1) return 0.0;
    double dNumber(_number);
    return sigma()/sqrt(2.0*(dNumber-1.0));
  }


private:
  unsigned _number;
  double _sum;
  double _sumOfSquares;
};

#endif
