#include <unistd.h>
#include <streambuf>
#include <ios>

#include <iostream>

using std::cerr;

class fdstreambuf: public std::streambuf
{
    public:
        fdstreambuf(int fd, std::ios::openmode mode = 
                                std::ios::in | std::ios::out)
        :
            fd(fd),
            input_char(EOF),
            mode(mode)
        {
            std::streambuf::_M_mode = mode;
//            char
//                dummy;
//            if (mode & std::ios::in)
//                setg(&dummy, &dummy, &dummy);



//            if (mode & std::ios::out)
//                setp(&dummy, &dummy);
        }


    int uflow()                 // consumes the character
    {
std::cerr << "uflow\n";
        if (input_char != EOF)
        {
            int
                next = input_char;
            input_char = EOF;
            return next;
        }

        return underflow();
    }

    int underflow()             // inspects the character
    {
std::cerr << "underflow, in_avail() = " << in_avail() << "\n";
        char
            c;

        if (read(fd, &c, 1))
        {
//            std::cerr << "Got " << c;
            input_char = c;
            std::cerr << ", input_char is " << input_char << 
                                    " (" << (char)input_char << ")\n";
            return input_char;
        }

//std::cerr << "EOF underflow\n";
        return input_char = EOF;
    }

    int overflow(int c)
    {
        if (c != EOF)
        {
            if (write(fd, &c, 1) != 1)
                return EOF;
        }
        return c;
    }

    private:
        std::ios::openmode
            mode;
        int
            fd,
            input_char;
};
