#!/usr/bin/perl
# simple dictionary lookup with char-by-char stemming
# prefix search (word*) performed on default, use word+ to search for word
use strict;
use Text::Wrap;
use Search::Saryer;
use locale;

$Text::Wrap::columns=75;
my $dict = '/usr/local/dict/ERE.full';
my $vowels = '(a|e|i|j|o|u|y|||||||||)';
my $tolerance = 0.7; # how much is allowed to stem word
my $PAGER = 'less -eMIsX';
my (@search_params,@result) = ();
my @opts = qw ( -l -b -p); # first is default
my %opt = ();
my $query = '';
my $saryer = new Search::Saryer(filename=>$dict);


my $nopt = 0;
foreach my $arg (@ARGV) {
   if ( grep /$arg/, @opts ) {
      $nopt++;
      $opt{$arg}=1;
   } else {
      $query .= $arg . ' ';
   }
}
# default
$opt{ $opts[0] } = 1 if ( !$nopt );

die "Usage: $0 [-pbl] word (vocterm for interactive usage)\nOleg Bartunov, 2001-2002\n" if !$query;

my ($suffix,$flag,$line,$wordbold) = '';
my ($cnt,$n) = 0;
($query,$flag) = ( $query =~ /^(.*?)((?:\*|\+)*)$/ ); # word*, word+
my $word = $query;
my $qlength = length($query);

while ( length($word) >= 3 &&    # absolute check
        int( length($suffix)/$qlength ) < $tolerance && # relative check
        grep /$vowels/i, split //,$word   # must be at least one vowel
       ) {
   $word .= ' ' if ( $flag eq '+' ); # exact matching 
   @result = $saryer->grep($word,'ignore_case');
   $n = scalar @result;
   $suffix = ($suffix)? '['.$suffix.']' :'';
   $word =~ s/(\s+)$//;
   if ( $opt{'-l'} ) {
     ($wordbold = $word ) =~ s/(.)/$1$1/g;     # termcap
   } elsif ( $opt{'-b'} ) {
     $wordbold = '[1m'.$word.'[0m';           # bash
   }
#   $line = $word . $suffix . ':' . join( "\n", map{ split /\s+(?=\d+[>)])/ } sort @result) ;
   $line = join( "\n", map{ split /\s+(?=\d+[>)])/ } 
           map { $_->[1] } 
           sort { $a->[0] <=> $b->[0] } 
           map { [ length( ( split /\s+/ )[0] ), $_ ] } @result) ;
   $line =~ s/$word/$wordbold/ig if ( $opt{'-b'} || $opt{'-l'} );
   if ( $n > 0 ) {
     if ( $opt{'-l'} ) {
       if ( open(PAGER,"|$PAGER") ) {
         print PAGER Text::Wrap::wrap("->"," ",$line);
         close (PAGER);
       } else { # fallback to standard mode
         print       Text::Wrap::wrap("->"," ",$line);
       } 
     } else {
       print       Text::Wrap::wrap("->"," ",$line);
     }
     last; # the end
   }
   $cnt++;
   ($word,$suffix) = ( $query =~ /^(.+)(.{$cnt})$/ );
}
