use strict;
use warnings;
use Irssi;
my %repeat_whois;
my $redraw;

sub parseargs {
    my $args = shift;
    my @args = split /(?:^| ):/, $args, 2;
    unshift @args, split ' ', shift @args;
    @args
}

Irssi::signal_add_first(
    'event 263', sub {
	my ($server, $args, $sender, $addr) = @_;
	my @args = parseargs($args);
	if (lc $args[1] eq 'whois') {
	    $repeat_whois{$server->{tag}}++;
	} else {
	    Irssi::signal_emit('default event', $server, "263 $args", $sender, $addr);
	}
    }
   );
Irssi::signal_register({'whois end'=>[qw[iobject string string string]]});
Irssi::signal_add_first(
    'event 318', sub {
	my ($server, $args, $sender, $addr) = @_;
	unless ($repeat_whois{$server->{tag}}) {
	    Irssi::command("REDRAW") if $redraw;
	    $redraw = undef;
	    return;
	}
	$repeat_whois{$server->{tag}}--;
	my @args = parseargs($args);
	$server->command("WHOIS $args[1] $args[1]");
	$redraw++;
	print STDERR ("\e7 [retrying WHOIS $args[1] ($redraw)...]\e8");
	Irssi::signal_stop;
    }
   );
