#!/usr/bin/perl -s

$dflttags = "tags $ENV{'HOME'}/tags $ENV{'HOME'}/etc/tags";

# tag - output the files corresponding to each given vi tag
# Steve Kinzler, steve@kinzler.com, Dec 02/Apr 08
# https://kinzler.com/me/home.html#vi

$tags  = (defined $ENV{'TAGS'}) ? $ENV{'TAGS'} : $dflttags;
$tags .= ' ' . $ENV{'TAGSMORE'} if $ENV{'TAGSMORE'};

$usage = "usage: $0 [ -s | -m ] [ -f | -q ] [ tag ... ]
	-s	output only the first matching tag's file (default)
	-m	output all the matching tags' files
	-f	output tags as files if they're not found
	-q	don't warn of tags not found
Tag files searched are listed in \$TAGS then \$TAGSMORE.
Default: $dflttags
Current: $tags\n";
die $usage if $h;

foreach (grep(/./, split(/\s+/, $tags))) {
	open(TAGS, $_) || next;
	while (<TAGS>) {
		next if /^!_/ || /^\s*$/;
		($tag, $file) = split(/\t+/);
		# Note: very hard to safely expand $var and ~user in files
		#	here; leaving these functions out of this script
		$tag{$tag} = (! defined $tag{$tag}) ? $file :
			$tag{$tag} . (($m) ? "\n$file" : '');
	}
	close TAGS;
}

foreach (@ARGV) {
	print($_,	"\n"), next if $f && ! defined $tag{$_};
	$q || warn("$0: tag not found ($_)\n"), next unless defined $tag{$_};
	print $tag{$_}, "\n";
}
