#!/usr/bin/perl
#
# CRC16 algorythm implimented by Sheer

# (there's probably already a PM that does this)
#

@test_array = ();

while((defined($p = shift)) && $p ne "end") {
	push(@test_array,hex $p);
}

$crc16 = crc_16(@test_array);


printf("CRC: %04x %d %d\n",$crc16, (($crc16 & 0xFF00) >> 8), ($crc16 & 0x00FF));


sub crc_16 {
	my $crcval, $n, $q, $c, $t1, $t2;
	$crcval = 0;

	while((defined($c = shift))) {
		$t1 = ($crcval ^ $c);
		$q = $t1 & 0x000f;

		$t1 = ($crcval >> 4);
		$t2 = $q * 0x1081;
		$crcval = $t1 ^ $t2;

		$t1 = ($c >> 4);
		$t2 = ($crcval ^ $t1);
		$q = ($t2 & 0x000f);

		$t1 = ($crcval >> 4);
		$t2 = $q * 0x1081;
		$crcval = $t1 ^ $t2;
	}

	return $crcval;

}

