#include <stdio.h>
#include "identifiers.h"
#include "qbtypes.h"
#include "write_endian.h"

void EndianSwap(unsigned int *x)
{
    *x = (*x>>24) | ((*x<<8) & 0x00FF0000) | ((*x>>8) & 0x0000FF00) | (*x<<24);
}

// Read for different endian
size_t freadBe(void *ptr, size_t size, size_t count, FILE *stream)
{
	size_t returnValue;
	returnValue = fread(ptr, size, count, stream);

	#if BIG_ENDIAN == 1
		unsigned int i;
		if (size == 4)
		{
			unsigned int *integer;
			integer = (unsigned int *) ptr;

			for (i = 0; i < count; i++)
				EndianSwap(&integer[i]);
		}
	#endif
	return returnValue;
}

size_t fwriteBe(const void *ptr, size_t size, size_t count, FILE *stream)
{
	unsigned int i;
	unsigned int *integer;

	if (size != 4) // Check
	{
		printf("Error: Reading more than 4 bytes on fwriteBe!");
	}

	#if BIG_ENDIAN == 1
		// Swap
		integer = (unsigned int *) ptr;

		for (i = 0; i < count; i++)
		{
			EndianSwap(&integer[i]);
		}
	#endif
	size_t retVal;
	retVal = fwrite(ptr, size, count, stream);

	#if BIG_ENDIAN == 1
		// Restore
		integer = (unsigned int *) ptr;

		for (i = 0; i < count; i++)
		{
			EndianSwap(&integer[i]);
		}
	#endif
	return retVal;
}