# which for RISC OS
# =================
#
# written by Vincent Lefevre <vincent@vinc17.net>

use strict;
use RISCOS::Filespec;

@ARGV == 1 or die "Usage: which <command>\n";
my $cmd = $ARGV[0];
my ($f,$alias,$path);

sub help ($)
  {
    my $module;
    open HELP, "Help $_[0]|" or return;
    while (<HELP>)
      {
        /^[\000-\037]*$/ and $module = '', next;
        $module ne '' or ($module) = /^[\000-\037]*(.*?)\s+\d+\.\d/, next;
        /\b\Q$cmd\E\b/i and last;
      }
    close HELP;
    return $module;
  }

if (defined ($alias = $ENV{'Alias$'.$cmd}))
  {
    $f = 1;
    $alias =~ s/(["|<])/|$1/g;
    $alias =~ s/([\000-\037])/"|".chr(64+ord$1)/eg;
    $alias =~ s/\177/|?/g;
    print "$cmd: aliased to $alias\n";
  }

if (open HELP, "Help $cmd|")
  {
    while (<HELP>)
      {
        /^[\000-\037]*==> Help on keyword \Q$cmd\E/i or next;
        <HELP> =~ /^[\000-\037]*Module is:/ and next;
        $f = 2;
        last;
      }
    close HELP;
    if ($f == 2)
      {
        my $module = help('Commands');
        if ($module ne '')
          { $module = " ($module)" }
        elsif (help('FileCommands') ne '')
          { $module = " (filing system command)" }
        print "$cmd: builtin command$module\n";
      }
  }

if (defined ($path = $ENV{'Run$Path'} || $ENV{'Run$Path(Macro)'}))
  {
    foreach (split ',', $path)
      { tr/\t //;
        $_ .= $cmd;
        -e $_ and $f = 1, print "$_\n"; }
  }

$f or die "$cmd: not found\n";