
#ifndef __MMAPPER_H__
#define __MMAPPER_H__

#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>
#include <string>

class MMapper {
	
public:
	MMapper (std::string path, std::string permissions, void** dest, unsigned long *len);
	~MMapper ();

private:
	void *mDataPtr;
	unsigned long mLength;
};

inline MMapper::MMapper (std::string path, std::string permissions, void** dest, 
								unsigned long *len)
/*
	Inputs:	path to file, permissions (ie. "rb"), data handle, pointer
	 			to file length
	Outputs:	dest and length
*/
{
	FILE* f = fopen (path.c_str(), permissions.c_str());
	if (f) {
		mLength = *len = lseek (fileno(f), 0, SEEK_END);
		mDataPtr = *dest = mmap(0, mLength, PROT_READ, MAP_SHARED, fileno(f), 0);
		fclose(f);

		if(long(mDataPtr) == -1)
		{
			perror("MMapper");
			mLength = *len = 0;
			mDataPtr = *dest = 0;
		}
	}
	else {
		mLength = *len = 0;
		mDataPtr = *dest = 0;
	}
}


inline MMapper::~MMapper ()
{
	if (mDataPtr) munmap ((char*)mDataPtr, mLength);
}

#endif
