#include <string.h>

#if defined(__MINGW32__)
	#include <winsock2.h>
#else
	#include <sys/types.h>
#endif

#include "tpl2.h"

void tpl_upkbyte(void *message, void *p, int nitems)
{
	int ni1, ni2;

	if ( p == NULL ) return;

	if ( message == NULL )
	{
		ni1 = 0;
		ni2 = nitems;
	}
	else
	{
		if ( ((tpl_message *)message)->pos + nitems <= ((tpl_message *)message)->length )
		{
			ni1 = nitems;
			ni2 = 0;
		}
		else
		{
			ni1 = ((tpl_message *)message)->length - ((tpl_message *)message)->pos;
			ni2 = nitems - ni1;
		}
	}

	if ( ni1 > 0 )
	{
		memcpy( p, (void *) ((u_long) (((tpl_message *)message)->addr) + ((tpl_message *)message)->pos) , ni1);
	}

	if ( ni2 > 0 )
	{
		memset( (void *) ((u_long) (p) + ni1), 0, ni2);
	}
}

void tpl_upkchar(void *message, char *p, int nitems)
{
	tpl_upkbyte(message, p, nitems * sizeof(*p));
}

void tpl_upkdouble(void *message, double *p, int nitems)
{
	tpl_upkbyte(message, p, nitems * sizeof(*p));
}

void tpl_upkfloat(void *message, float *p, int nitems)
{
	tpl_upkbyte(message, p, nitems * sizeof(*p));
}

void tpl_upkint(void *message, int *p, int nitems)
{
	tpl_upkbyte(message, p, nitems * sizeof(*p));
}

void tpl_upklong(void *message, long *p, int nitems)
{
	tpl_upkbyte(message, p, nitems * sizeof(*p));
}

void tpl_upklongdouble(void *message, long double *p, int nitems)
{
	tpl_upkbyte(message, p, nitems * sizeof(*p));
}

void tpl_upkshort(void *message, short *p, int nitems)
{
	tpl_upkbyte(message, p, nitems * sizeof(*p));
}

void tpl_upkuchar(void *message, unsigned char *p, int nitems)
{
	tpl_upkbyte(message, p, nitems * sizeof(*p));
}

void tpl_upkuint(void *message, unsigned int *p, int nitems)
{
	tpl_upkbyte(message, p, nitems * sizeof(*p));
}

void tpl_upkulong(void *message, unsigned long *p, int nitems)
{
	tpl_upkbyte(message, p, nitems * sizeof(*p));
}

void tpl_upkushort(void *message, unsigned short *p, int nitems)
{
	tpl_upkbyte(message, p, nitems * sizeof(*p));
}

