#include "h/p33FJ64GP802.h"
#include "h/crc.h"

unsigned int CRC7(BYTE* chr, unsigned long cnt)
{
	int i; 
	unsigned long a;
	unsigned char crc,Data; 

	crc=0; 
	for (a=0; a<cnt; a++) 
	{ 
		Data=chr[a]; 
		for (i=0;i<8;i++)
		{ 
		crc <<= 1; 
		if ((Data & 0x80)^(crc & 0x80)) 
		crc ^=0x09; 
		Data <<= 1; 
		} 
	} 
	crc=(crc<<1)|1; 
	return((unsigned int)crc); 
}

unsigned int CRC16(BYTE* chr, unsigned long cnt)
{
	// compute the CRC16 of bytes at chr and cnt bytes in total
	// the polynomial is
	unsigned int CRCResult;
	unsigned int tmp;
	unsigned long i;

	CRCCON = 0x0F; 		/* Configure the polynomial length (PLEN) */
	CRCXOR = 0x1020; 	/* In CRCXOR, configure for the polynomial x^16 + x^12 + x^5 + 1 */
	CRCWDAT = 0x00; 	/* Clear CRCWDAT*/

	for(i = 0; i< cnt; i+=2)
	{
	tmp=((*chr)<<8)+(*(chr+1));
	CRCDAT=tmp; 				/* Populate the FIFO */
	chr+=2;
	if(CRCCONbits.CRCFUL)
	{
	CRCCONbits.CRCGO = 1; 		/* CRC calculation start */
	}
	while(CRCCONbits.CRCFUL); 	/* Wait for available FIFO register */
	}
	CRCDAT = 0x0000;			/* Do this to shift the last word out of the CRC shift register */
	while (!IFS4bits.CRCIF); 	/* Check for interrupt flag bit */
	IFS4bits.CRCIF = 0;
	while(!CRCCONbits.CRCMPT);	/* Wait for CRC shifter to clear FIFO */
	CRCResult = CRCWDAT; 		/* Output result */
	CRCWDAT = 0;
	return CRCResult;
}

