#!/usr/bin/perl -w
use lib "/usr/cslib/libraries/perl";
use Term::ReadKey;

if ($ENV{TERM} !~ /xterm/) {
	exec("man", @ARGV);
}

ReadMode 3;

sub getcol {
	my $id = shift;
	print "\e]$id;?\e\\";
	
	my $s = "";
	while (1) {
		$s .= ReadKey 0;
		if ($s =~ /\e\\$/) {
			last;
		}
	}

	$s =~ /^\e]$id;(.*)\e\\/;
	return $1;
}

sub setcol {
	my $id = shift;
	my $col = shift;
	print "\e]$id;$col\e\\";
}

my $fg = getcol 10;
my $bg = getcol 11;

$bg =~ m#^rgb:([[:xdigit:]]*)/([[:xdigit:]]*)/([[:xdigit:]]*)$#;
my $max = 16 ** length $1;
if (((hex($1) + hex($2) + hex($3)) / 1.5) > $max) {
	# light bg
	setcol(11, "rgb:ef/c2/e5");
	system("man", @ARGV);
	setcol(11, $bg);
} else {
	# dark bg
	setcol(10, "rgb:d1/8a/c2");
	system("man", @ARGV);
	setcol(10, $fg);
}

ReadMode 0;
