#!/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.10
#
# Use: ./translate -f<from language> -t<to language> text


=head1 NAME

translate - translates a string via babelfish

=head1 SYNOPSIS

    translate B<-f> I<country-code> B<-t> I<country-code> 'string'

=head1 DESCRIPTION

    Translate will take a word or a string and translate to another language
    using babelfish.

=head1 OPTIONS

=over 4

=item -f 

    Language that we should translate from. You can use the following: 
    en (English), fr (French), de (German), it (Italien), es (Spanish), pt (Portugeese).

=item -t

    Language we should translate the word/string to. Same language codes as above.

=item -h

    Displays the help screen.

=back

=head1 CHANGELOG

    March 2003:
    o Add MAN page
    o Fix new babelfish semantics
    June 2002:
    o Initial release

=head1 BUGS

    Sometimes a translated string coming back from babelfish may contain special characters 
    (e.g. accents etc on fx. french words) which causes the screen to garble up.

=head1 AUTHOR

    Written by Michael L. Hostbaek <mich@freebsdcluster.org>

=cut

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

# check paramaters
    getopts('hf:t:');
    if (defined($opt_h)) {
	print "translate version 1.10
    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/babelfish/tr',[doit=>"done",intl=>"1",tt=>"urltext",Submit=>"Translate",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 =~ /<Div style=padding:10px;.*?>(.*?)<\/div>/si) { 
    $lort = $1; 
    $lort =~ s/\n//g;
}
print "[$convert_text] ---> $lort\n";
