#include <string.h>
#include "sys.h"
#include "Helper.h"
u32 Crc32Table[256];
void Helper_CRC32_Init(void){
	  u32 Crc;        
		int i,j;
		for(i = 0;i < 256; i++)
		{
				Crc = (u32)i;
				for (j = 8; j > 0; j--)
				{
						if ((Crc & 1) == 1)
								Crc = (Crc >> 1) ^ 0xEDB88320;
						else
								Crc >>= 1;
				}
				Crc32Table[i] = Crc;
		}
}
 
uint32_t Helper_CRC_CalcBlockCRC8(uint8_t pBuffer[], uint32_t BufferLength){

	u32 value = 0xffffffff;

	for (int i = 0; i < BufferLength; i++)
	{
			value = (value >> 8) ^ Crc32Table[(value & 0xFF)^ pBuffer[i]];
	}
	return value ^ 0xffffffff;
}
 
uint32_t Helper_CRC_CalcFlashBlockCRC8(u32 flashStartAddr, uint32_t bytesLength)
{

	u32 value = 0xffffffff;
	u32 u32Count=(bytesLength+sizeof(u32)-1)/sizeof(u32);
	u32 calcByteCount=0;
	u32Byte4 dwordData;
	
	for (int i = 0; i < u32Count; i++)
	{
			dwordData.u32_Data=(*(vu32*)(flashStartAddr+i*sizeof(u32)));
			for(int j=0;j<sizeof(u32);j++)
			{
				if (calcByteCount<bytesLength)
				{					
					value = (value >> 8) ^ Crc32Table[(value & 0xFF)^ dwordData.bytes[j]];
					calcByteCount++;
				}
				else
					break;
			}
	}
	return value ^ 0xffffffff;
}
	
uint16_t Helper_Sum16(uint8_t *buffer, uint32_t length){
	uint16_t result=0;
	for(int i=0;i<length;i++){
		result+=(uint16_t)buffer[i];
	}
	return result;
}
u8 Helper_CheckInvertBytesIsRegist(u8 * pData,u16 totalLength)
{
	if (totalLength==0)
		return 1;
	if ((totalLength % 2)!=0)
		return 0;
	u16 bytes=totalLength/2;
	for(int i=0;i<bytes;i++)
	{
		if (((~pData[i]) & 0xff)!=pData[i+bytes])
			return 0;
	}
	return 1;
}

void Helper_ConvertInvert(u8 * pData,u16 sourceBytes)
{
	for(int i=0;i<sourceBytes;i++)
		pData[i+sourceBytes]=(~pData[i]) & 0xff;
}
u8 Helper_CheckRightRecvedData(u8 *pData,u16 dataLength,u16 exceptLength,u8 bIsContentBitInverted_Recv)
{
	if (dataLength==0)
		return 1;
	u8 bDataOK=1;
	u8 validDataLength=dataLength;
	if (bIsContentBitInverted_Recv)
	{
		validDataLength=dataLength/2;
		if (!Helper_CheckInvertBytesIsRegist(pData,dataLength))
			bDataOK=0;
	}
	if (validDataLength!=exceptLength)
		bDataOK=0;	
	return bDataOK;
}
