#ifndef _UTILITY_H
#define _UTILITY_H 0x01


#include <algorithm> //required for std::swap


#define ByteSwap(x) __ByteSwap((unsigned char*)&x, sizeof(x))

static void __ByteSwap(unsigned char* b, int n)
{
   register int i = 0;
   register int j = n-1;
   while (i<j)
   {
      std::swap(b[i], b[j]);
      i++, j--;
   }
}


#define ntoh(dest, source) __ntoh((unsigned char*)&dest, (unsigned char*)&source, sizeof(dest))
static int __ntoh(unsigned char* dest, unsigned char* source, int size) {
	// copy into the destination
	memcpy(dest, source, size);
	// switch the bytes
	__ByteSwap(dest, size);
	return size;
}

#define getshort(source, pos) __getshort((unsigned char*)&(source[pos]), pos)
static int __getshort(unsigned char* source, int& pos) {
	short result;
	pos += __ntoh((unsigned char*)&result, source, sizeof(result));
	return result;
}

#define getint(source, pos) __getint((unsigned char*)&(source[pos]), pos)
static int __getint(unsigned char* source, int& pos) {
	int result;
	pos += __ntoh((unsigned char*)&result, source, sizeof(result));
	return result;
}

#define getlong(source, pos) __getlong((unsigned char*)&(source[pos]), pos)
static long long __getlong(unsigned char* source, int& pos) {
	long long result;
	pos += __ntoh((unsigned char*)&result, source, sizeof(result));
	return result;
}

#define getdouble(source, pos) __getdouble((unsigned char*)&(source[pos]), pos)
static double __getdouble(unsigned char* source, int& pos) {
	double result;
	pos += __ntoh((unsigned char*)&result, source, sizeof(result));
	return result;
}


#define hton(dest, source) __hton((unsigned char*)&dest, (unsigned char*)&source, sizeof(source))
static int __hton(unsigned char* dest, unsigned char* source, int size) {
	// copy into the destination
	memcpy(dest, source, size);
	// switch the bytes
	__ByteSwap(dest, size);
	return size;
}

#define setshort(dest, pos, source) __setshort((unsigned char*)&(dest[pos]), pos, (unsigned char*)&source, sizeof(source))
static void __setshort(unsigned char* dest, int& pos, unsigned char* source, int size) {
	pos += __hton(dest, source, 2);
}

#define setint(dest, pos, source) __setint((unsigned char*)&(dest[pos]), pos, (unsigned char*)&source, sizeof(source))
static void __setint(unsigned char* dest, int& pos, unsigned char* source, int size) {
	pos += __hton(dest, source, 4);
}

#define setlong(dest, pos, source) __setlong((unsigned char*)&(dest[pos]), pos, (unsigned char*)&source, sizeof(source))
static void __setlong(unsigned char* dest, int& pos, unsigned char* source, int size) {
	pos += __hton(dest, source, 8);
}


#include <sstream>
#include <string>

template<typename T>
char* tosstring(const T& val)
{
	std::ostringstream os;
	os << val;
	string str = os.str();

	char* ret = new char[str.length() + 1];
	strncpy(ret, str.c_str(), str.length());
	ret[str.length()] = '\0';

	return ret;
}


#endif /* UTILITY_H */