#include "file.h"
#include "m3derror.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <iostream>
#include <assert.h>

namespace M3D
{
	File::File ( const std::string & fname, bool is_creating )
	{
		_fdesc_ = -1;
		if ( is_creating ) creat ( fname.c_str() );
		else open ( fname.c_str() );
	}

	File::File ( const char * fname, bool is_creating )
	{
		_fdesc_ = -1;
		if ( is_creating ) creat ( fname );
		else open ( fname );
	}

	void File::close()
	{
		if ( _fdesc_>=0 ) ::close ( _fdesc_ );
	}
	File::~ File()
	{
		close();
	}
	void File::open ( const char * fname, int flags )
	{
		close();
		_fdesc_ = ::open ( fname, flags );
		if ( _fdesc_<0 ) THROW ( std::string(fname) + ": " + strerror ( errno ) );
		_opened_file_name_ = fname;
	}

	void File::creat ( const char * fname, int mode )
	{
		close();
		_fdesc_ = ::creat ( fname, mode );
		if ( _fdesc_<0 ) THROW ( std::string(fname) + ": " + strerror ( errno ) );
		_opened_file_name_ = fname;
	}

	File::File() : _fdesc_ ( -1 ), _opened_file_name_("")
	{
	}
	
	void M3D::File::write( const void * buf, size_t count )
	{
		assert( _fdesc_ >= 0); 
		if ( ::write ( _fdesc_ , buf, count ) != (ssize_t)count )THROW ( "Write to " + _opened_file_name_ + ": " + strerror ( errno ) );
	}
	void M3D::File::read( void * buf, size_t count )
	{
		assert( _fdesc_ >= 0); 
		if ( ::read ( _fdesc_ , buf, count ) != (ssize_t)count )THROW ( "Read from " + _opened_file_name_ + ": " + strerror ( errno ) );
	}
}


