#!/usr/bin/perl -w
#
# Dict - odszukuje definicje, synonimy i antonimy sw.
# Komentarze, sugestie, uwagi? Prosz na adres e-mail adam@bregenzer.net.
#
# Jest to darmowe oprogramowanie; moesz je rozpowszechnia i/lub
# modyfikowa na takich warunkach, jak samego Perla.
#

use strict; $|++;
use LWP;
use Net::Dict;
use Sort::Array "Discard_Duplicates";
use URI::Escape;

my $word = $ARGV[0]; # the word to look-up
die "Nie podano sowa!\n" unless $word;
print "Definicje sowa '$word':\n";

# pobierz wyniki z dict.org.
my $dict = Net::Dict->new('dict.org');
my $defs = $dict->define($word);
foreach my $def (@{$defs}) {
    my ($db, $definition) = @{$def};
    print $definition . "\n";
}

# bazowy adres URL do da do thesaurus.com oraz kod HTML otaczajcy
# potrzebne nam dane; wyraenia regularne czyszczce dane.
my $base_url       = "http://thesaurus.reference.com/search?q=";
my $middle_html    = ":</b>&nbsp;&nbsp;</td><td>";
my $end_html       = "</td></tr>";
my $highlight_html = "<b style=\"background: #ffffaa\">";

# pobierz wyniki z tezaurusa.
my $ua = LWP::UserAgent->new(agent => 'Mozilla/4.76 [en] (Win98; U)');
my $data = $ua->get("$base_url" . uri_escape($word))->content;

# miejsce na znalezione dane.
my (@synonyms, @antonyms);

# a teraz ptla po tych danych.
while ($data =~ /Entry(.*?)<b>Source:<\/b>(.*)/) {
    my $match = $1; $data = $2;

    # odrzucamy pogrubienia dopasowanych sw.
    $match =~ s/${highlight_html}([^<]+)<\/b>/$1/;

    # wstawiamy wyniki do rnych tablic.
    if ($match =~ /Synonyms${middle_html}([^<]*)${end_html}/) {
        push @synonyms, (split /, /, $1);
    }
    elsif ($match =~ /Antonyms${middle_html}([^<]*)${end_html}/) {
        push @antonyms, (split /, /, $1);
    }
}

# sortowanie za pomoc sort::array, zwrcenie dopasowa bez powtrze.
if ($#synonyms > 0) {
    @synonyms = Discard_Duplicates(
        sorting      => 'ascending',
        empty_fields => 'delete',
        data         => \@synonyms,
    );

    print "Synonimy sowa $word:\n";
    my $quotes = ''; 
    foreach my $nym (@synonyms) {
        print $quotes . $nym;
        $quotes = ', ';
    } print "\n\n";
}

# to samo, co powyej.
if ($#antonyms > 0) {
    @antonyms = Discard_Duplicates(
        sorting      => 'ascending',
        empty_fields => 'delete',
        data         => \@antonyms,
    );

    print "Antonimy sowa $word:\n";
    my $quotes = ''; # purtier.
    foreach my $nym (@antonyms) {
        print $quotes . $nym;
        $quotes = ', ';
    } print "\n";
}

