// implementation file: FileIO.cpp
// description:         Functions for reading from and writing to files.
// author:              Karlheinz Hug
// creation date:       2012-07-05
// last update:         2012-10-03

#include <cassert>
#include <fstream>

#include "FileIO.hpp"

	int FileIO::a_result;

	void FileIO::read_from_file_to_buffer (const std::string & filename, std::vector<char> & buffer)
	{
		assert(filename.size() > 0); // precondition

		std::ifstream stream(filename.c_str(), std::ifstream::binary);
		if (stream.fail())
		{
			a_result = failed_open;
			return;
		}
		stream.seekg(0, std::ios::end);
		assert(!stream.fail());

		buffer.resize(stream.tellg());
		stream.seekg(0, std::ios::beg);
		assert(!stream.fail());

		{// unsafe!
			stream.read(&buffer[0], buffer.size());   // yes, it's dull, but what can a poor boy do...
		}
		assert(!stream.fail());
		a_result = done;

		stream.close();
		assert(!stream.fail());
	};

	void FileIO::write_from_buffer_to_file (const std::vector<char> & buffer, const std::string & filename)
	{
		assert(filename.size() > 0); // precondition

		std::ofstream stream(filename.c_str(), std::ofstream::binary);
		if (stream.fail())
		{
			a_result = failed_open;
			return;
		}
		{// unsafe!
			stream.write(&buffer[0], buffer.size());   // yes, it's dull, but what can a poor boy do...
		}
		if (stream.bad())
		{
			a_result = failed_write;
		}
		else
		{
			a_result = done;
		}
		stream.close();
		assert(!stream.fail());
	};
