#!/usr/bin/perl

use strict;

die "usage: $0 <hex>\n" unless @ARGV;
my $hex = shift;

my @bytes = map { ord } split //, pack("H*", $hex);

print "@bytes\n";
my $crcTmp = 0xFFFF;

my $i = 0;
if ($bytes[0] == 0xFE) { $i = 1; } # start of frame included?
print "i=$i\n";

for (; $i < @bytes; $i++)
{
	$crcTmp = crc_accumulate($bytes[$i], $crcTmp);
}
print "$crcTmp\n";
$crcTmp = unpack("H4", pack("s", $crcTmp));
print "0x$crcTmp\n";

sub crc_accumulate
{
	my ($b, $crc) = @_;

	my $ch = ($b ^ ($crc & 0x00ff)) & 0xFF;
	$ch = ($ch ^ ($ch << 4)) & 0xFF;
	#print "ch=$ch crc=$crc\n";
	return (($crc >> 8) ^ ($ch << 8) ^ ($ch << 3) ^ ($ch >> 4));
}
