// myreader.cpp

#include <windows.h>
#include "myreader.h"

namespace mylib
{

CMyReader::CMyReader()
{
	m_bEofDetected = false;
	m_nFilled = 0;
	m_nRead = 0;
}

CMyReader::~CMyReader()
{
}

bool
CMyReader::Fill(unsigned char* buffer, size_t maxread, size_t& nread)
{
	nread = 0;
	return false;
}

bool
CMyReader::Read(unsigned char* buffer, size_t maxread, size_t& nread)
{
	bool result = false;

	if(m_nFilled >= (m_nRead + maxread))
	{
		for(size_t n = 0; n < maxread; n++)
			buffer[n] = m_bBuffer[m_nRead++];
		nread = maxread;
		result = true;
	}
	else
	{
		size_t k = 0;
		for(size_t n = m_nRead; n < m_nFilled; n++)
			buffer[k++] = m_bBuffer[n];
		m_nRead = m_nFilled = 0;
		if(m_bEofDetected)
		{
			nread = k;
			return true;
		}
		m_nRead = m_nFilled = 0;
		result = Fill(&buffer[k], (maxread - k), nread);
		if(nread == 0)
			m_bEofDetected = true;
		nread = nread + k;
	}
	return result;
}

int
CMyReader::GetOctet()
{
	if(m_nRead >= m_nFilled)
	{
		m_nFilled = m_nRead = 0;
		if(m_bEofDetected)
			return MY_EOF;
		if(!Fill(m_bBuffer, MY_BUFSIZE, m_nFilled))
			return MY_EOF;
		if(m_nFilled == 0)
		{
			m_bEofDetected = true;
			return MY_EOF;
		}
	}
	int c = (int)m_bBuffer[m_nRead++] & 255;
	return c;
} 

const unsigned char*
CMyReader::Buffer() const
{
	return m_bBuffer;
}

size_t
CMyReader::Filled() const
{
	return m_nFilled;
}

}	//namespace mylib
