#!/usr/bin/python
# encoding=UTF-8
# Copyright © 2008 Jakub Wilk <jwilk@jwilk.net>
#
# This package is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 dated June, 1991.
#
# This package is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.

if __name__ != '__main__':
    raise ImportError('This module is not intended for import')

import sys

import djvu.decode
import djvu.sexpr

try:
    import djvusmooth_importer
except ImportError:
    pass

from djvusmooth.text.mangle import import_, export

def do_export(djvu_file_name, page_no):
    context = djvu.decode.Context()
    document = context.new_document(djvu.decode.FileURI(djvu_file_name))
    text = djvu.decode.PageText(document.pages[page_no], details = djvu.decode.TEXT_DETAILS_WORD)
    text.wait()
    export(text.sexpr, sys.stdout)

def do_import(djvu_file_name, page_no):
    context = djvu.decode.Context()
    document = context.new_document(djvu.decode.FileURI(djvu_file_name))
    text = djvu.decode.PageText(document.pages[page_no], details = djvu.decode.TEXT_DETAILS_WORD)
    text.wait()
    print import_(text.sexpr, sys.stdin)

def main():
    from optparse import OptionParser
    oparser = OptionParser(usage = '%prog {--import | --export} --page N')
    oparser.add_option('-p', '--page', dest='page_no', action='store', type='int')
    oparser.add_option('-x', '--export', dest='action', action='store_const', const=do_export)
    oparser.add_option('-i', '--import', dest='action', action='store_const', const=do_import)
    options, [djvu_file_name] = oparser.parse_args()
    if options.action is None:
        oparser.error('No action specified')
    if options.page_no is None:
        oparser.error('No page specified')
    options.action(djvu_file_name, options.page_no - 1)


if __name__ == '__main__':
    main()

# vim:ts=4 sw=4 et
