#!/usr/bin/perl

# written by Andrii Grytsenko, 2010

use Locale::Recode;
use LWP::UserAgent;
use strict;


sub parse_html {
    my $text = shift;
    my $result ;
    $text =~ s/></>\n</g;
    foreach my $line (split(/\n/,$text)){
	$result .= $line."\n" if ( $line =~ /span class=.translation/ or $line =~ /lol-dict-name/ or 
				   $line =~ /span class=.Abbrev./ or $line =~ /span class=.comment./);
    }
    return $result;
}

sub print_html {
    my $text = shift; 
    my $class = 0;
    foreach my $line (split(/\n/,$text)){
	$line =~ s/<[^>]+>//g ; #delete all html tags
	print "$line\n";
    }
}


my $cd = Locale::Recode->new (from => 'UTF-8', to => 'koi8-r');
die $cd->getError if $cd->getError;
my $ua = LWP::UserAgent->new;
$ua->agent("Firefox/0.1 ");

my $word = $ARGV[0];
my $req = HTTP::Request->new(GET => "http://lingvo.abbyyonline.com/en/en-ru/$word");

my $res = $ua->request($req);

if ($res->is_success) {
    my $text = $res->content;
    $cd->recode($text); # change code encoding from UTF-8 to koi8-ru
    print "Translate for word $word\n";
    $text = parse_html($text);
    print_html($text);
} else {
    print $res->status_line, "\n";
}
