#ifndef CWRAPPERMEMORYREADFILE_H_INCLUDED
#define CWRAPPERMEMORYREADFILE_H_INCLUDED


namespace irr
{

namespace io
{

	/*!
		Class for reading from memory.
	*/
	class CWrapperMemoryReadFile : public IReadFile
	{
	public:

		CWrapperMemoryReadFile(void* memory, s32 len, const c8* fileName, bool deleteMemoryWhenDropped = false)
		: Buffer(memory), Len(len), Pos(0), deleteMemoryWhenDropped(deleteMemoryWhenDropped)
        {
#ifdef _DEBUG
            setDebugName("CWrapperMemoryReadFile");
#endif
            Filename = fileName;
        }

		virtual ~CWrapperMemoryReadFile()
        {
            if (deleteMemoryWhenDropped)
                delete [] (c8*)Buffer;
        }

		//! returns how much was read
		s32 read(void* buffer, u32 sizeToRead)
		
		{
            s32 amount = sizeToRead;
            if (Pos + amount > Len)
                amount -= Pos + amount - Len;

            if (amount < 0)
                amount = 0;

            c8* p = (c8*)Buffer;
            memcpy(buffer, p + Pos, amount);

            Pos += static_cast<u32> ( amount );

            return amount;
        }


		//! changes position in file, returns true if successful
		//! if relativeMovement==true, the pos is changed relative to current pos,
		//! otherwise from begin of file
		bool seek(long finalPos, bool relativeMovement = false)
        {
            if (relativeMovement)
            {
                if (Pos + finalPos > Len)
                    return false;

                Pos += finalPos;
            }
            else
            {
                if ( (unsigned) finalPos > Len)
                    return false;

                Pos = finalPos;
            }

            return true;
        }

		//! returns size of file
		long getSize() const
        {
            return Len;
        }


		//! returns where in the file we are.
		long getPos() const
        {
            return Pos;
        }

		//! returns name of file
		const c8* getFileName() const
        {
            return Filename.c_str();
        }

	private:

		core::stringc Filename;
		void *Buffer;
		u32 Len;
		u32 Pos;
		bool deleteMemoryWhenDropped;
	};

} // end namespace io
} // end namespace irr

#endif // CWRAPPERMEMORYREADFILE_H_INCLUDED
