#include "stdafx.h"
#include "ogFile.h"

CFile::CFile (TCHAR * name) {
	file = map = INVALID_HANDLE_VALUE;
	ptr = NULL;
	length = 0;

	reopenFile (name);
}

CFile::~CFile () {
	closeFile ();		
}

void CFile::closeFile () {
	unmapFile ();

	if (file != INVALID_HANDLE_VALUE) {
		CloseHandle (file);
		file = INVALID_HANDLE_VALUE;
	}
	length = 0;
}

// close file. open another file, if non-NULL parameter specified
bool CFile::reopenFile(TCHAR *name) {
	closeFile ();
	if (name) 
		file = CreateFile (name, GENERIC_READ, FILE_SHARE_WRITE|FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	
	if (file != INVALID_HANDLE_VALUE) // get length, if file opened successfully
		length = GetFileSize (file, NULL);
	return file != INVALID_HANDLE_VALUE;
}

BYTE * CFile::mapFile () {
	if (ptr)	// file already mapped. do nothing
		return ptr;		

	map = CreateFileMapping (file, NULL, PAGE_READONLY, 0, length, NULL);
	if (map) 
		ptr = (BYTE *)MapViewOfFile (map, FILE_MAP_READ, 0, 0, length);

	return ptr;
}

void CFile::unmapFile() {
	if (ptr) {
		UnmapViewOfFile (ptr);
		ptr = NULL;
	}
	if (map != INVALID_HANDLE_VALUE) {
		CloseHandle (map);
		map = INVALID_HANDLE_VALUE;
	}
}