#include "m3ds.h"
#include "file.h"
#include "m3derror.h"
#include <string.h>
#include <errno.h>

namespace M3D
{
M3DS::M3DS()
{}


M3DS::~M3DS()
{}

void M3DS::load( std::string fname )
{
	//Отобразим файл в память
	_mapped_file_.mmap ( fname.c_str() );
	char *mapped_file_pointer = _mapped_file_.get_pointer();
	
	_header_ = (M3DS_Header*)mapped_file_pointer;
	
	_data_.fragment_shader = mapped_file_pointer + _header_->fragment_shader_offset;
	_data_.vertex_shader= mapped_file_pointer + _header_->vertex_shader_offset;
}	

void M3DS::save( std::string fname )
{
	File fdesc ( fname.c_str(), true );
	//Скорректируем заголовок
	int base_offset = sizeof(M3DS_Header);
	_header_->vertex_shader_offset = base_offset;
	_header_->fragment_shader_offset = base_offset + _header_->vertex_shader_size;
	 
	//Сохраним заголовок
	if(write(fdesc, _header_, sizeof(M3DS_Header)) != sizeof(M3DS_Header))THROW ( strerror ( errno ) );
	//Сохраним данные
	if(write(fdesc, _data_.vertex_shader, _header_->vertex_shader_size) != _header_->vertex_shader_size)
		THROW ( strerror ( errno ) );
	if(write(fdesc, _data_.fragment_shader, _header_->fragment_shader_size) != _header_->fragment_shader_size)
		THROW ( strerror ( errno ) );

}

void M3DS::set_header( M3DS_Header * value )
{
	_header_ = value;
	memcpy(_header_->signature, M3DS_SIGNATURE, strlen(M3DS_SIGNATURE));
	_header_->version = M3DS_VER_MAGIC;
}

void M3DS::set_data( M3DS_Data * value )
{
	_data_ = *value;
}

}
