// OcrBackEndTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include "OcrInterface.h"

void PrintOutput(const OCR_CHAR* output, int nCount, const char *sOutDir) {
	int nRight = 0;
	FILE* fp = fopen(sOutDir,"wb");
	for (int i = 0; i < nCount; ++i) {
		const OCR_CHAR* ch = output + i;
		if(ch->right < nRight) {
			fprintf(fp, "\r\n");
		}
		else if(ch->blanks > 0) {
			fprintf(fp, " ");
		}
		fprintf(fp, "%c", ch->char_code);
		nRight = ch->right;
	}
	fclose(fp);
}

CString GetInstallDir(LPCTSTR subDir = NULL){
	TCHAR installPath[MAX_PATH];
	CString installDir;
	
	// Get the directory where the module is running. This should be the installation directory.
	::GetModuleFileName(GetModuleHandle(NULL), installPath, MAX_PATH);
	
	// Remove module name to leave just the path.
	int curPos = lstrlen(installPath);
	while (curPos)
	{
		if (installPath[curPos] == '\\')
			break;
		
		--curPos;
	}
	
	installPath[curPos] = 0;
	installDir = installPath;
	
	if (subDir != NULL)
	{
		installDir += _T("\\");
		installDir += subDir;
	}
	
	return installDir;
}


PUCHAR Read1BppBMP(const char* sBmpFileName, int &nWidth, int &nHeight);
void FlipImage(UCHAR *pImg, int nWidthStep, int nHeight);

int _tmain(int argc, _TCHAR* argv[])
{
	CString sInstallDir = GetInstallDir();
	OcrInit(sInstallDir  + "\\..\\Data\\", "eng");
	int nWidth, nHeight;
	UCHAR *pImg = Read1BppBMP(sInstallDir  + "\\..\\sample1.bmp", nWidth, nHeight);
	FlipImage(pImg, nWidth / 8, nHeight);
	OCR_CHAR *pResult = NULL;
	int nChars = OcrRecognize(pImg, nWidth, nHeight, &pResult);
	delete [] pImg;
	PrintOutput(pResult, nChars, sInstallDir + "\\..\\sample1.txt");
	free(pResult);

	pImg = Read1BppBMP(sInstallDir+ "\\..\\sample2.bmp", nWidth, nHeight);
	FlipImage(pImg, nWidth / 8, nHeight);
	nChars = OcrRecognize(pImg, nWidth, nHeight, &pResult);
	delete [] pImg;
	PrintOutput(pResult, nChars, sInstallDir + "\\..\\sample2.txt");
	free(pResult);

	OcrTerm();
	return 0;
}

