#!/usr/bin/env python

from __future__ import division

__version__ = "$Revision: 1.5 $"

import sys

import enstag as _enstag
import textinput

def enstag2ensid(filenames):
    for line in textinput.lines(filenames):
        for word in line.split():
            print "\t".join(processor(word)
                            for processor in options.processors)

def processor_enstag(enstag):
    return enstag

def processor_ensid(enstag):
    return _enstag.decode(enstag)

def processor_species(enstag):
    return _enstag.taxonomic_name(enstag)

def processor_feature_type(enstag):
    return _enstag.feature_fulltypes[_enstag.feature_type(enstag)]

def parse_options(args):
    from optik import OptionParser

    global options
    
    usage = "%prog [OPTION]... [FILE]..."
    version = "%%prog %s" % __version__
    parser = OptionParser(usage=usage, version=version)
    parser.add_option("-i", "--ensid", action="append_const",
                      dest="processors", const=processor_ensid)
    parser.add_option("-t", "--enstag", action="append_const",
                      dest="processors", const=processor_enstag)
    parser.add_option("-s", "--species", action="append_const",
                      dest="processors", const=processor_species)
    parser.add_option("-f", "--feature-type", action="append_const",
                      dest="processors", const=processor_feature_type)
    
    options, args = parser.parse_args(args)

    return args

def main(args):
    args = parse_options(args)

    if not options.processors:
        options.processors = [processor_enstag, processor_ensid,
                              processor_species, processor_feature_type]

    return enstag2ensid(args)

def _test(*args, **keywds):
    import doctest
    doctest.testmod(sys.modules[__name__], *args, **keywds)

if __name__ == "__main__":
    if __debug__:
        _test()
    sys.exit(main(sys.argv[1:]))
