/*
  File name: fileio.h
  Copyright: (C) 2009 Tomasz Kazmierczak

  Creation date: 10.06.2009
  Last modification date: 12.06.2009

  This file is part of Cytadela

 *   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 3 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, see <http://www.gnu.org/licenses/>.  *

*/

#ifndef _FILEIO_H_
#define _FILEIO_H_

#include <stdio.h>
#include <stdint.h>

union Float32 {
	float f;
	uint32_t i;
};

union Float64 {
	double d;
	uint64_t i;
};

template <typename TYPE>
bool fioWrite(const TYPE &in, FILE *file) {
	for(size_t i = 0, shift = 0; i < sizeof(TYPE); i++, shift += 8) {
		TYPE mask = ((TYPE)0xFF) << shift;
		uint8_t byte = (in & mask) >> shift;
		if(fwrite(&byte, 1, 1, file) != 1)
			return false;
	}
	return true;
}

template <typename TYPE>
bool fioRead(TYPE &out, FILE *file) {
	out = 0;
	for(size_t i = 0, shift = 0; i < sizeof(TYPE); i++, shift += 8) {
		uint8_t byte = 0;
		if(fread(&byte, 1, 1, file) != 1)
			return false;
		out |= ((TYPE)byte) << shift;
	}
	return true;
}

template <>
bool fioWrite<float>(const float &in, FILE *file);

template <>
bool fioWrite<double>(const double &in, FILE *file);

template <>
bool fioRead<float>(float &out, FILE *file);

template <>
bool fioRead<double>(double &out, FILE *file);

#endif //_FILEIO_H_
