/*  DS
 *  Copyright (C) Joakim Kolsjö and Anders Asplund 2005
 *	This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 
 */ 
 
#include "datareader.h"

using namespace std;

namespace DS
{
	MemFile::MemFile(char* pData, int length)
	{
		m_pos = 0;
		m_length = length;
		m_pData = pData;
	}
	
	MemFile::~MemFile()
	{
		delete m_pData;
	}
	
	char* MemFile::GetData()
	{
		return m_pData;
	}
	
	int MemFile::Read(void* pBuffer, int size)
	{
		if(m_pos + size >= m_length)
    		size = m_length - m_pos;
  		
		memcpy(pBuffer, (char*)(m_pData + m_pos), size);
  		m_pos += size;
  		return size;
	}
	
	void MemFile::Seek(int pos, signed char mode)
	{
		if(mode == SEEK_SET)
			m_pos = pos;
		else if(mode == SEEK_CUR)
			m_pos += pos;
		else if(mode == SEEK_END)
			m_pos = m_length + pos;	
		
		if(m_pos > m_length)
			m_pos = m_length;
	}
	
	int MemFile::Tell()
	{
		return m_pos;
	}
		
	int MemFile::GetLength()
	{
		return m_length;
	}

	DataReader::~DataReader()
	{
		std::map <std::string, MemFile*>::iterator miter = m_MemFiles.begin();
		while(miter != m_MemFiles.end())
		{
			delete miter->second;
			++miter;
		}	
		
		m_MemFiles.clear();
	}
	
	MemFile* DataReader::GetFile(const char* pFile)
	{
		if(!m_MemFiles[pFile])
			Read(pFile);
		
		return m_MemFiles[pFile];
	}
}
