#!/usr/bin/python
# -*- mode: Python; coding: utf-8; -*-

# PO file translation glossary generator
# 
# Pedro Morais <morais@kde.org>
# José Nuno Pires <jncp@netcabo.pt>
# (c) Copyright 2003, 2004
# Based on an idea by Kevin Donnelly <kevin@dotmon.com>
# Distributable under the terms of the GPL - see COPYING

import sys
import getopt
if not "@prefix@/share/@PACKAGE@" in sys.path:
    sys.path.append("@prefix@/share/@PACKAGE@")
from POFile import POFile
from util import Output

def usage(code = -1):
    w = sys.stderr.write
    w('Usage: POFileEquiv [OPTION] <FILE>...\n')
    w('\n')
    w('Mandatory arguments to long options are mandatory '
      'for short options too.\n')
    w('\n')
    w('Options:\n')
    w('  -h, --help                 show this help\n')
    w('  -m, --max=<number>         maximum number of translations to consider\n')
    w('  -o, --occurences=<number>  minimum number of occurences of a translation\n')
    w('  -r, --ratio=<ratio>        minimum ratio to consider\n')
    sys.exit(code)

try:
    opts, args = getopt.getopt(sys.argv[1:], "hm:o:r:",
                               ["help", "max=", "ratio="])
except getopt.GetoptError:
    usage()
max_words = -1
ratio = 0
occurences = 0
for o, a in opts:
    if o in ("-h", "--help"): usage(0)
    if o in ("-m", "--max"): max_words = int(a)
    if o in ("-o", "--occurences"): occurences = int(a)
    if o in ("-r", "--ratio"): ratio = int(a)
if len(args) < 1: usage()

equiv = {}
for filename in args:
    po = POFile(filename)
    if po.parse() == 0:
        sys.stderr.write('error parsing file %s\n' % filename)
    else:
        equiv = po.findEquiv(3, equiv)

out = Output("po-file-equiv")
for word, matches in equiv.iteritems():
    items = matches.items()
    if len(items) < 1: continue
    items.sort(lambda x, y: y[1] - x[1])
    localmax = items[0][1]
    line = max(occurences, localmax*ratio)
    if localmax < line: continue
    out.opentag('entry')
    out.opentag('original', body = word, close = 1)
    for m, c in items[:max_words]: 
        if c < line: break
        out.opentag('translation', { 'count': str(c) },
                    body = m, close = 1)
    out.closetag()
out.finish()
