#include "common.h"
#include <commdlg.h>
#include <stdlib.h>
#include <stdio.h>

#define BUFLENGTH_LINE			800

BOOL OpenTextFile(LPTSTR *ppszContent, LPTSTR szFileName, HWND hwndOwner)
{
	if(ppszContent == NULL)
		return FALSE;
	*ppszContent = NULL;
	TCHAR szFile[MAX_PATH];
	memset(szFile, 0, MAX_PATH * sizeof(TCHAR));
	TCHAR szFileTitle[MAX_PATH];
	OPENFILENAME ofn;
	memset(&ofn, 0, sizeof(OPENFILENAME));
	ofn.lStructSize = sizeof(OPENFILENAME);
	ofn.hwndOwner = hwndOwner;
	ofn.lpstrFilter = _T("Text Files (*.txt)|*.txt|All Files (*.*)|*.*||");
	ofn.lpstrFile = szFile;
	ofn.nMaxFile = MAX_PATH;
	ofn.lpstrFileTitle = szFileTitle;
	ofn.nMaxFileTitle = MAX_PATH;
	ofn.lpstrTitle = _T("Open Source File...");
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_EXPLORER;
	if(GetOpenFileName(&ofn))
	{
		HCURSOR hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));
		_tcscpy(szFileName, ofn.lpstrFileTitle);
		FILE *pFile = _tfopen(ofn.lpstrFile, _T("rt"));
		fseek(pFile, 0, SEEK_END);
		int nFileLength = ftell(pFile);
		rewind(pFile);
		*ppszContent = (TCHAR*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (nFileLength + 1) * sizeof(TCHAR));
		if(*ppszContent == NULL)
		{
			fclose(pFile);
			return FALSE;
		}
		TCHAR szLine[BUFLENGTH_LINE];
		int iStrLength = 0;
		while(_fgetts(szLine, BUFLENGTH_LINE - 1, pFile))
		{
			_tcscat(*ppszContent + iStrLength, szLine);
			iStrLength += _tcslen(szLine);
		}
		if(!feof(pFile))
		{
			HeapFree(GetProcessHeap, 0, *ppszContent);
			fclose(pFile);
			return FALSE;
		}
		fclose(pFile);
		SetCursor(hCursor);
		return TRUE;
	}
	return FALSE;
}