#! /usr/bin/perl

use v5.36;

my %keys;

sub find_manpage($man, $section)
{
	my $f;
	for my $d ("/usr/share/man/", "/usr/X11R6/man", "/usr/local/man") {
		for my $try (split(/,\s+/, $man)) {
			if (open($f, '<', "$d/man$section/$try.$section")) {
				return $f;
			}
		}
	}
	return undef;
}

sub cache_file($man, $section)
{
	my $f = find_manpage($man, $section);
	if (!defined $f) {
		say STDERR "Can't locate $man($section)";
		return;
	}
	my $h = {};
	while (<$f>) {
		chomp;
		if (m/^\.Ev\s+(.*)/) {
			for my $word (split(/\s+/, $1)) {
				$h->{$word} = 1;
			}
		} elsif (m/^\.It\s+Ev\s+(.*)/) {
			for my $word (split(/\s+/, $1)) {
				$h->{$word} = 1;
			}
		}
	}
	$keys{$man.$section} = $h;
	close($f);
}

sub contains($man, $section, $ev)
{
	if (!defined $keys{$man.$section}) {
		cache_file($man, $section);
	}
	if ($keys{$man.$section}{$ev}) {
		return 1;
	} else {
		return 0;
	}
}



open(my $g, '<', "fullwords") or die;
while (<$g>) {
	chomp;
	if (m/^(.*)(\s\=\>.*)/) {
		my ($var, $rest) = ($1, $2);
		my @mans;
		open(my $pipe, "man -k Ev=$var 2>/dev/null|");
		while (<$pipe>) {
			chomp;
			if (m/^(.*)\((\dp?)\)\s+\-\s+/) {
				my ($man, $section) = ($1, $2);
				if (contains($man, $section, $var)) {
					push(@mans, "$man($section)");
			    	}
			}
	    	}
		close($pipe);
		if (@mans) {
			say $var.' ('.join(', ', @mans).')'.$rest;
		} else {
			say $var.$rest;
		}
	}
}

