LIB3MFMETHODIMP CCOMModelTexture2D::WriteToBuffer(_Out_ BYTE * pBuffer, _In_ ULONG64 cbBufferSize)
	{
		try {
			if (pBuffer == nullptr)
				throw CNMRException(NMR_ERROR_INVALIDPOINTER);

			CModelTexture2DResource * pTextureResource = getTexture2D();
			__NMRASSERT(pTextureResource);

			PImportStream pTextureStream = pTextureResource->getTextureStream();

			if (pTextureStream.get() != nullptr) {
				nfUint64 cbStreamSize = pTextureStream->retrieveSize();
				if (cbStreamSize > cbBufferSize)
					throw CNMRException(NMR_ERROR_INSUFFICIENTBUFFERSIZE);
					
				pTextureStream->seekPosition(0, true);
				pTextureStream->readBuffer(pBuffer, cbStreamSize, true);
			}
			else {
				throw CNMRException(NMR_ERROR_NOTEXTURESTREAM);
			}

			return handleSuccess();
		}
		catch (CNMRException & Exception) {
			return handleNMRException(&Exception);
		}
		catch (...) {
			return handleGenericException();
		}

	}
	LIB3MFMETHODIMP CCOMModelTexture2D::WriteToStream(_In_ IStream * pStream)
	{
		try {
			if (pStream == nullptr)
				throw CNMRException(NMR_ERROR_INVALIDPOINTER);

			CModelTexture2DResource * pTextureResource = getTexture2D();
			__NMRASSERT(pTextureResource);

			PImportStream pTextureStream = pTextureResource->getTextureStream();

			if (pTextureStream.get() != nullptr) {
				nfUint64 cbStreamSize = pTextureStream->retrieveSize();

				pTextureStream->seekPosition(0, true);
				std::array<nfByte, NMR_IMPORTSTREAM_COPYBUFFERSIZE> pBuffer;
				
				nfUint64 cbBytesLeft = cbStreamSize;
				while (cbBytesLeft > 0) {
					nfUint64 cbLength = cbBytesLeft;
					if (cbLength > NMR_IMPORTSTREAM_COPYBUFFERSIZE)
						cbLength = NMR_IMPORTSTREAM_COPYBUFFERSIZE;

					ULONG cbWrittenBytes = 0;
					pTextureStream->readBuffer(&pBuffer[0], cbLength, true);
					HRESULT hResult = pStream->Write(&pBuffer[0], (nfUint32) cbLength, &cbWrittenBytes);
					if (hResult != S_OK)
						throw CNMRException_Windows(NMR_ERROR_COULDNOTWRITESTREAM, hResult);
					
					if (cbWrittenBytes != cbLength)
						throw CNMRException(NMR_ERROR_COULDNOTWRITEFULLDATA);
					cbBytesLeft -= cbLength;
				}

			}
			else {
				throw CNMRException(NMR_ERROR_NOTEXTURESTREAM);
			}

			return handleSuccess();
		}
		catch (CNMRException & Exception) {
			return handleNMRException(&Exception);
		}
		catch (...) {
			return handleGenericException();
		}

	}