#ifndef _INCLUDED_OFILTERSTREAMBUF_
#define _INCLUDED_OFILTERSTREAMBUF_

#include <streambuf>
#include <fstream>

namespace FBB
{

class OFilterStreambuf: public std::streambuf
{
    typedef std::ios::openmode openmode;
    std::ofstream d_dest;

    std::ostream *d_out;

    public:
        OFilterStreambuf();                                 // 1.f
        OFilterStreambuf(char const *fname,                 // 2.f
                         openmode mode = std::ios::out);
        OFilterStreambuf(std::ostream &out);                // 3.f
        OFilterStreambuf(std::string const &fname, 
                         openmode mode = std::ios::out);
        ~OFilterStreambuf() override;

        void open(char const *fname, openmode mode = std::ios::out);
        void open(std::string const &fname, openmode mode = std::ios::out);
        void open(std::ostream &out);                       // .f

        void close();                                       // .f

    protected:
        std::ostream &out() const;                          // .f
};

inline OFilterStreambuf::OFilterStreambuf()
:
    d_out(&d_dest)
{}
inline OFilterStreambuf::OFilterStreambuf(char const *fname, openmode mode)
:
    d_dest(fname, mode),
    d_out(&d_dest)
{}
inline OFilterStreambuf::OFilterStreambuf(std::ostream &out)
:
    d_out(&out)
{}

inline void OFilterStreambuf::close()
{
    sync();
    d_dest.close();
}
inline void OFilterStreambuf::open(std::ostream &out)
{
    close();
    d_out = &out;
}
inline std::ostream &OFilterStreambuf::out() const
{
    return *d_out;
}

} // FBB
        
#endif
