/**
    bambam
    Copyright (C) 2019 German Tischler

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**/
#include <biobambam2/RunEOFFilter.hpp>

namespace biobambam2
{
	uint64_t runEOFFilter(std::ostream & out, std::istream & in, std::ostream & errstr, int const verbose)
	{
		uint64_t filteredinline = 0;
		uint64_t p = 0;
		libmaus2::lz::BgzfInflateBase BIB;

		while ( in.peek() != std::istream::traits_type::eof() )
		{
			libmaus2::lz::BgzfInflateBase::BaseBlockInfo BBI = BIB.readBlock(in);
			if ( BBI.uncompdatasize )
				BIB.writeBlock(out,BBI);
			else
			{
				bool const eof = (in.peek() == std::istream::traits_type::eof());
				if ( verbose )
					errstr << "[V] filtering out empty BGZF block at file position " << p << " EOF " << eof << std::endl;
				if ( !eof )
					filteredinline += 1;
			}

			p += BBI.compdatasize;
		}

		return filteredinline;
	}

	std::string runEOFFilter(std::string const & s)
	{
		std::istringstream istr(s);
		std::ostringstream ostr;
		runEOFFilter(ostr,istr,std::cerr,false);
		return ostr.str();
	}
}
