#!/usr/bin/perl

my @last;

while(1) {

my @pcf = `gpio -x pcf8591:120:0x48 readall`;
my @gpio = `gpio -g readall`;
my $i = 0;
foreach (@gpio) {
	chomp;
#	next unless /\d\s/;

	# kill wiringpi mapping columns
	s/^(.{8}).{6}/$1/;
	s/.{6}(.{8})$/$1/;

	s/([ \d]{2})(...GPIO.)../$1$2$1/;
	s/(GPIO.)..(...)(\s*\d+)/$1$3$2$3/;

	my $line = $_ . ( shift @pcf || '');
	chomp $line;
	if ( $last[$i] && $line ne $last[$i] ) {
		my @l = split(/\|/, $line);
		my @o = split(/\|/, $last[$i]);
		foreach my $i ( 0 .. $#l ) {
			$l[$i] = "\e[33;7;1m$l[$i]\e[0m" if $l[$i] ne $o[$i];
		}
		print join('|', @l), "|\n";
	} else {
		print "$line\n";
	}
	$last[$i] = $line;
	$i++;
}

my $cmd = <STDIN>;
chomp $cmd;
if ( $cmd =~ m/^(\d+)$/ ) {
	my $v = `gpio -g read $1`;
	warn "# pin $1 ", $v;
	$v ^= 1;
	system "gpio -g write $1 $v";
}


} #/while

