#ifndef MARS_MBinning
#define MARS_MBinning

#ifndef MARS_MParContainer
#include "MParContainer.h"
#endif

#ifndef ROOT_TArrayD
#include <TArrayD.h>
#endif

class TH1;
class TAxis;

class MBinning : public MParContainer
{
private:
    TArrayD fEdges;

    Byte_t  fType;

    void StreamPrimitive(ofstream &out) const;

    enum {
        kIsDefault,
        kIsLinear,
        kIsLogarithmic,
        kIsCosinic,
        kIsUserArray
    };

public:
    MBinning(const char *name=NULL, const char *title=NULL);
    MBinning(Int_t nbins, Axis_t lo, Axis_t hi, const char *name, const char *opt="", const char *title=NULL);

    void SetEdges(const TArrayD &arr)
    {
        fEdges = arr;
        fType = kIsUserArray;
    }

    void SetEdges(const TAxis &axe);
    void SetEdges(const TH1 &h, const Char_t axis='x');
    void SetEdges(const Int_t nbins, const Axis_t lo, Axis_t up);
    void SetEdges(const Int_t nbins, const Axis_t lo, Axis_t up, const char *opt);
    void SetEdgesLog(const Int_t nbins, const Axis_t lo, Axis_t up);
    void SetEdgesCos(const Int_t nbins, const Axis_t lo, Axis_t up);

    Int_t FindLoEdge(Double_t val) const
    {
        if (val<GetEdgeLo() || val>=GetEdgeHi())
            return -1;

	for (int i=1; i<fEdges.GetSize(); i++)
        {
            if (((TArrayD)fEdges)[i] >= val)
                return i-1;
        }
        return -1;
    }
    Int_t FindHiEdge(Double_t val) const
    {
        const Int_t i = FindLoEdge(val);
        return i<0 ? -1 : i+1;
    }

    // FIXME: ROOT workaround: "operator[] const" missing
    Double_t GetEdgeLo() const { return ((TArrayD)fEdges)[0]; }
    Double_t GetEdgeHi() const { return ((TArrayD)fEdges)[fEdges.GetSize()-1]; }

    Int_t GetNumEdges() const { return fEdges.GetSize(); }
    Int_t GetNumBins() const { return fEdges.GetSize()-1; }

    Double_t *GetEdges() const { return (Double_t*)fEdges.GetArray(); }

    Bool_t IsLinear() const { return fType==kIsLinear; }
    Bool_t IsLogarithmic() const { return fType==kIsLogarithmic; }
    Bool_t IsCosinic() const { return fType==kIsCosinic; }
    Bool_t IsDefault() const { return fType==kIsDefault; }
    Bool_t IsUserArray() const { return fType==kIsUserArray; }

    void Apply(TH1 &) const;

    ClassDef(MBinning, 1) //Container to store the binning of a histogram
};

#endif

