#!/usr/bin/perl
use warnings;
use strict;

use Data::Dump qw(dump);

my @last;

while(1) {

my @pcf = `gpio -x pcf8591:120:0x48 readall`;
my @gpio = `gpio -g readall`;
my $i = 0;
my $mode;

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;
	my @l = split(/\|/, $line);
	if ( $#l > 10 ) {
		no warnings;
		$mode->{ $l[1]  } = [ $l[4] + 0, $l[2], $l[3] ];
		$mode->{ $l[11] } = [ $l[8] + 0, $l[10], $l[9] ];
		$mode->{ $l[13] } = [ $l[14], $l[15] ] if $l[15];
		#warn "## l = ",dump(@l);
	}
	

	if ( $last[$i] && $line ne $last[$i] ) {
		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++;

}

#warn "# mode = ", dump($mode);

sub pin2dir {
	my $pin = shift;
	my ($p) = grep { /$pin/ } keys %$mode;
warn dump($p);
	my $dir = $mode->{ $p }->[2];
	warn "# pin2dir $pin = $dir\n";
	return $dir;
}
	

my $cmd = <STDIN>;
chomp $cmd;
if ( $cmd =~ m/^(\d+)$/ ) {
	my $pin = $1;
	system "gpio -g mode $pin out" unless pin2dir($pin) =~ m/OUT/i;

	my $v = `gpio -g read $pin`;
	warn "# pin $pin ", $v;
	$v ^= 1;
	system "gpio -g write $pin $v";
}


} #/while

