#!/usr/bin/perl -w
# Script to translate a string to another language using
# altavista's babelfish...
# Author: Michael L. Hostbaek <mich@freebsdcluster.org>
# Version 1.0
#
# Use: ./translate -f<from language> -t<to language> text

use LWP::UserAgent;
use Getopt::Std;
use HTTP::Request::Common;

# check paramaters
getopts('hf:t:');
if (defined($opt_h)) {
    print "translate version 1.0
by Michael L. Hostbaek <mich\@freebsdcluster.org>
Usage : translate -f<from language code> -t<to language code> text
Note : If more than one word needs to be translated, string must be 
single-quoted.

Language codes available :
English - en
French - fr
German - de
Italien - it
Portuguese - pt
Spanish - es

Example : translate -f en -t fr 'how are you' will give the result :
[how are you] --> comment allez vous
translate -h $opt_h will produce this help message\n";
    exit;
} elsif(!(@ARGV) || !(defined($opt_t)) || !(defined($opt_f))) {
    print "Please specify languages - and text\nUsage: translate -f<from language code> -t<to language code> text\nSee translate -h for help\n";
    exit;
}


# send request
my $convert_code = $opt_f."_".$opt_t;
my $convert_text = $ARGV[0];

my $request=POST
'http://babelfish.altavista.com/translate.dyn',[doit=>"done",bbltype=>"urltext",lp=>$convert_code,urltext=>$convert_text];
$request->content_type('application/x-www-form-urlencoded');
my $do_browser=LWP::UserAgent->new;
my $answer=$do_browser->request($request)->content;

# let us see these results
my $content = $answer;
if($content =~ /<textarea.*?>(.*?)<\/textarea>/si) { 
    $lort = $1; 
    $lort =~ s/\n//g;
}
print "[$convert_text] ---> $lort\n";
