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

#include "stdafx.h"
#include "p_check.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

void _CheckFile(CString strInputFile, CString strOutputFile);

/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	// initialize MFC and print and error on failure
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: change error code to suit your needs
		cerr << _T("Fatal Error: MFC initialization failed") << endl;
		nRetCode = 1;
	}
	else
	{
		// TODO: code your application's behavior here.
		if (argc != 3)
		{
			CString strHello;
			strHello.LoadString(IDS_HELLO);
			cout << (LPCTSTR)strHello << endl;
		}
		else
		{
			_CheckFile(argv[1], argv[2]);
		}
	}

	return nRetCode;
}


void _CheckFile(CString strInputFile, CString strOutputFile)
{
	CStdioFile in, out;
	CString strIn, strOut;

	printf("check %s, output %s\n", strInputFile, strOutputFile);

	if (!in.Open(strInputFile, CFile::modeRead|CFile::typeText))
	{
		printf("Can not open source check file\n");
		exit(-1);
	}

	if (!out.Open(strOutputFile, CFile::modeCreate|CFile::modeWrite|CFile::typeText))
	{
		printf("Can not create dest file\n");
		exit(-2);
	}

	out.WriteString("Check result:\n\n");
	while (in.ReadString(strIn))
	{
		if (strIn.Left(3) == "***")
		{
			CString strErr1, strErr2;
			strOut.Format("%s\n", strIn);
			in.ReadString(strErr1);
			if (!strErr1.IsEmpty())
			{
				strOut += strErr1 + "\n";
				in.ReadString(strErr2);
				if (!strErr2.IsEmpty())
				{
					strOut += strErr2 + "\n";
				}
			}
			out.WriteString(strOut);
		}
		else if (strIn.Left(13) == "Program Size:")
		{
			strOut.Format("%s\n\n", strIn);
			out.WriteString(strOut);
		}
		else if (strIn.Find("BL51 @linkfile.txt", 0) != -1)
		{
			strOut.Format("%s\n", strIn);
			out.WriteString(strOut);
		}
	}
	out.WriteString("\nCheck end\n");

	in.Close();
	out.Close();
}

