# NOTE: Derived from lib/Zoidberg/Fish/Intel.pm.
# Changes made here will be lost when autosplit is run again.
# See AutoSplit.pm.
package Zoidberg::Fish::Intel;

#line 387 "lib/Zoidberg/Fish/Intel.pm (autosplit into blib/lib/auto/Zoidberg/Fish/Intel/i_man_opts.al)"
sub i_man_opts { # TODO caching (tie classe die ook usefull is voor FileRoutines ?)
	my ($self, $block) = @_;
	return unless $$self{config}{man_cmd} && $$block[1];
	debug "Going to open pipeline '-|', '$$self{config}{man_cmd}', '$$block[1]'";

	# re-route STDERR
	open SAVERR, '>&STDERR';
	open STDERR, '>', $Zoidberg::Utils::FileSystem::DEVNULL;

	# reset manpager
	local $ENV{MANPAGER} = 'cat'; # FIXME is this portable ?

	open MAN, '-|', $$self{config}{man_cmd}, $$block[1];
	my (%poss, @poss, $state, $desc);
	# state 3 = new alinea
	#       2 = still parsing options
	#       1 = recoding description
	#       0 = skipping
	while (<MAN>) { # line based parsing ...
		if ($state > 1) { # FIXME try to expand "zoid --help" & "zoid --usage"
			# search for more options
			s/\e.*?m//g; # de-ansi-fy
			s/.\x08//g;  # remove backspaces
			unless (/^\s*-{1,2}\w/) { $state = ($state == 3) ? 0 : 1 }
			else { $state = 2 }
			$desc .= $_ if $state;
			next unless $state > 1;
			while (/(-{1,2}[\w-]+)/g) { push @poss, $1 unless exists $poss{$1} }
		}
		elsif ($state == 1) {
			if (/\w/) { $desc .= $_ }
			else {
				$state = 3;
				# backup description
				my $copy = $desc || '';
				for (@poss) { $poss{$_} = \$copy }
				($desc, @poss) = ('', ());
			}
		}
		else { $state = 3 unless /\w/ }
	}
	close MAN;
	open STDERR, '>&SAVERR';
	
	$block->[0]{poss} = [ grep /^\Q$$block[-1]\E/, sort keys %poss ];
	if (@{$$block[0]{poss}} == 1) { $$block[0]{message} = ${$poss{$$block[0]{poss}[0]}} }
	elsif (exists $poss{$$block[-1]}) { $$block[0]{message} = ${$poss{$$block[-1]}} }
	$block->[0]{message} =~ s/[\s\n]+$//; #chomp it

	return $block;
}

# end of Zoidberg::Fish::Intel::i_man_opts
1;
