#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static int indian;
main()
{
	char bf[555];
	int i;
	lib_setendian();
	printf("lib crc %d\n",lib_crc32("test string"));
	for (i=0;;i++) {
		gets(bf);
		printf("crc %d\n",lib_crc32(bf+i));
	}
}
int lib_setendian(void)
{
	union {char bf[2]; short x;} both;
	if (indian!=0) return;
	if ( (((char *) &both.x)-1) == &both.bf[0]) {
		indian = -1;
	} else {
		indian = 1;
	}
	printf("Processor is %d endian order \n",indian);

}
int lib_crc(char *xin)
{
  unsigned short dx;
  unsigned char *in = (unsigned char *) xin;
  unsigned short ax;
  unsigned char *al;
  unsigned char *ah;
  unsigned char *dl;
  unsigned char *dh;
	
	ax = 0xffff;
	al = (unsigned char *) &ax;
	ah = al+indian;
	dl = (unsigned char *) &dx;
	dh = dl+indian;
	for (;(*in!=0);in++) {
 	  dx = ax;
	  *dl = *al ^ *in;
	  *dl = *dl ^ (*dl / 16);
	  *ah = *dl * 16;
	  *dh = *dh ^ *ah;
	  *al = *dl;
	  *ah = 0;
	  ax *= 32;
	  ax = ax ^ dx;
	}
	return ax;

}
int lib_crc32(char *xin)
{
  unsigned int dx;
  int r;
  unsigned short *in;
  unsigned int ax;
  unsigned short *al;
  unsigned short *ah;
  unsigned short *dl;
  unsigned short *dh;
	
	if (*xin==0) return 0;
	if (((long) xin)&1 == 1) xin++;
	in = (unsigned short *) xin;

  ax = 0xffffffff;
	al = (unsigned short *) &ax;
	ah = al+indian;
	dl = (unsigned short *) &dx;
	dh = dl+indian;
	for (;(*in!=0);in++,xin+=2) {
 	  dx = ax;
	  *dl = *al ^ *in;
	  *dl = *dl ^ (*dl / 256);
	  *ah = *dl * 256;
	  *dh = *dh ^ *ah;
	  *al = *dl;
	  *ah = 0;
	  ax *= 1024;
	  ax = ax ^ dx;
	  if (xin[0] == 0) break;
	  if (xin[1] == 0) break;
	}
	r = (int) ax;
	if (r<0) r = -r;
	return r;

}