#!/usr/bin/perl
# Filename:     define
# Author:       David Ljung
# Description:  Looks up a word on the web
use strict;

##################################################
# Setup the variables
##################################################
($MAIN::PROGNAME = $0) =~ s|.*/||;

#my $WEBSTER='http://smac.ucsd.edu/cgi-bin/http_webster?method=exact&isindex=%s';
my $DICTIONARY='http://dictionary.reference.com/browse/%s';

my $BROWSER = "browser";	# Or netscape or whatever..

# Pick one
#my $GET  = "lynx -source";
my $GET  = "GET";

##################################################
# Usage
##################################################
sub usage {
  my $msg;
  foreach $msg (@_) { print "ERROR:  $msg\n"; }
  print "\n";
  print "Usage:\t$MAIN::PROGNAME [-d] [-n] <word>\n";
  print "\tLooks up a word's definition\n";
  print "\t-b\tStartup browser\n";
  print "\t-d\tDebug mode\n";
  print "\n";
  exit -1;
}

sub parse_args {
  my $word;
  my ($browser,$debug) = (0,0);
  while ($#ARGV>=0) {
    $a=shift(@ARGV);
    if ($a =~ /^-h$/) { usage(); }
    if ($a =~ /^-d$/) { $debug=1; next; }
    if ($a =~ /^-b$/) { $browser=1; next; }
    if ($a =~ /^-/) { &usage("Unknown option: $a"); }
    usage("You can only specify one word [$word] vs [$a]") if (defined($word));
    $word=$a;
  }
  usage("You need to specify a word to lookup") if (!defined($word));
  ($word,$browser,$debug);
}

##################################################
# Define
##################################################
sub define {
  my ($word,$browser,$debug) = @_;
  my $query=$DICTIONARY;
	$query =~ s/%s/$word/g;
  if ($browser) {
    $query=~s/&/\\&/g;
    print "$BROWSER $query\n" if ($debug);
    system("$BROWSER $query");
    exit;
  }
  open(HTML,"$GET '$query' |")
    || die("Couldn't $GET $query\n");
  my ($go,$blank)=(0,0);
  while(<HTML>) {
		$go=1 if /<section[^>]+class="def-pbk"/;
		$go=0 if /<\/section>/;

    # Un-HTML
    s#</?(h\d|a|p|br|hr|(a class=|a href=|input|form|div|span|section|header)[^>]*)>##ig;
    s/\s?&amp;\s?/&/;
    s/\s?&lt;\s?/</;
    s/\s?&gt;\s?/>/;
    print if ($debug);

		#$go=1 if (/Hypertext Webster Gateway:/);
		#$go=0 if (/Additional Hypertext Webster/);
    next if (!$go);
    if (/^\s*$/) {
      print unless $blank++;
      next;
    }
    $blank=0;
		print "\n" if /^From /;
    print;
  }
  close(HTML);
}

##################################################
# Main code
##################################################
sub main {
  define(parse_args());
}

main();
