#!/usr/bin/python

import urllib
import sys
import getopt

def translate(lang='en_it', text='bye'):
    '''translates sentences from source lang to dest lang'''

    url = urllib.URLopener()
    
    query = urllib.urlencode({'doit':'done', 'intl':'1', 'lp':lang, 'tt':'urltext', 'urltext':text})
    
    responde = url.open('http://babelfish.altavista.com/tr', query).read()

    start = responde.find('<div style=padding:10px;>') + 25
    stop = responde.find('</div>', start)

    return responde[start:stop]

####

if len(sys.argv) < 3 :
    print '''
        Usage: srttranslator.py <subtitle> <output> <options>

            where options can be:
                -s  source_language      (for example en for english or it for italian, by default en)
                -d destination_language  (for example en for english or it for italian, by default it)
                -e encoding              (the encoding used by babelfish for translations, by default ISO_8859-1)
                -f encoding              (the encoding used in the source srt file, by default ASCII)
    '''
    sys.exit(1)

source = 'en'
dest = 'it'
encoding = 'ISO_8859-1'
fencoding = 'ascii'
optlist, args = getopt.getopt(sys.argv[3:],"s:d:")
for o, a in optlist:
    if o == "-s":
        source = a
    if o == "-d":
        dest = a
    if o == '-e':
        encoding = a
    if o == '-f':
        fencoding = a

original = u''
fin = open(sys.argv[1], 'r')
line = unicode(fin.readline(), fencoding)
while len(line) > 0 :
    line = unicode(fin.readline(), fencoding)
    line = unicode(fin.readline(), fencoding)
    while len(line) > 1 and line[0] != '\r' and line[0] != '\n':
        line = line.replace('#', '%')
        original = original + ' # ' + line
        line = unicode(fin.readline(), fencoding)
    line = unicode(fin.readline(), fencoding)
fin.close()

translated = translate(source + '_' + dest, original)
translated = unicode(translated, encoding)
translated = translated.replace('\n', ' ')
tranlist = translated.split('#')

fin = open(sys.argv[1], 'r')
fout = open(sys.argv[2], 'w')
line = unicode(fin.readline(), fencoding)
i = 1
while len(line) > 0 :
    fout.write(line)
    line = unicode(fin.readline(), fencoding)
    fout.write(line)
    line = unicode(fin.readline(), fencoding)
    while len(line) > 1 and line[0] != '\r' and line[0] != '\n' :
        fout.write(tranlist[i].strip(' ').encode(encoding) + '\n')
        i = i + 1
        if i > len(tranlist) :
            print 'An error may have occurred'
            fout.close()
            sys.exit(0)
        line = unicode(fin.readline(), fencoding)
    fout.write(line)
    line = unicode(fin.readline(), fencoding)
fin.close()
fout.close()

