#include "stdafx.h"
#include "ibm2bk.h"

void IBM2BK(CMyFile *pInFile, CMyFile *pOutFile)
{
	if (pInFile == NULL || pOutFile == NULL)
	{
		_tprintf(_T("Недостаточно памяти.\n"));
		return;
	}

//	BYTE Out;
	DWORD dwFlags = 0, t;
	int nCharsCount = 0;
	WCHAR Sym;

	if (!pInFile->Open(FALSE))
	{
		_tprintf(_T("Ошибка! %s не открывается.\n"), pInFile->getFileName().GetBuffer());
		return;
	}

	if (!pOutFile->Open(TRUE))
	{
		_tprintf(_T("Ошибка! %s не открывается.\n"), pOutFile->getFileName().GetBuffer());
		return;
	}

	while (!pInFile->isEOF())
	{
		Sym = pInFile->ReadChar();

		if (pInFile->isEOF())
		{
			break;
		}

		switch (Sym)
		{
			case 0: t = INPUT_SYMBOL_NULL;
				break;

			case 10: t = INPUT_SYMBOL_N;
				break;

			case 13: t = INPUT_SYMBOL_R;
				break;

			default:
			{
				dwFlags = 0;

				if (Sym == 9)
				{
					int nNextTabPos = (nCharsCount / pInFile->getTabWidth() + 1) * pInFile->getTabWidth();

					do
					{
						pOutFile->WriteChar(L' '); nCharsCount++;
					}
					while (nCharsCount < nNextTabPos);
				}
				else
				{
					pOutFile->WriteChar(Sym); nCharsCount++;
				}

				continue;
			}
		}

		if ((dwFlags & INPUT_SYMBOL_EOLN) == 0)
		{
			dwFlags |= t;
		}
		else
		{
			if ((dwFlags & t) == 0)
			{
				dwFlags = 0;
				continue;
			}
		}

		pOutFile->WriteChar(0);
		nCharsCount = 0;
	}
}

