#ifndef MARS_MExtralgoDigitalFilter
#define MARS_MExtralgoDigitalFilter

#ifndef ROOT_TROOT
#include <TROOT.h>
#endif

class MExtralgoDigitalFilter
{
private:
    // Input
    Float_t *fVal;
    Int_t    fNum;

    Float_t *fWeightsAmp;
    Float_t *fWeightsTime;

    Int_t   fWeightsPerBin; // Number of weights per data bin

    // Result
    Float_t fTime;
    Float_t fTimeDev;
    Float_t fSignal;
    Float_t fSignalDev;

    inline void Eval(Double_t &sumamp, Double_t &sumtime, const Int_t windowsize, const Int_t startv, const Int_t startw=0) const
    {
        //
        // Slide with a window of size windowsize over the sample
        // and multiply the entries with the corresponding weights
        //
        sumamp = 0;
        sumtime = 0;

        // Shift the start of the weight to the center of sample 0
        Float_t const *wa  = fWeightsAmp  + fWeightsPerBin/2 + startw;
        Float_t const *wt  = fWeightsTime + fWeightsPerBin/2 + startw;
        Float_t *const beg = fVal+startv;

        for (Float_t const *pex=beg; pex<beg+windowsize; pex++)
        {
            sumamp  += *wa * *pex;
            sumtime += *wt * *pex;

            // Step forward by one bin
            wa += fWeightsPerBin;
            wt += fWeightsPerBin;
        }
    }

public:
    MExtralgoDigitalFilter(Float_t *val, Int_t n, Float_t *wa, Float_t *wt)
        : fVal(val), fNum(n),
        fWeightsAmp(wa), fWeightsTime(wt), fTime(0), fTimeDev(-1), fSignal(0), fSignalDev(-1)
    {
    }

    void SetWeightsPerBin(Int_t res) { fWeightsPerBin=res; }

    Float_t GetTime() const          { return fTime; }
    Float_t GetSignal() const        { return fSignal; }

    Float_t GetTimeDev() const       { return fTimeDev; }
    Float_t GetSignalDev() const     { return fSignalDev; }

    void GetSignal(Float_t &sig, Float_t &dsig) const { sig=fSignal; dsig=fSignalDev; }
    void GetTime(Float_t &sig, Float_t &dsig) const   { sig=fTime; dsig=fTimeDev; }

    Float_t ExtractNoise(Int_t iter, Int_t windowsize) const;
    void Extract(Int_t windowsize, Float_t timeshift);
};


#endif
