#ifndef MARS_MZlib
#define MARS_MZlib

#ifndef ROOT_TObject
#include <TObject.h>
#endif

#ifdef __CINT__
typedef void *gzFile;
#else
#include <zlib.h>
#endif

#include <iostream>  // base classes for MLog
#include <fstream>

class MZlib : public std::streambuf, virtual public std::istream, public TObject
{
private:
    static const int fgBufferSize = 47+256; // size of data buff totals 512 bytes under g++ for igzstream at the end.

    gzFile fFile;                 // file handle for compressed file
    char   fBuffer[fgBufferSize]; // data buffer

    int underflow();
    int fill_buffer(int putback=0);

public:
    MZlib() : istream(this), fFile(0)
    {
        setg(fBuffer+4, fBuffer+4, fBuffer+4);
    }
    MZlib(const char *name) : istream(this), fFile(0)
    {
        setg(fBuffer+4, fBuffer+4, fBuffer+4);
        open(name);
    }
    ~MZlib() { MZlib::close(); }

    int is_open() { return fFile!=0; }

    void open(const char* name);
    void close();

# if (__GNUC__>2)
    std::streambuf::pos_type seekoff(std::streambuf::off_type, std::ios_base::seekdir,
                                     std::ios_base::openmode = std::ios_base::in);
    std::streambuf::pos_type seekpos(std::streambuf::pos_type,
                                     std::ios_base::openmode = std::ios_base::in);
# else
    std::streampos seekoff(std::streamoff, int, int = std::ios::in);
    std::streampos seekpos(std::streampos, int = std::ios::in);
# endif

    ClassDef(MZlib, 0) // A C++ wrapper to istream zlib files
};

#endif
