#!/usr/bin/env perl

# fillchk.lua: scan for repetitions of a single byte (file corruption)
# 2019-10-24,  ed <fillchk@ocv.me>,  MIT-licensed
#
# this impl:
#   4.4 MiB/s, just use the other versions
#
# see also:
#   https://ocv.me/dev/?fillchk.c
#   https://ocv.me/dev/?fillchk.cpp
#   https://ocv.me/dev/?fillchk.py
#   https://ocv.me/dev/?fillchk.pl
#   https://ocv.me/dev/?fillchk.go
#   https://ocv.me/dev/?fillchk.lua

use strict;
use warnings;
binmode(STDIN);

sub report {
	my ($ch, $p1, $p2) = @_;
	printf "from %08x to %08x, %02x seen 0x%x / %d times\x1b[J\n",
		$p1, $p2, ord($ch), $p2-$p1, $p2-$p1;
}

my $p0 = 0;
my $ch0 = 0;
my $pos = -1;

while (read STDIN, my $buf, 4096) {
	$buf = reverse $buf;
	#while ($buf =~ /(.)/gc) {
	#	$pos += 1;
	while (length $buf) {
		$pos += 1;
		my $ch = chop $buf;
		if ($ch eq $ch0) {
			next;
		}
		if ($pos - $p0 >= 0x400) {
			report($ch0, $p0, $pos);
		}
		$ch0 = $ch;
		$p0 = $pos;
	}
}
if ($pos - $p0 >= 0x400) {
	report($ch0, $p0, $pos);
}
