/*
    libmaus2
    Copyright (C) 2020 German Tischler-Höhle

    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/>.
*/
#if ! defined(LIBMAUS2_GAMMA_GAMMAENGENERICDECODER_HPP)
#define LIBMAUS2_GAMMA_GAMMAENGENERICDECODER_HPP

#include <libmaus2/gamma/GammaGenericClz.hpp>
#include <libmaus2/gamma/GammaGenericBase.hpp>

namespace libmaus2
{
	namespace gamma
	{
		template<typename _stream_type, typename _stream_data_type, typename _value_type>
		struct GammaGenericDecoder : public GammaGenericBase<sizeof(_stream_data_type)>
		{
			typedef _stream_type stream_type;
			typedef _stream_data_type stream_data_type;
			typedef _value_type value_type;
			typedef GammaGenericBase<sizeof(stream_data_type)> base_type;
			typedef GammaGenericDecoder<stream_type,stream_data_type,value_type> this_type;
			typedef std::unique_ptr<this_type> unique_ptr_type;

			static unsigned int const w = CHAR_BIT * sizeof(stream_data_type);

			stream_type & stream;
			stream_data_type v;
			unsigned int bav;

			GammaGenericDecoder(stream_type & rstream)
			: stream(rstream), v(0), bav(0)
			{

			}

			void fill()
			{
				v = stream.get();
				bav = w;
			}

			void flush()
			{
				if ( bav != w )
				{
					bav = 0;
					v = 0;
				}
			}

			value_type decodeWord(unsigned int codelen)
			{
				value_type r = 0;

				while ( codelen )
				{
					if ( ! bav )
						fill();

					unsigned int const use    = std::min(bav,codelen);
					unsigned int const notuse = w-use;

					r <<= use;
					r |= (v >> notuse);
					v <<= use;
					codelen -= use;
					bav -= use;
				}

				return r;
			}

			std::string wordToBits() const
			{
				unsigned int mask = stream_data_type(1) << (w - 1);
				std::ostringstream ostr;
				while ( mask )
				{
					ostr.put( (v&mask) ? '1' : '0');
					mask >>= 1;
				}
				return ostr.str();
			}

			value_type decode()
			{
				// decode length of code
				unsigned int codelen = 1;

				while ( true )
				{
					if ( ! bav )
						fill();

					if ( v == 0 )
					{
						codelen += bav;
						bav = 0;
					}
					else
					{
						// count number of leading zeros in v
						unsigned int const lz =
							GammaGenericClz<stream_data_type>::clz(v,static_cast<base_type const &>(*this));

						v <<= lz;
						codelen += lz;
						bav -= lz;
						break;
					}
				}

				return decodeWord(codelen)-1;
			}
		};
	}
}
#endif
