/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "TeeBuffer.h"

#include <cstdio>

TeeBuffer::TeeBuffer(std::ostream& one, std::ostream& two) :
    std::streambuf(),
    one_(one),
    two_(two)
{
    setp(buffer_, buffer_ + sizeof(buffer_));
    setg(nullptr, nullptr, nullptr);
}

TeeBuffer::~TeeBuffer()
{
    dumpBuffer();
}

int TeeBuffer::overflow(int c)
{
    if (c == EOF) {
        sync();
        return 0;
    }

    dumpBuffer();
    sputc(c);
    return 0;
}

int TeeBuffer::sync()
{
    dumpBuffer();
    return 0;
}

void TeeBuffer::dumpBuffer()
{
    for (const char* p = pbase(); p != epptr(); ++p) {
        one_ << *p;
        two_ << *p;
        if (*p == '\n')
            break;
    }

    setp(pbase(), epptr());

    one_ << std::flush;
    two_ << std::flush;
}
