/*
 * This code is released under the Microsoft Public License (MS-PL). See license.txt, below.
 */
#include "stdafx.h"

int CompareUnsignedLong(
	const void* a, 
	const void* b
	)
{
	return (int)(*(unsigned long*)a - *(unsigned long*)b);
}

int CompareFile(
	_TCHAR* path, 
	unsigned long idx, 
	_TCHAR* file_ext, 
	unsigned long* isOk, 
	FILE* logFp
	)
{
	for(unsigned long i = 0; i < idx; i++) {
		if(isOk[i] == FALSE) {
			continue;
		}
		_TCHAR szFilenameWithoutPath1[_MAX_PATH];
		memset(szFilenameWithoutPath1, 0, sizeof(szFilenameWithoutPath1));
		FILE* FpSrc = CreateOrOpenFile(path, NULL, 
			szFilenameWithoutPath1, file_ext, _T("rb"), i, idx);
		if(!FpSrc) {
			_tprintf(_T("No file or already opened [F:%s][L:%d][Idx:%d]\n"), 
				_T(__FUNCTION__), __LINE__, i + 1);
			continue;
		}
		unsigned long SizeSrc = getFilesize(FpSrc);
		char* bufSrc = (char*)malloc(SizeSrc);
		if(!bufSrc) {
			FcloseAndNull(FpSrc);
			continue;
		}

		for(unsigned long k = i + 1; k < idx; k++) {
			if(isOk[k] == FALSE) {
				continue;
			}
			_TCHAR szFilenameWithoutPath2[_MAX_PATH];
			memset(szFilenameWithoutPath2, 0, sizeof(szFilenameWithoutPath2));
			FILE* FpDst = CreateOrOpenFile(path, NULL, 
				szFilenameWithoutPath2, file_ext, _T("rb"), k, idx);
			if(!FpDst) {
				_tprintf(_T("No file or already opened [F:%s][L:%d][Idx:%d]\n"), 
					_T(__FUNCTION__), __LINE__, k + 1);
				continue;
			}
			unsigned long SizeDst = getFilesize(FpDst);
			if(SizeSrc == SizeDst) {
				char* bufDst = (char*)malloc(SizeDst);
				if(!bufDst) {
					FcloseAndNull(FpDst);
					continue;
				}
				if(k == i + 1) {
					fread(bufSrc, SizeSrc, sizeof(char), FpSrc);
				}
				fread(bufDst, SizeDst, sizeof(char), FpDst);
				if(memcmp(bufSrc, bufDst, SizeDst) == 0) {
					_TCHAR logbuf[128];
					memset(logbuf, 0, sizeof(logbuf));
					_sntprintf(logbuf, sizeof(logbuf) / sizeof(_TCHAR), 
						_T("[%s] & [%s]\r\n"), szFilenameWithoutPath1, szFilenameWithoutPath2);
					logbuf[127] = 0;
					fwrite(logbuf, sizeof(_TCHAR), _tcslen(logbuf), logFp);
				}
				FreeAndNull(bufDst);
			}
			FcloseAndNull(FpDst);
			_tprintf(_T("\rCompare %s %d and %d"), file_ext, i + 1, k + 1);
		}
		FreeAndNull(bufSrc);
		FcloseAndNull(FpSrc);
	}
	if(idx > 1) {
		_tprintf(_T("\n"));
	}
	return 0;
}
