#!/usr/bin/perl -w

# useful on the saved output of mde40 command
# trigger times of 2byte words, but unknown which is high byte


# default threshold :
$threshold=1.5;
if (defined $ARGV[0]){
	$threshold=$ARGV[0];
}

my $tabs = 0;
my $ch;
my $counter=1;

# array(ref) for tooth-gaps:
$toothgap = [ 0 ];

while (defined ($ch = getc STDIN)){

	unshift @a, $ch;

	if( $#a > 10){
		# print STDERR "popping\n";
		# pop @a;
	}

	$tabs ++;
	if( $tabs > 1){
		$tabs = 0;
	}

	my $num = getdiff( $toothgap, @a );

	my $s = ($tabs == 0 ? '' : "\t\t\t\t\t\t");


	my  $missing_or_not = ' ';
	if ( $mult >= $threshold ){
		my $odd = $counter % 2;

		my $teeth_passed = 0.5 * ($counter - $prev_missing_tooth[$odd]);
		$missing_or_not =  ' MISSINGTOOTH ' . $teeth_passed ;
		$prev_missing_tooth[$odd] = $counter;
	}

	print $counter. "\t". $s . $num . "\t" . $mult .  $missing_or_not . "\n";
	$counter++;
}


# besides diff, also provides $mult in global variable;
# and changed $tg->[] array !!!
sub getdiff
{
	my ($tg, $lo1, $hi1, $lo2, $hi2) = @_;

	my $n1 = tonum( $lo1, $hi1 );	# fresh
	my $n2 = tonum( $lo2, $hi2 );	# older

 	my $diff = $n1 - $n2;

	# % 65536
	if( $diff < 0 ){
		# handle underflow
		$diff += 65536;
	}

	my $tg_prev = $tg->[1]; 

	# intentionally global:
	$mult = 1;
	if( defined $tg_prev && ($tg_prev > 1)){
		$mult = 0.01 * int(100 * $diff / $tg_prev);
	}

	unshift @$tg, $diff;
	return $diff;
}


#  1, 2 => 258 ( == 1*256 + 2) BUT INPUT IS LITTLE ENDIAN !!!
sub tonum
{
	my ($lo, $hi) = @_;
	my $l = ord($lo);
	my $h = ord($hi);
	my $n = $h * 256 + $l;
	# print "tonum: $h, $l (=$n)\n";
	return $n ;
}


