[tryton-debian-vcs] relatorio branch debian created. fcedd4e1e20a3f345e1a60344787cd2608654aad

Mathias Behrle tryton-debian-vcs at alioth.debian.org
Wed Nov 27 16:48:56 UTC 2013


The following commit has been merged in the debian branch:
https://alioth.debian.org/plugins/scmgit/cgi-bin/gitweb.cgi/?p=tryton/relatorio.git;a=commitdiff;h=fcedd4e1e20a3f345e1a60344787cd2608654aad
commit fcedd4e1e20a3f345e1a60344787cd2608654aad
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Sun Nov 24 19:15:24 2013 +0100

    Updating to standards version 3.9.5, no changes needed.

diff --git a/debian/control b/debian/control
index 2fe81f5..59b7021 100644
--- a/debian/control
+++ b/debian/control
@@ -5,7 +5,7 @@ Maintainer: Debian Tryton Maintainers <maintainers at debian.tryton.org>
 Uploaders: Mathias Behrle <mathiasb at m9s.biz>
 Build-Depends:
  debhelper (>= 9), python (>= 2.6.6-3~), python-genshi, python-setuptools
-Standards-Version: 3.9.4
+Standards-Version: 3.9.5
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://debian.tryton.org/gitweb/?p=packages/relatorio.git
 Vcs-Git: git://debian.tryton.org/packages/relatorio.git
commit 1d7f9bc436d8c4deb8445984fca1e15fa928440e
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Thu Aug 15 12:03:23 2013 +0200

    Releasing debian version 0.6.0-1.

diff --git a/debian/changelog b/debian/changelog
index f3a8fb7..09112e2 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,9 @@
+relatorio (0.6.0-1) unstable; urgency=low
+
+  * Merging upstream version 0.6.0.
+
+ -- Mathias Behrle <mathiasb at m9s.biz>  Thu, 15 Aug 2013 11:44:05 +0200
+
 relatorio (0.5.7-3) unstable; urgency=low
 
   * Removing pydist-overrides, it is no more needed.
commit 29a2ed1077f9c8185b3435ebc2640e8eed32b6f3
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Thu Aug 15 11:34:17 2013 +0200

    Merging upstream version 0.6.0.

diff --git a/CHANGES b/CHANGES
index c466577..15bec1b 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,7 @@
+0.6.0 - 20130810
+ * Add support for Python 3
+ * Allow to pass only source to Template
+
 0.5.7 - 20130126
  * Allow string as bitstream for images
 
diff --git a/MANIFEST.in b/MANIFEST.in
index a72bf8f..9f38fae 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,3 +1,7 @@
 include AUTHORS
 include CHANGES
 include LICENSE
+include relatorio/tests/*.jpg
+include relatorio/tests/*.odt
+include relatorio/tests/*.png
+include relatorio/tests/templates/*.tmpl
diff --git a/PKG-INFO b/PKG-INFO
index 4ed7bfc..e112e9f 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
 Metadata-Version: 1.1
 Name: relatorio
-Version: 0.5.7
+Version: 0.6.0
 Summary: A templating library able to output odt and pdf files
 Home-page: http://relatorio.openhex.org/
 Author: Cedric Krier
@@ -22,6 +22,7 @@ Classifier: Development Status :: 4 - Beta
 Classifier: Intended Audience :: Developers
 Classifier: License :: OSI Approved :: GNU General Public License (GPL)
 Classifier: Operating System :: OS Independent
-Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 3
 Classifier: Topic :: Software Development :: Libraries :: Python Modules
 Classifier: Topic :: Text Processing
diff --git a/relatorio.egg-info/PKG-INFO b/relatorio.egg-info/PKG-INFO
index 4ed7bfc..e112e9f 100644
--- a/relatorio.egg-info/PKG-INFO
+++ b/relatorio.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
 Metadata-Version: 1.1
 Name: relatorio
-Version: 0.5.7
+Version: 0.6.0
 Summary: A templating library able to output odt and pdf files
 Home-page: http://relatorio.openhex.org/
 Author: Cedric Krier
@@ -22,6 +22,7 @@ Classifier: Development Status :: 4 - Beta
 Classifier: Intended Audience :: Developers
 Classifier: License :: OSI Approved :: GNU General Public License (GPL)
 Classifier: Operating System :: OS Independent
-Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 3
 Classifier: Topic :: Software Development :: Libraries :: Python Modules
 Classifier: Topic :: Text Processing
diff --git a/relatorio.egg-info/SOURCES.txt b/relatorio.egg-info/SOURCES.txt
index 99038ab..017f677 100644
--- a/relatorio.egg-info/SOURCES.txt
+++ b/relatorio.egg-info/SOURCES.txt
@@ -16,4 +16,15 @@ relatorio/templates/__init__.py
 relatorio/templates/base.py
 relatorio/templates/chart.py
 relatorio/templates/opendocument.py
-relatorio/templates/pdf.py
\ No newline at end of file
+relatorio/templates/pdf.py
+relatorio/tests/__init__.py
+relatorio/tests/egg.jpg
+relatorio/tests/one.jpg
+relatorio/tests/test.odt
+relatorio/tests/test_api.py
+relatorio/tests/test_odt.py
+relatorio/tests/two.png
+relatorio/tests/templates/include.tmpl
+relatorio/tests/templates/other.tmpl
+relatorio/tests/templates/test.tmpl
+relatorio/tests/templates/time.tmpl
\ No newline at end of file
diff --git a/relatorio/__init__.py b/relatorio/__init__.py
index cdd9d54..09888e1 100644
--- a/relatorio/__init__.py
+++ b/relatorio/__init__.py
@@ -12,4 +12,4 @@ and report together, find reports by mimetypes/name/python objects.
 from relatorio.reporting import MIMETemplateLoader, ReportRepository, Report
 import templates
 
-__version__ = '0.5.7'
+__version__ = '0.6.0'
diff --git a/relatorio/templates/base.py b/relatorio/templates/base.py
index 5a3d46c..2b69076 100644
--- a/relatorio/templates/base.py
+++ b/relatorio/templates/base.py
@@ -20,11 +20,6 @@
 
 __metaclass__ = type
 
-try:
-    from cStringIO import OutputType
-except ImportError:
-    from StringIO import StringIO as OutputType
-
 import genshi.core
 from genshi.template import NewTextTemplate, MarkupTemplate
 
@@ -46,12 +41,5 @@ class RelatorioStream(genshi.core.Stream):
         "Support for the bitwise operator"
         return RelatorioStream(self.events | function, self.serializer)
 
-    def __str__(self):
-        val = self.render()
-        if isinstance(val, OutputType):
-            return val.getvalue()
-        else:
-            return val
-
 MIMETemplateLoader.add_factory('text', NewTextTemplate)
 MIMETemplateLoader.add_factory('xml', MarkupTemplate)
diff --git a/relatorio/templates/opendocument.py b/relatorio/templates/opendocument.py
index 4f59972..159eff0 100644
--- a/relatorio/templates/opendocument.py
+++ b/relatorio/templates/opendocument.py
@@ -32,9 +32,12 @@ import time
 import urllib
 import zipfile
 try:
-    from cStringIO import StringIO
+    from io import BytesIO
 except ImportError:
-    from StringIO import StringIO
+    try:
+        from cStringIO import StringIO as BytesIO
+    except ImportError:
+        from StringIO import StringIO as BytesIO
 from copy import deepcopy
 import datetime
 from decimal import Decimal
@@ -130,7 +133,7 @@ class ImageHref:
         elif isinstance(bitstream, ChartTemplate):
             bitstream = bitstream.generate(**self.context).render()
         elif not hasattr(bitstream, 'seek') or not hasattr(bitstream, 'read'):
-            bitstream = StringIO(bitstream)
+            bitstream = BytesIO(bitstream)
         bitstream.seek(0)
         file_content = bitstream.read()
         name = md5(file_content).hexdigest()
@@ -237,6 +240,7 @@ class Template(MarkupTemplate):
         self.namespaces = {}
         self.inner_docs = []
         self.has_col_loop = False
+        self._zip_source = None
         super(Template, self).__init__(source, filepath, filename, loader,
                                        encoding, lookup, allow_exec)
 
@@ -245,7 +249,19 @@ class Template(MarkupTemplate):
 
         It adds genshi directives and finds the inner docs.
         """
-        zf = zipfile.ZipFile(self.filepath)
+        if not self.filepath:
+            if hasattr(source, 'read') and hasattr(source, 'mode'):
+                if 'U' in source.mode:
+                    # TemplateLoader of Genshi <= 0.6 open files with universal
+                    # newlines which is not suitable for zipfile
+                    raise ValueError('filepath is required '
+                        'if source is openned with universal newlines')
+                else:
+                    # source could be closed before generate calls
+                    source = BytesIO(source.read())
+        else:
+            source = self.filepath
+        self._zip_source = zf = zipfile.ZipFile(source)
         content = zf.read('content.xml')
         styles = zf.read('styles.xml')
 
@@ -268,7 +284,6 @@ class Template(MarkupTemplate):
             content_files.append((c_path, c_parsed))
             styles_files.append((s_path, s_parsed))
 
-        zf.close()
         parsed = []
         for fpath, fparsed in content_files + styles_files:
             parsed.append((genshi.core.PI, ('relatorio', fpath), None))
@@ -279,7 +294,7 @@ class Template(MarkupTemplate):
     def insert_directives(self, content):
         """adds the genshi directives, handle the images and the innerdocs.
         """
-        tree = lxml.etree.parse(StringIO(content))
+        tree = lxml.etree.parse(BytesIO(content))
         root = tree.getroot()
 
         # assign default/fake namespaces so that documents do not need to
@@ -306,7 +321,7 @@ class Template(MarkupTemplate):
         self._handle_images(tree)
         self._handle_innerdocs(tree)
         self._escape_values(tree)
-        return StringIO(lxml.etree.tostring(tree))
+        return BytesIO(lxml.etree.tostring(tree))
 
     def _invert_style(self, tree):
         "inverts the text:a and text:span"
@@ -692,7 +707,7 @@ class Template(MarkupTemplate):
 
     def generate(self, *args, **kwargs):
         "creates the RelatorioStream."
-        serializer = OOSerializer(self.filepath)
+        serializer = OOSerializer(self._zip_source)
         kwargs['__relatorio_make_href'] = ImageHref(serializer.outzip,
                                                     serializer.manifest,
                                                     kwargs)
@@ -752,13 +767,17 @@ class DuplicateColumnHeaders(object):
 class Manifest(object):
 
     def __init__(self, content):
-        self.tree = lxml.etree.parse(StringIO(content))
+        self.tree = lxml.etree.parse(BytesIO(content))
         self.root = self.tree.getroot()
         self.namespaces = self.root.nsmap
 
     def __str__(self):
-        return lxml.etree.tostring(self.tree, encoding='UTF-8',
-                                   xml_declaration=True)
+        val = lxml.etree.tostring(self.tree, encoding='UTF-8',
+                                  xml_declaration=True)
+        # In Python 3, val will be bytes
+        if not isinstance(val, str):
+            return str(val, 'utf-8')
+        return val
 
     def add_file_entry(self, path, mimetype=None):
         manifest_namespace = self.namespaces['manifest']
@@ -782,7 +801,7 @@ class Manifest(object):
 class Meta(object):
 
     def __init__(self, content):
-        self.tree = lxml.etree.parse(StringIO(content))
+        self.tree = lxml.etree.parse(BytesIO(content))
         root = self.tree.getroot()
         self.namespaces = root.nsmap
         path = '/office:document-meta/office:meta'
@@ -816,17 +835,21 @@ class Meta(object):
         self.remove('printed-by')
         self.remove('creator', 'dc')
         self.remove('date', 'dc')
-        return lxml.etree.tostring(self.tree, encoding='UTF-8',
-                                   xml_declaration=True)
+        val = lxml.etree.tostring(self.tree, encoding='UTF-8',
+                                  xml_declaration=True)
+        # In Python 3, val will be bytes
+        if not isinstance(val, str):
+            return str(val, 'utf-8')
+        return val
 
 
 class OOSerializer:
 
-    def __init__(self, oo_path):
-        self.inzip = zipfile.ZipFile(oo_path)
+    def __init__(self, inzip):
+        self.inzip = inzip
         self.manifest = Manifest(self.inzip.read(MANIFEST))
         self.meta = Meta(self.inzip.read(META))
-        self.new_oo = StringIO()
+        self.new_oo = BytesIO()
         self.outzip = zipfile.ZipFile(self.new_oo, 'w')
         self.xml_serializer = genshi.output.XMLSerializer()
 
@@ -850,7 +873,8 @@ class OOSerializer:
                 new_info = zipfile.ZipInfo(f_info.filename, now)
                 for attr in ('compress_type', 'flag_bits', 'create_system'):
                     setattr(new_info, attr, getattr(f_info, attr))
-                serialized_stream = output_encode(self.xml_serializer(stream))
+                serialized_stream = output_encode(self.xml_serializer(stream),
+                    encoding='utf-8')
                 self.outzip.writestr(new_info, serialized_stream)
             elif f_info.filename == MANIFEST:
                 manifest_info = f_info
@@ -863,7 +887,6 @@ class OOSerializer:
         self.manifest.remove_file_entry(THUMBNAILS + '/')
         if manifest_info:
             self.outzip.writestr(manifest_info, str(self.manifest))
-        self.inzip.close()
         self.outzip.close()
 
         return self.new_oo
diff --git a/relatorio/tests/__init__.py b/relatorio/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/relatorio/tests/egg.jpg b/relatorio/tests/egg.jpg
new file mode 100644
index 0000000..2700e16
Binary files /dev/null and b/relatorio/tests/egg.jpg differ
diff --git a/relatorio/tests/one.jpg b/relatorio/tests/one.jpg
new file mode 100644
index 0000000..48723f0
Binary files /dev/null and b/relatorio/tests/one.jpg differ
diff --git a/relatorio/tests/templates/include.tmpl b/relatorio/tests/templates/include.tmpl
new file mode 100644
index 0000000..cb46df8
--- /dev/null
+++ b/relatorio/tests/templates/include.tmpl
@@ -0,0 +1 @@
+{% include other.tmpl %}
diff --git a/relatorio/tests/templates/other.tmpl b/relatorio/tests/templates/other.tmpl
new file mode 100644
index 0000000..224a5d0
--- /dev/null
+++ b/relatorio/tests/templates/other.tmpl
@@ -0,0 +1 @@
+Another Hello.
diff --git a/relatorio/tests/templates/test.tmpl b/relatorio/tests/templates/test.tmpl
new file mode 100644
index 0000000..3b06a49
--- /dev/null
+++ b/relatorio/tests/templates/test.tmpl
@@ -0,0 +1 @@
+Hello ${o.name}.
diff --git a/relatorio/tests/templates/time.tmpl b/relatorio/tests/templates/time.tmpl
new file mode 100644
index 0000000..8467d56
--- /dev/null
+++ b/relatorio/tests/templates/time.tmpl
@@ -0,0 +1,2 @@
+Hi ${o.name},
+It's ${time} to ${func(y)} !
diff --git a/relatorio/tests/test.odt b/relatorio/tests/test.odt
new file mode 100644
index 0000000..6c3e196
Binary files /dev/null and b/relatorio/tests/test.odt differ
diff --git a/relatorio/tests/test_api.py b/relatorio/tests/test_api.py
new file mode 100644
index 0000000..11e8993
--- /dev/null
+++ b/relatorio/tests/test_api.py
@@ -0,0 +1,124 @@
+###############################################################################
+#
+# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
+# Reserved.
+#
+# This program 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; either version 3 of the License, or (at your option) any later
+# version.
+#
+# This program 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.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+###############################################################################
+
+
+import os
+from nose.tools import *
+
+from relatorio.reporting import (ReportRepository, Report, MIMETemplateLoader,
+                                 DefaultFactory, _absolute, _guess_type)
+
+
+class StubObject(object):
+
+    def __init__(self, **kwargs):
+        for key, val in kwargs.iteritems():
+            setattr(self, key, val)
+
+
+class TestRepository(object):
+
+    def test_register(self):
+        "Testing the registration"
+        reporting = ReportRepository()
+        reporting.add_report(StubObject, 'text/plain',
+                             os.path.join('templates', 'test.tmpl'),
+                             description='Test report')
+
+        assert_true(StubObject in reporting.classes)
+        assert_true('default' in reporting.classes[StubObject].ids)
+        assert_true('text/plain' in reporting.classes[StubObject].mimetypes)
+
+        report, mime, desc = reporting.classes[StubObject].ids['default']
+        eq_(mime, 'text/plain')
+        eq_(desc, 'Test report')
+        eq_(report.mimetype, 'text/plain')
+        assert_true(report.fpath.endswith(os.path.join('templates',
+                                                       'test.tmpl')))
+
+        report2, name = (reporting.classes[StubObject]
+                         .mimetypes['text/plain'][0])
+        eq_(name, 'default')
+        eq_(report, report2)
+
+    def test_mimeguesser(self):
+        eq_(_guess_type('application/pdf'), 'pdf')
+        eq_(_guess_type('text/plain'), 'text')
+        eq_(_guess_type('text/xhtml'), 'markup')
+        eq_(_guess_type('application/vnd.oasis.opendocument.text'), 'oo.org')
+
+    def abspath_helper(self, path):
+        return _absolute(path)
+
+    def test_absolute(self):
+        "Test the absolute path calculation"
+        eq_("/home/nicoe/python/mock.py",
+            _absolute("/home/nicoe/python/mock.py"))
+
+        our_dir, _ = os.path.split(__file__)
+        # We use this because me go up by two frames
+        new_path = self.abspath_helper(os.path.join('brol', 'toto'))
+        eq_(os.path.join(our_dir, 'brol', 'toto'), new_path)
+
+
+class TestReport(object):
+
+    def setup(self):
+        self.loader = MIMETemplateLoader()
+        our_dir, _ = os.path.split(__file__)
+        self.report = Report(os.path.join(our_dir, 'templates', 'test.tmpl'),
+                             'text/plain', DefaultFactory(), self.loader)
+
+    def test_report(self):
+        "Testing the report generation"
+        a = StubObject(name='OpenHex')
+        eq_(self.report(o=a).render(), 'Hello OpenHex.\n')
+
+    def test_factory(self):
+        "Testing the data factory"
+        class MyFactory:
+            def __call__(self, o, time, y=1):
+                d = dict()
+                d['o'] = o
+                d['y'] = y
+                d['time'] = time
+                d['func'] = lambda x: x + 1
+                return d
+
+        our_dir, _ = os.path.split(__file__)
+        report = Report(os.path.join(our_dir, 'templates', 'time.tmpl'),
+                        'text/plain', MyFactory(), self.loader)
+
+        a = StubObject(name='Foo')
+        eq_(report(o=a, time="One o'clock").render(),
+            "Hi Foo,\nIt's One o'clock to 2 !\n")
+        eq_(report(o=a, time="One o'clock", y=4).render(),
+            "Hi Foo,\nIt's One o'clock to 5 !\n")
+        assert_raises(TypeError, report, a)
+
+
+class TestReportInclude(object):
+
+    def test_include(self):
+        our_dir = os.path.dirname(__file__)
+        template_path = os.path.join(our_dir, 'templates')
+        relative_report = Report(os.path.join(template_path, 'include.tmpl'),
+                                 'text/plain')
+        eq_(relative_report().render(), 'Another Hello.\n\n')
diff --git a/relatorio/tests/test_odt.py b/relatorio/tests/test_odt.py
new file mode 100644
index 0000000..2d982ff
--- /dev/null
+++ b/relatorio/tests/test_odt.py
@@ -0,0 +1,312 @@
+# -*- encoding: utf-8 -*-
+###############################################################################
+#
+# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
+# Reserved.
+#
+# This program 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; either version 3 of the License, or (at your option) any later
+# version.
+#
+# This program 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.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+###############################################################################
+
+
+import os
+try:
+    from cStringIO import StringIO
+except ImportError:
+    from StringIO import StringIO
+
+import lxml.etree
+from nose.tools import *
+from genshi.filters import Translator
+from genshi.core import PI
+from genshi.template.eval import UndefinedError
+
+from relatorio.templates.opendocument import Template, GENSHI_EXPR,\
+    GENSHI_URI, RELATORIO_URI
+
+OO_TABLE_NS = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"
+
+
+def pseudo_gettext(string):
+    catalog = {'Mes collègues sont:': 'My colleagues are:',
+               'Bonjour,': 'Hello,',
+               'Je suis un test de templating en odt.':
+                'I am an odt templating test',
+               'Felix da housecat': u'Félix le chat de la maison',
+               'We sell stuff': u'On vend des choses',
+              }
+    return catalog.get(string, string)
+
+def stream_to_string(stream):
+    # In Python 3, stream will be bytes
+    if not isinstance(stream, str):
+        return str(stream, 'utf-8')
+    return stream
+
+
+class TestOOTemplating(object):
+
+    def setup(self):
+        thisdir = os.path.dirname(__file__)
+        filepath = os.path.join(thisdir, 'test.odt')
+        self.oot = Template(open(filepath, mode='rb'))
+        self.data = {'first_name': u'Trente',
+                     'last_name': u'Møller',
+                     'ville': u'Liège',
+                     'friends': [{'first_name': u'Camille',
+                                  'last_name': u'Salauhpe'},
+                                 {'first_name': u'Mathias',
+                                  'last_name': u'Lechat'}],
+                     'hobbies': [u'Music', u'Dancing', u'DJing'],
+                     'animals': [u'Felix da housecat', u'Dog eat Dog'],
+                     'images': [(open(os.path.join(thisdir, 'one.jpg'), 'rb'),
+                                 'image/jpeg'),
+                                (open(os.path.join(thisdir, 'two.png'), 'rb'),
+                                 'image/png')],
+                     'oeuf': open(os.path.join(thisdir, 'egg.jpg'), 'rb'),
+                     'footer': u'We sell stuff'}
+
+    def test_init(self):
+        "Testing the correct handling of the styles.xml and content.xml files"
+        ok_(isinstance(self.oot.stream, list))
+        eq_(self.oot.stream[0], (PI, ('relatorio', 'content.xml'), None))
+        ok_((PI, ('relatorio', 'content.xml'), None) in self.oot.stream)
+
+    def test_directives(self):
+        "Testing the directives interpolation"
+        xml = b'''<xml xmlns:text="urn:text" xmlns:xlink="urn:xlink">
+                    <text:a xlink:href="relatorio://foo">foo</text:a>
+                 </xml>'''
+        interpolated = self.oot.insert_directives(xml)
+        root_interpolated = lxml.etree.parse(interpolated).getroot()
+        child = root_interpolated[0]
+        eq_(child.get('{http://genshi.edgewall.org/}replace'), 'foo')
+
+    def test_column_looping(self):
+        xml = b'''
+<table:table
+    xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
+    xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+    xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
+    xmlns:xlink="http://www.w3.org/1999/xlink"
+    table:name="Tableau1"
+    table:style-name="Tableau1">
+    <table:table-column table:style-name="Tableau1.A"
+                        table:number-columns-repeated="2"/>
+    <table:table-column table:style-name="Tableau1.C"/>
+    <table:table-column table:style-name="Tableau1.A"/>
+    <table:table-column table:style-name="Tableau1.E"/>
+    <table:table-header-rows>
+        <table:table-row table:style-name="Tableau1.1">
+            <table:table-cell table:style-name="Tableau1.A1"
+                              office:value-type="string">
+                <text:p text:style-name="Table_20_Heading">Brol</text:p>
+            </table:table-cell>
+            <table:table-cell table:style-name="Tableau1.A1"
+                              office:value-type="string">
+                <text:p text:style-name="Table_20_Heading">
+                    <text:a xlink:type="simple"
+                            xlink:href="relatorio://for each="title in titles"">for each="title in titles"</text:a>
+                </text:p>
+            </table:table-cell>
+            <table:table-cell table:style-name="Tableau1.A1"
+                              office:value-type="string">
+                <text:p text:style-name="Table_20_Heading">${title}</text:p>
+                <text:p text:style-name="Table_20_Heading"/>
+            </table:table-cell>
+            <table:table-cell table:style-name="Tableau1.A1"
+                              office:value-type="string">
+                <text:p text:style-name="Table_20_Heading">
+                    <text:a xlink:type="simple"
+                            xlink:href="relatorio:///for">/for</text:a>
+                </text:p>
+            </table:table-cell>
+            <table:table-cell table:style-name="Tableau1.E1"
+                              office:value-type="string">
+                <text:p text:style-name="Table_20_Heading">Truc</text:p>
+            </table:table-cell>
+        </table:table-row>
+    </table:table-header-rows>
+    <table:table-row>
+        <table:table-cell table:style-name="Tableau1.A2"
+                          table:number-columns-spanned="5"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">
+                <text:a xlink:type="simple"
+                        xlink:href="relatorio://for%20each=%22items%20in%20lst%22">for each="items in lst"</text:a>
+            </text:p>
+        </table:table-cell>
+        <table:covered-table-cell/>
+        <table:covered-table-cell/>
+        <table:covered-table-cell/>
+        <table:covered-table-cell/>
+    </table:table-row>
+    <table:table-row>
+        <table:table-cell table:style-name="Tableau1.A3"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">Brol</text:p>
+        </table:table-cell>
+        <table:table-cell table:style-name="Tableau1.A3"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">
+                <text:a xlink:type="simple"
+                        xlink:href="relatorio://for%20each=%22item%20in%20items%22">for each="item in items"</text:a>
+            </text:p>
+        </table:table-cell>
+        <table:table-cell table:style-name="Tableau1.A3"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">${item}</text:p>
+            <text:p text:style-name="Table_20_Contents"/>
+        </table:table-cell>
+        <table:table-cell table:style-name="Tableau1.A3"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">
+                <text:a xlink:type="simple"
+                        xlink:href="relatorio:///for">/for</text:a>
+            </text:p>
+        </table:table-cell>
+        <table:table-cell table:style-name="Tableau1.A2"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">Truc</text:p>
+        </table:table-cell>
+    </table:table-row>
+    <table:table-row>
+        <table:table-cell table:style-name="Tableau1.A2"
+                          table:number-columns-spanned="5"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">
+                <text:a xlink:type="simple"
+                        xlink:href="relatorio:///for">/for</text:a>
+            </text:p>
+        </table:table-cell>
+        <table:covered-table-cell/>
+        <table:covered-table-cell/>
+        <table:covered-table-cell/>
+        <table:covered-table-cell/>
+    </table:table-row>
+</table:table>'''
+        interpolated = self.oot.insert_directives(xml)
+        root = lxml.etree.parse(interpolated).getroot()
+        child2 = root[1]
+        eq_(child2.tag, "{%s}repeat" % RELATORIO_URI)
+        eq_(child2.get("closing"), "3")
+        eq_(child2.get("opening"), "1")
+        eq_(len(child2), 1)
+        child4 = root[3]
+        eq_(child4.tag, "{%s}table-header-rows" % OO_TABLE_NS)
+        row1 = child4[0]
+        ok_(row1.get("{%s}attrs" % GENSHI_URI)
+                .startswith('__relatorio_reset_col_count'))
+        eq_(len(row1), 4)
+        loop = row1[1]
+        eq_(loop.tag, "{%s}for" % GENSHI_URI)
+        cell = loop[0]
+        ok_(cell.get("{%s}attrs" % GENSHI_URI)
+                .startswith('__relatorio_inc_col_count'))
+        last_row_node = row1[3]
+        eq_(last_row_node.tag, "{%s}replace" % GENSHI_URI)
+        ok_(last_row_node.get("value")
+                         .startswith('__relatorio_store_col_count'))
+
+    def test_text_outside_p(self):
+        "Testing that the tail text of a directive node is handled properly"
+        xml = b'''<xml xmlns:text="urn:text" xmlns:xlink="urn:xlink">
+                    <text:a xlink:href="relatorio://if%20test=%22True%22">if test="True"</text:a>
+                    xxx
+                    <text:p text:style-name="other">yyy</text:p>
+                    zzz
+                    <text:a xlink:href="relatorio:///if">/if</text:a>
+                    aaa
+                 </xml>'''
+        interpolated = self.oot.insert_directives(xml)
+        root_interpolated = lxml.etree.parse(interpolated).getroot()
+        child = root_interpolated[0]
+        eq_(child.tag, '{http://genshi.edgewall.org/}if')
+        eq_(child.text.strip(), 'xxx')
+        eq_(child.tail.strip(), 'aaa')
+
+    def test_styles(self):
+        "Testing that styles get rendered"
+        stream = self.oot.generate(**self.data)
+        rendered = stream_to_string(stream.events.render(encoding='utf-8'))
+        ok_('We sell stuff' in rendered)
+
+        dico = self.data.copy()
+        del dico['footer']
+        stream = self.oot.generate(**dico)
+        assert_raises(UndefinedError,
+            lambda: stream.events.render(encoding='utf-8'))
+
+    def test_generate(self):
+        "Testing that content get rendered"
+        stream = self.oot.generate(**self.data)
+        rendered = stream_to_string(stream.events.render(encoding='utf-8'))
+        ok_('Bonjour,' in rendered)
+        ok_('Trente' in rendered)
+        ok_('Møller' in rendered)
+        ok_('Dog eat Dog' in rendered)
+        ok_('Felix da housecat' in rendered)
+
+    def test_filters(self):
+        "Testing the filters with the Translator filter"
+        stream = self.oot.generate(**self.data)
+        translated = stream.filter(Translator(pseudo_gettext))
+        translated_xml = stream_to_string(
+            translated.events.render(encoding='utf-8'))
+        ok_("Hello," in translated_xml)
+        ok_("I am an odt templating test" in translated_xml)
+        ok_('Felix da housecat' not in translated_xml)
+        ok_('Félix le chat de la maison' in translated_xml)
+        ok_('We sell stuff' not in translated_xml)
+        ok_('On vend des choses' in translated_xml)
+
+    def test_images(self):
+        "Testing the image replacement directive"
+        stream = self.oot.generate(**self.data)
+        rendered = stream_to_string(stream.events.render(encoding='utf-8'))
+        styles_idx = rendered.find('<?relatorio styles.xml?>')
+        tree = lxml.etree.parse(StringIO(rendered[25:styles_idx]))
+        root = tree.getroot()
+        images = root.xpath('//draw:frame', namespaces=self.oot.namespaces)
+        eq_(len(images), 3)
+        eq_(images[0].get('{%s}name' % self.oot.namespaces['draw']), "")
+        eq_(images[1].get('{%s}name' % self.oot.namespaces['draw']), '')
+        eq_(images[1].get('{%s}width' % self.oot.namespaces['svg']),
+            '1.732cm')
+        eq_(images[1].get('{%s}height' % self.oot.namespaces['svg']),
+            '1.513cm')
+        eq_(images[2].get('{%s}width' % self.oot.namespaces['svg']),
+            '1.732cm')
+        eq_(images[2].get('{%s}height' % self.oot.namespaces['svg']),
+            '1.513cm')
+
+    def test_regexp(self):
+        "Testing the regexp used to find relatorio tags"
+        # a valid expression
+        group = GENSHI_EXPR.match('for each="foo in bar"').groups()
+        eq_(group, (None, 'for', 'each', 'foo in bar'))
+
+        # invalid expr
+        group = GENSHI_EXPR.match('foreach="foo in bar"').groups()
+        eq_(group, (None, None, None, None))
+
+        # valid closing tags
+        group = GENSHI_EXPR.match('/for').groups()
+        eq_(group, ('/', 'for', None, None))
+        group = GENSHI_EXPR.match('/for ').groups()
+        eq_(group, ('/', 'for', None, None))
+
+        # another non matching expr
+        group = GENSHI_EXPR.match('formatLang("en")').groups()
+        eq_(group, (None, None, None, None))
diff --git a/relatorio/tests/two.png b/relatorio/tests/two.png
new file mode 100644
index 0000000..f7d65d5
Binary files /dev/null and b/relatorio/tests/two.png differ
diff --git a/setup.py b/setup.py
index ef10e1a..f342bf6 100644
--- a/setup.py
+++ b/setup.py
@@ -12,7 +12,7 @@ setup(
     url="http://relatorio.openhex.org/",
     author="Nicolas Evrard",
     author_email="nicoe at openhex.org",
-    maintainer=u"Cedric Krier",
+    maintainer="Cedric Krier",
     maintainer_email="cedric.krier at b2ck.com",
     description="A templating library able to output odt and pdf files",
     long_description="""
@@ -28,7 +28,10 @@ and report together, find reports by mimetypes/name/python objects.
     """,
     license="GPL License",
     version=get_version(),
-    packages=find_packages(exclude=['relatorio.tests', 'examples']),
+    packages=find_packages(exclude=['examples']),
+    package_data={
+        'relatorio.tests': ['*.jpg', '*.odt', '*.png', 'templates/*.tmpl'],
+        },
     install_requires=[
         "Genshi >= 0.5",
         "lxml >= 2.0"
@@ -38,9 +41,13 @@ and report together, find reports by mimetypes/name/python objects.
         "Intended Audience :: Developers",
         "License :: OSI Approved :: GNU General Public License (GPL)",
         "Operating System :: OS Independent",
-        "Programming Language :: Python",
+        "Programming Language :: Python :: 2",
+        "Programming Language :: Python :: 3",
         "Topic :: Software Development :: Libraries :: Python Modules",
         "Topic :: Text Processing",
     ],
     test_suite="nose.collector",
-    )
+    tests_require=[
+        "nose",
+    ],
+    use_2to3=True)
commit ea34f8f6d61b02d83d1ac6206dbf55856a5b4582
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Tue Aug 6 16:20:36 2013 +0200

    Releasing debian version 0.5.7-3.

diff --git a/debian/changelog b/debian/changelog
index 595ad50..f3a8fb7 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,10 @@
+relatorio (0.5.7-3) unstable; urgency=low
+
+  * Removing pydist-overrides, it is no more needed.
+  * Adapting the rules file to work also with git-buildpackage.
+
+ -- Mathias Behrle <mathiasb at m9s.biz>  Tue, 06 Aug 2013 13:31:57 +0200
+
 relatorio (0.5.7-2) unstable; urgency=low
 
   * Removing Daniel from Uploaders. Thanks for your work! (Closes: #704357).
commit 7e82d6b3b5368e3ce2dc451eca3e9ed1d9257377
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Mon Aug 5 18:12:00 2013 +0200

    Adapting the rules file to work also with git-buildpackage.

diff --git a/debian/rules b/debian/rules
index b918925..63f539a 100755
--- a/debian/rules
+++ b/debian/rules
@@ -1,11 +1,23 @@
 #!/usr/bin/make -f
 
+PACKAGE_NAME := $(shell python setup.py --name)
+
 %:
 	dh ${@} --with python2
 
 override_dh_auto_clean:
 	dh_auto_clean
+
+override_dh_auto_build:
+	mv $(PACKAGE_NAME).egg-info $(PACKAGE_NAME).hen-info
+	mv PKG-INFO PKG-INFO.hen
+	dh_auto_build
+
+override_dh_auto_install:
+	dh_auto_install
 	rm -rf *.egg-info
+	mv $(PACKAGE_NAME).hen-info $(PACKAGE_NAME).egg-info
+	mv PKG-INFO.hen PKG-INFO
 
 override_dh_builddeb:
 	dh_builddeb -- -Zxz -z9
commit fbb06c7f0c876d99e40343c9e4a18015b5ef59a3
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Mon Aug 5 14:04:41 2013 +0200

    Removing pydist-overrides, it is no more needed.

diff --git a/debian/pydist-overrides b/debian/pydist-overrides
deleted file mode 100644
index 85771df..0000000
--- a/debian/pydist-overrides
+++ /dev/null
@@ -1 +0,0 @@
-lxml python-lxml
commit 1578750e1879a8384a6d6c499a021f7694df2820
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Fri May 31 20:26:48 2013 +0200

    Releasing debian version 0.5.7-2.

diff --git a/debian/changelog b/debian/changelog
index 9ddd4ba..595ad50 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,10 @@
+relatorio (0.5.7-2) unstable; urgency=low
+
+  * Removing Daniel from Uploaders. Thanks for your work! (Closes: #704357).
+  * Removing needless empty line in rules.
+
+ -- Mathias Behrle <mathiasb at m9s.biz>  Fri, 31 May 2013 15:11:57 +0200
+
 relatorio (0.5.7-1) experimental; urgency=low
 
   * Removing obsolete Dm-Upload-Allowed
commit aceb833f33c85debab668ce9191e2cf7dfbef990
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Wed May 29 17:19:29 2013 +0200

    Removing needless empty line in rules.

diff --git a/debian/rules b/debian/rules
index 1ae0776..b918925 100755
--- a/debian/rules
+++ b/debian/rules
@@ -5,7 +5,6 @@
 
 override_dh_auto_clean:
 	dh_auto_clean
-
 	rm -rf *.egg-info
 
 override_dh_builddeb:
commit af8fcb295d575e4e0cd8f26962626acbfe62ac1f
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Sun Apr 21 23:20:56 2013 +0200

    Removing Daniel from Uploaders. Thanks for your work! (Closes: #704357).

diff --git a/debian/control b/debian/control
index 976367a..2fe81f5 100644
--- a/debian/control
+++ b/debian/control
@@ -2,7 +2,7 @@ Source: relatorio
 Section: python
 Priority: optional
 Maintainer: Debian Tryton Maintainers <maintainers at debian.tryton.org>
-Uploaders: Daniel Baumann <daniel at debian.org>, Mathias Behrle <mathiasb at m9s.biz>
+Uploaders: Mathias Behrle <mathiasb at m9s.biz>
 Build-Depends:
  debhelper (>= 9), python (>= 2.6.6-3~), python-genshi, python-setuptools
 Standards-Version: 3.9.4
commit 216cf3185b951a44ddc8f5861dee3bf448a0c38e
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Sun Feb 24 15:06:42 2013 +0100

    Releasing debian version 0.5.7-1.

diff --git a/debian/changelog b/debian/changelog
index df7532d..9ddd4ba 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,14 @@
+relatorio (0.5.7-1) experimental; urgency=low
+
+  * Removing obsolete Dm-Upload-Allowed
+  * Updating to Standards-Version: 3.9.4, no changes needed.
+  * Updating Vcs-Git to correct address.
+  * Adding watch file.
+  * Merging upstream version 0.5.7.
+  * Updating copyright.
+
+ -- Mathias Behrle <mathiasb at m9s.biz>  Sun, 24 Feb 2013 14:17:28 +0100
+
 relatorio (0.5.6-2) unstable; urgency=low
 
   [ Mathias Behrle ]
commit 2e3604bb98bc6cc45c14bbd8aa8d9683c47d5f1a
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Sun Feb 24 14:15:54 2013 +0100

    Updating copyright.

diff --git a/debian/copyright b/debian/copyright
index a65acfc..6e27b2d 100644
--- a/debian/copyright
+++ b/debian/copyright
@@ -6,12 +6,12 @@ License: GPL-3+
 
 Files: relatorio/templates/opendocument.py
 Copyright: 2007-2008 OpenHex SPRL <http://www.openhex.com/>
-           2009 Cedric Krier
+           2009-2013 Cedric Krier
 License: GPL-3+
 
 Files: debian/*
 Copyright: 2009-2012 Daniel Baumann <daniel at debian.org>
-           2012 Mathias Behrle <mathiasb at m9s.biz>
+           2012-2013 Mathias Behrle <mathiasb at m9s.biz>
 License: GPL-3+
 
 License: GPL-3+
commit 22dfbcb0a8693a96731a035a7c66a421966d5a34
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Sun Feb 24 14:12:14 2013 +0100

    Merging upstream version 0.5.7.

diff --git a/CHANGES b/CHANGES
index 00f42e2..c466577 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,6 @@
+0.5.7 - 20130126
+ * Allow string as bitstream for images
+
 0.5.6 - 20120223
  * Add expression cache to prevent multiple evaluation of the same expression
  * Fix typo when writing manifest
diff --git a/PKG-INFO b/PKG-INFO
index 02b646a..4ed7bfc 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
-Metadata-Version: 1.0
+Metadata-Version: 1.1
 Name: relatorio
-Version: 0.5.6
+Version: 0.5.7
 Summary: A templating library able to output odt and pdf files
 Home-page: http://relatorio.openhex.org/
 Author: Cedric Krier
diff --git a/relatorio.egg-info/PKG-INFO b/relatorio.egg-info/PKG-INFO
index 02b646a..4ed7bfc 100644
--- a/relatorio.egg-info/PKG-INFO
+++ b/relatorio.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
-Metadata-Version: 1.0
+Metadata-Version: 1.1
 Name: relatorio
-Version: 0.5.6
+Version: 0.5.7
 Summary: A templating library able to output odt and pdf files
 Home-page: http://relatorio.openhex.org/
 Author: Cedric Krier
diff --git a/relatorio/__init__.py b/relatorio/__init__.py
index eced3e4..cdd9d54 100644
--- a/relatorio/__init__.py
+++ b/relatorio/__init__.py
@@ -12,4 +12,4 @@ and report together, find reports by mimetypes/name/python objects.
 from relatorio.reporting import MIMETemplateLoader, ReportRepository, Report
 import templates
 
-__version__ = '0.5.6'
+__version__ = '0.5.7'
diff --git a/relatorio/templates/opendocument.py b/relatorio/templates/opendocument.py
index a7aa8c6..4f59972 100644
--- a/relatorio/templates/opendocument.py
+++ b/relatorio/templates/opendocument.py
@@ -1,6 +1,6 @@
 ###############################################################################
 #
-# Copyright (c) 2009 Cedric Krier.
+# Copyright (c) 2009-2013 Cedric Krier.
 # Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
 # Reserved.
 #
@@ -37,6 +37,7 @@ except ImportError:
     from StringIO import StringIO
 from copy import deepcopy
 import datetime
+from decimal import Decimal
 
 
 import warnings
@@ -51,7 +52,6 @@ from genshi.filters.transform import ENTER, EXIT
 from genshi.core import Stream
 from genshi.template.interpolation import PREFIX
 
-#from relatorio import __version__ as VERSION
 import relatorio
 from relatorio.templates.base import RelatorioStream
 from relatorio.reporting import Report, MIMETemplateLoader
@@ -107,7 +107,7 @@ EtreeElement = lxml.etree.Element
 def guess_type(val):
     if isinstance(val, (str, unicode)):
         return 'string'
-    elif isinstance(val, (int, float, long)):
+    elif isinstance(val, (int, float, long, Decimal)):
         return 'float'
 
 
@@ -129,6 +129,8 @@ class ImageHref:
             bitstream = bitstream(**self.context).render()
         elif isinstance(bitstream, ChartTemplate):
             bitstream = bitstream.generate(**self.context).render()
+        elif not hasattr(bitstream, 'seek') or not hasattr(bitstream, 'read'):
+            bitstream = StringIO(bitstream)
         bitstream.seek(0)
         file_content = bitstream.read()
         name = md5(file_content).hexdigest()
commit 305d3f9de9aad514f9d575851aa82a3dfbf2f61f
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Sun Feb 24 13:06:56 2013 +0100

    Adding watch file.

diff --git a/debian/watch b/debian/watch
new file mode 100644
index 0000000..dfade28
--- /dev/null
+++ b/debian/watch
@@ -0,0 +1,2 @@
+version=3
+http://pypi.python.org/packages/source/r/relatorio/relatorio-(\d+.*)\.(?:tgz|tbz2|txz|tar\.(?:gz|bz2|xz)) 
commit a5121435e18715cc968716cadb1eb578ca641525
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Sat Feb 23 20:08:07 2013 +0100

    Updating Vcs-Git to correct address.

diff --git a/debian/control b/debian/control
index cee769b..976367a 100644
--- a/debian/control
+++ b/debian/control
@@ -8,7 +8,7 @@ Build-Depends:
 Standards-Version: 3.9.4
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://debian.tryton.org/gitweb/?p=packages/relatorio.git
-Vcs-Git: git://debian.tryton.org/git/packages/relatorio.git
+Vcs-Git: git://debian.tryton.org/packages/relatorio.git
 X-Python-Version: >= 2.4
 
 Package: python-relatorio
commit bae1d53c19119c73a6bcac77b764f51c43b39e60
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Fri Feb 15 19:28:24 2013 +0100

    Updating to Standards-Version: 3.9.4, no changes needed.

diff --git a/debian/control b/debian/control
index 39410f8..cee769b 100644
--- a/debian/control
+++ b/debian/control
@@ -5,7 +5,7 @@ Maintainer: Debian Tryton Maintainers <maintainers at debian.tryton.org>
 Uploaders: Daniel Baumann <daniel at debian.org>, Mathias Behrle <mathiasb at m9s.biz>
 Build-Depends:
  debhelper (>= 9), python (>= 2.6.6-3~), python-genshi, python-setuptools
-Standards-Version: 3.9.3
+Standards-Version: 3.9.4
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://debian.tryton.org/gitweb/?p=packages/relatorio.git
 Vcs-Git: git://debian.tryton.org/git/packages/relatorio.git
commit b461f2ee956c435df45b39e12febab434196f2e8
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Wed Feb 13 21:37:13 2013 +0100

    Removing obsolete Dm-Upload-Allowed

diff --git a/debian/control b/debian/control
index 6311454..39410f8 100644
--- a/debian/control
+++ b/debian/control
@@ -3,7 +3,6 @@ Section: python
 Priority: optional
 Maintainer: Debian Tryton Maintainers <maintainers at debian.tryton.org>
 Uploaders: Daniel Baumann <daniel at debian.org>, Mathias Behrle <mathiasb at m9s.biz>
-Dm-Upload-Allowed: yes
 Build-Depends:
  debhelper (>= 9), python (>= 2.6.6-3~), python-genshi, python-setuptools
 Standards-Version: 3.9.3
commit 77cbb2daefb69ac9ee8df0c1ada96cbcb0b245df
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat Jun 30 17:20:54 2012 +0200

    Releasing debian version 0.5.6-2.

diff --git a/debian/changelog b/debian/changelog
index 103fd3e..df7532d 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,18 @@
+relatorio (0.5.6-2) unstable; urgency=low
+
+  [ Mathias Behrle ]
+  * Updating to Standards-Version: 3.9.3, no changes needed.
+  * Adding Format header for DEP5.
+
+  [ Daniel Baumann ]
+  * Updating maintainers field.
+  * Updating vcs fields.
+  * Switching to xz compression.
+  * Updating to debhelper version 9.
+  * Correcting copyright file to match format version 1.0.
+
+ -- Daniel Baumann <daniel at debian.org>  Sat, 30 Jun 2012 17:20:34 +0200
+
 relatorio (0.5.6-1) unstable; urgency=low
 
   * Updating copyright file.
commit 86007b7d004cb5a83ad437fb096c333b3161c345
Author: Daniel Baumann <daniel at 127011.net>
Date:   Sat Jun 30 17:01:29 2012 +0200

    Correcting copyright file to match format version 1.0.

diff --git a/debian/copyright b/debian/copyright
index 567fd39..a65acfc 100644
--- a/debian/copyright
+++ b/debian/copyright
@@ -1,20 +1,17 @@
 Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
 
 Files: *
-Copyright:
- (C) 2007-2008 OpenHex SPRL <http://www.openhex.com/>
+Copyright: 2007-2008 OpenHex SPRL <http://www.openhex.com/>
 License: GPL-3+
 
 Files: relatorio/templates/opendocument.py
-Copyright:
- (C) 2007-2008 OpenHex SPRL <http://www.openhex.com/>
- (C) 2009 Cedric Krier
+Copyright: 2007-2008 OpenHex SPRL <http://www.openhex.com/>
+           2009 Cedric Krier
 License: GPL-3+
 
 Files: debian/*
-Copyright:
- (C) 2009-2012 Daniel Baumann <daniel at debian.org>
- (C) 2012 Mathias Behrle <mathiasb at m9s.biz>
+Copyright: 2009-2012 Daniel Baumann <daniel at debian.org>
+           2012 Mathias Behrle <mathiasb at m9s.biz>
 License: GPL-3+
 
 License: GPL-3+
commit 1d5a9e61654685e6617db29e97c6808e493fc619
Author: Daniel Baumann <daniel at 127011.net>
Date:   Sat Jun 30 17:01:29 2012 +0200

    Updating to debhelper version 9.

diff --git a/debian/compat b/debian/compat
index 45a4fb7..ec63514 100644
--- a/debian/compat
+++ b/debian/compat
@@ -1 +1 @@
-8
+9
diff --git a/debian/control b/debian/control
index 503d9b6..6311454 100644
--- a/debian/control
+++ b/debian/control
@@ -5,7 +5,7 @@ Maintainer: Debian Tryton Maintainers <maintainers at debian.tryton.org>
 Uploaders: Daniel Baumann <daniel at debian.org>, Mathias Behrle <mathiasb at m9s.biz>
 Dm-Upload-Allowed: yes
 Build-Depends:
- debhelper (>= 8), python (>= 2.6.6-3~), python-genshi, python-setuptools
+ debhelper (>= 9), python (>= 2.6.6-3~), python-genshi, python-setuptools
 Standards-Version: 3.9.3
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://debian.tryton.org/gitweb/?p=packages/relatorio.git
commit 68a6455e17e0650da05f08754be25b37ef4dabf8
Author: Daniel Baumann <daniel at 127011.net>
Date:   Sat Jun 30 17:01:29 2012 +0200

    Switching to xz compression.

diff --git a/debian/rules b/debian/rules
index e32b791..1ae0776 100755
--- a/debian/rules
+++ b/debian/rules
@@ -7,3 +7,6 @@ override_dh_auto_clean:
 	dh_auto_clean
 
 	rm -rf *.egg-info
+
+override_dh_builddeb:
+	dh_builddeb -- -Zxz -z9
diff --git a/debian/source/options b/debian/source/options
index d053b65..22a4de9 100644
--- a/debian/source/options
+++ b/debian/source/options
@@ -1,2 +1,2 @@
-compression = gzip
+compression = xz
 compression-level = 9
commit c743dd4fdf63e990df3b15120bc2b30be7d57072
Author: Daniel Baumann <daniel at 127011.net>
Date:   Sat Jun 30 16:55:07 2012 +0200

    Updating vcs fields.

diff --git a/debian/control b/debian/control
index 3d19111..503d9b6 100644
--- a/debian/control
+++ b/debian/control
@@ -8,8 +8,8 @@ Build-Depends:
  debhelper (>= 8), python (>= 2.6.6-3~), python-genshi, python-setuptools
 Standards-Version: 3.9.3
 Homepage: http://relatorio.openhex.org/
-Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
-Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
+Vcs-Browser: http://debian.tryton.org/gitweb/?p=packages/relatorio.git
+Vcs-Git: git://debian.tryton.org/git/packages/relatorio.git
 X-Python-Version: >= 2.4
 
 Package: python-relatorio
commit 32416c69613bcb6cff8f79d723f7112c9809eb23
Author: Daniel Baumann <daniel at 127011.net>
Date:   Sat Jun 30 16:47:48 2012 +0200

    Updating maintainers field.

diff --git a/debian/control b/debian/control
index 3f2a843..3d19111 100644
--- a/debian/control
+++ b/debian/control
@@ -1,7 +1,7 @@
 Source: relatorio
 Section: python
 Priority: optional
-Maintainer: Debian Tryton Maintainers <tryton at lists.debian-maintainers.org>
+Maintainer: Debian Tryton Maintainers <maintainers at debian.tryton.org>
 Uploaders: Daniel Baumann <daniel at debian.org>, Mathias Behrle <mathiasb at m9s.biz>
 Dm-Upload-Allowed: yes
 Build-Depends:
commit 78f4870be147af00cd01b6eaec85df0a72185af8
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Sun Mar 25 15:28:17 2012 +0200

    Adding Format header for DEP5.

diff --git a/debian/copyright b/debian/copyright
index 0d6fdd6..567fd39 100644
--- a/debian/copyright
+++ b/debian/copyright
@@ -1,3 +1,5 @@
+Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
+
 Files: *
 Copyright:
  (C) 2007-2008 OpenHex SPRL <http://www.openhex.com/>
commit c83c90b7dbd14b6404ec35f9fe79ba8c094387aa
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Fri Feb 24 13:47:00 2012 +0100

    Updating to Standards-Version: 3.9.3, no changes needed.

diff --git a/debian/control b/debian/control
index bccdfa7..3f2a843 100644
--- a/debian/control
+++ b/debian/control
@@ -6,7 +6,7 @@ Uploaders: Daniel Baumann <daniel at debian.org>, Mathias Behrle <mathiasb at m9s.biz>
 Dm-Upload-Allowed: yes
 Build-Depends:
  debhelper (>= 8), python (>= 2.6.6-3~), python-genshi, python-setuptools
-Standards-Version: 3.9.2
+Standards-Version: 3.9.3
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
 Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
commit 6186f28c6e53164be2050170609cdd80e9dd28e9
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Fri Feb 24 01:09:23 2012 +0100

    Releasing debian version 0.5.6-1.

diff --git a/debian/changelog b/debian/changelog
index c573638..103fd3e 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,10 @@
+relatorio (0.5.6-1) unstable; urgency=low
+
+  * Updating copyright file.
+  * Merging upstream version 0.5.6.
+
+ -- Mathias Behrle <mathiasb at m9s.biz>  Fri, 24 Feb 2012 01:07:17 +0100
+
 relatorio (0.5.5-4) unstable; urgency=low
 
   * Removing deprecated XB-Python-Version for dh_python2.
commit a87aaa9f6432b5bcc6df4e74448326d38105237f
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Fri Feb 24 00:59:13 2012 +0100

    Updating copyright file.

diff --git a/debian/copyright b/debian/copyright
index 92747f7..0d6fdd6 100644
--- a/debian/copyright
+++ b/debian/copyright
@@ -1,9 +1,18 @@
 Files: *
-Copyright: (C) 2007-2010 OpenHex SPRL <http://www.openhex.com/>
+Copyright:
+ (C) 2007-2008 OpenHex SPRL <http://www.openhex.com/>
+License: GPL-3+
+
+Files: relatorio/templates/opendocument.py
+Copyright:
+ (C) 2007-2008 OpenHex SPRL <http://www.openhex.com/>
+ (C) 2009 Cedric Krier
 License: GPL-3+
 
 Files: debian/*
-Copyright: (C) 2009-2011 Daniel Baumann <daniel at debian.org>
+Copyright:
+ (C) 2009-2012 Daniel Baumann <daniel at debian.org>
+ (C) 2012 Mathias Behrle <mathiasb at m9s.biz>
 License: GPL-3+
 
 License: GPL-3+
commit 7e85bc80977601b1866182613e947b1af13dee99
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Fri Feb 24 00:31:37 2012 +0100

    Merging upstream version 0.5.6.

diff --git a/AUTHORS b/AUTHORS
index 160f9b9..f16a0a7 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -1,7 +1,5 @@
 relatorio is the work of:
     Nicolas Évrard <nicoe at openhex.org>
     Gaëtan de Menten <gdementen at openhex.org>
-
-We included ideas and patches from:
     Cédric Krier <cedric.krier at b2ck.com>
     Udo Spallek <udono at virtual-things.biz>
diff --git a/CHANGES b/CHANGES
index 5faf36d..00f42e2 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,11 @@
+0.5.6 - 20120223
+ * Add expression cache to prevent multiple evaluation of the same expression
+ * Fix typo when writing manifest
+ * Remove Thumbnails in opendocument
+ * Clean meta in opendocument
+ * Clean template code from draw:frame in opendocument
+ * Use StringIO as failback of cStringIO
+
 0.5.5 - 20100719
  * Fix namespace in opendocument manifest
 
diff --git a/PKG-INFO b/PKG-INFO
index cb0069e..02b646a 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
 Metadata-Version: 1.0
 Name: relatorio
-Version: 0.5.5
+Version: 0.5.6
 Summary: A templating library able to output odt and pdf files
 Home-page: http://relatorio.openhex.org/
 Author: Cedric Krier
@@ -16,7 +16,7 @@ Description:
         
         relatorio also provides a report repository allowing you to link python objects
         and report together, find reports by mimetypes/name/python objects.
-        
+            
 Platform: UNKNOWN
 Classifier: Development Status :: 4 - Beta
 Classifier: Intended Audience :: Developers
diff --git a/relatorio.egg-info/PKG-INFO b/relatorio.egg-info/PKG-INFO
index cb0069e..02b646a 100644
--- a/relatorio.egg-info/PKG-INFO
+++ b/relatorio.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
 Metadata-Version: 1.0
 Name: relatorio
-Version: 0.5.5
+Version: 0.5.6
 Summary: A templating library able to output odt and pdf files
 Home-page: http://relatorio.openhex.org/
 Author: Cedric Krier
@@ -16,7 +16,7 @@ Description:
         
         relatorio also provides a report repository allowing you to link python objects
         and report together, find reports by mimetypes/name/python objects.
-        
+            
 Platform: UNKNOWN
 Classifier: Development Status :: 4 - Beta
 Classifier: Intended Audience :: Developers
diff --git a/relatorio/__init__.py b/relatorio/__init__.py
index f28b310..eced3e4 100644
--- a/relatorio/__init__.py
+++ b/relatorio/__init__.py
@@ -12,4 +12,4 @@ and report together, find reports by mimetypes/name/python objects.
 from relatorio.reporting import MIMETemplateLoader, ReportRepository, Report
 import templates
 
-__version__ = '0.5.5'
+__version__ = '0.5.6'
diff --git a/relatorio/reporting.py b/relatorio/reporting.py
index 676e8d3..bfbff5a 100644
--- a/relatorio/reporting.py
+++ b/relatorio/reporting.py
@@ -20,11 +20,12 @@
 
 __metaclass__ = type
 
-import os, sys
+import os
+import sys
 
-import pkg_resources
 from genshi.template import TemplateLoader
 
+
 def _absolute(path):
     "Compute the absolute path of path relative to the caller file"
     if os.path.isabs(path):
@@ -33,6 +34,7 @@ def _absolute(path):
     caller_dir = os.path.dirname(caller_fname)
     return os.path.abspath(os.path.join(caller_dir, path))
 
+
 def _guess_type(mime):
     """
     Returns the codename used by relatorio to identify which template plugin
@@ -124,7 +126,6 @@ class Report:
         return '<relatorio report on %s>' % self.fpath
 
 
-
 class ReportDict:
 
     def __init__(self, *args, **kwargs):
diff --git a/relatorio/templates/__init__.py b/relatorio/templates/__init__.py
index 8bc7307..a4bbb60 100644
--- a/relatorio/templates/__init__.py
+++ b/relatorio/templates/__init__.py
@@ -20,7 +20,10 @@
 
 import traceback
 import warnings
-from cStringIO import StringIO
+try:
+    from cStringIO import StringIO
+except ImportError:
+    from StringIO import StringIO
 
 plugins = ['base', 'opendocument', 'pdf', 'chart']
 
diff --git a/relatorio/templates/base.py b/relatorio/templates/base.py
index dfc9a38..5a3d46c 100644
--- a/relatorio/templates/base.py
+++ b/relatorio/templates/base.py
@@ -10,7 +10,7 @@
 #
 # This program 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 
+# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 # details.
 #
 # You should have received a copy of the GNU General Public License along with
@@ -20,12 +20,15 @@
 
 __metaclass__ = type
 
-from cStringIO import OutputType
+try:
+    from cStringIO import OutputType
+except ImportError:
+    from StringIO import StringIO as OutputType
 
 import genshi.core
 from genshi.template import NewTextTemplate, MarkupTemplate
 
-from relatorio.reporting import Report, MIMETemplateLoader
+from relatorio.reporting import MIMETemplateLoader
 
 
 class RelatorioStream(genshi.core.Stream):
diff --git a/relatorio/templates/chart.py b/relatorio/templates/chart.py
index 6c6ba8a..34d0770 100644
--- a/relatorio/templates/chart.py
+++ b/relatorio/templates/chart.py
@@ -10,7 +10,7 @@
 #
 # This program 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 
+# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 # details.
 #
 # You should have received a copy of the GNU General Public License along with
@@ -20,7 +20,10 @@
 
 __metaclass__ = type
 
-from cStringIO import StringIO
+try:
+    from cStringIO import StringIO
+except ImportError:
+    from StringIO import StringIO
 
 import yaml
 import genshi
@@ -78,11 +81,11 @@ class CairoSerializer:
                                        chart_yaml['options']['height'])
         else:
             raise NotImplementedError
-        
+
         chart = PYCHA_TYPE[chart_info['type']](surface, chart_yaml['options'])
         chart.addDataset(chart_info['dataset'])
         chart.render()
-        
+
         if chart_type == 'png':
             surface.write_to_png(result)
         elif chart_type == 'svg':
diff --git a/relatorio/templates/opendocument.py b/relatorio/templates/opendocument.py
index 72486d2..a7aa8c6 100644
--- a/relatorio/templates/opendocument.py
+++ b/relatorio/templates/opendocument.py
@@ -31,8 +31,12 @@ except ImportError:
 import time
 import urllib
 import zipfile
-from cStringIO import StringIO
+try:
+    from cStringIO import StringIO
+except ImportError:
+    from StringIO import StringIO
 from copy import deepcopy
+import datetime
 
 
 import warnings
@@ -47,7 +51,8 @@ from genshi.filters.transform import ENTER, EXIT
 from genshi.core import Stream
 from genshi.template.interpolation import PREFIX
 
-
+#from relatorio import __version__ as VERSION
+import relatorio
 from relatorio.templates.base import RelatorioStream
 from relatorio.reporting import Report, MIMETemplateLoader
 try:
@@ -75,6 +80,8 @@ EXTENSIONS = {'image/png': 'png',
 RELATORIO_URI = 'http://relatorio.openhex.org/'
 GENSHI_URI = 'http://genshi.edgewall.org/'
 MANIFEST = 'META-INF/manifest.xml'
+META = 'meta.xml'
+THUMBNAILS = 'Thumbnails'
 output_encode = genshi.output.encode
 EtreeElement = lxml.etree.Element
 
@@ -103,6 +110,7 @@ def guess_type(val):
     elif isinstance(val, (int, float, long)):
         return 'float'
 
+
 class OOTemplateError(genshi.template.base.TemplateSyntaxError):
     "Error to raise when there is a SyntaxError in the genshi template"
 
@@ -169,6 +177,19 @@ class ColumnCounter:
                                         self.counters.get(table_name, 0))
 
 
+class ExpressionCache:
+    """A class used to cache result of expression evaluation"""
+    def __init__(self):
+        self.cache = {}
+
+    def store(self, expression_id, expression):
+        self.cache[expression_id] = expression
+        return expression
+
+    def get(self, expression_id):
+        return self.cache[expression_id]
+
+
 def wrap_nodes_between(first, last, new_parent):
     """An helper function to move all nodes between two nodes to a new node
     and add that new node to their former parent. The boundary nodes are
@@ -189,6 +210,7 @@ def wrap_nodes_between(first, last, new_parent):
         # remove it from its previous parent
         new_parent.append(node)
     old_parent.replace(first, new_parent)
+    new_parent.tail = last.tail
     old_parent.remove(last)
 
 
@@ -366,7 +388,6 @@ class Template(MarkupTemplate):
         office_name = '{%s}value' % self.namespaces['office']
         office_valuetype = '{%s}value-type' % self.namespaces['office']
 
-        py_attrs_attr = '{%s}attrs' % GENSHI_URI
         py_replace = '{%s}replace' % GENSHI_URI
 
         r_statements, closing_tags = self._relatorio_statements(tree)
@@ -429,16 +450,22 @@ class Template(MarkupTemplate):
                                    genshi_node)
             else:
                 # It's not a genshi statement it's a python expression
-                r_node.attrib[py_replace] = expr
                 parent = r_node.getparent().getparent()
                 if parent is None or parent.tag != table_cell_tag:
+                    r_node.attrib[py_replace] = expr
                     continue
 
+                cache_id = id(r_node)
+                r_node.attrib[py_replace] = ("__relatorio_get_cache(%s)" %
+                                             cache_id)
                 # The grand-parent tag is a table cell we should set the
                 # correct value and type for this cell.
-                dico = "{'%s': %s, '%s': __relatorio_guess_type(%s)}"
+                dico = ("{'%s': __relatorio_store_cache(%s, %s), "
+                        "'%s': __relatorio_guess_type("
+                        "__relatorio_get_cache(%s))}")
                 update_py_attrs(parent, dico %
-                        (office_name, expr, office_valuetype, expr))
+                        (office_name, cache_id, expr, office_valuetype,
+                         cache_id))
                 parent.attrib.pop(office_valuetype, None)
                 parent.attrib.pop(office_name, None)
 
@@ -452,7 +479,6 @@ class Template(MarkupTemplate):
         table_col_tag = '{%s}table-column' % table_namespace
         table_num_col_attr = '{%s}number-columns-repeated' % table_namespace
 
-        py_attrs_attr = '{%s}attrs' % GENSHI_URI
         repeat_tag = '{%s}repeat' % RELATORIO_URI
 
         # table node (it is not necessarily the direct parent of ancestor)
@@ -535,11 +561,7 @@ class Template(MarkupTemplate):
                 tag_pos = table_node.index(tag)
                 num = int(tag.attrib.pop(table_num_col_attr))
                 new_tags = [deepcopy(tag) for _ in range(num)]
-                table_node[tag_pos:tag_pos+1] = new_tags
-
-            # recompute the list of column headers as it could
-            # have changed.
-            coldefs = list(table_node.iterchildren(table_col_tag))
+                table_node[tag_pos:tag_pos + 1] = new_tags
 
             # compute the column header nodes corresponding to
             # the opening and closing tags.
@@ -599,7 +621,7 @@ class Template(MarkupTemplate):
         rows_to_wrap = [row_node]
         assert row_node.tag == table_row_tag
         next_rows = row_node.itersiblings(table_row_tag)
-        for row_idx in range(rows_spanned-1):
+        for row_idx in range(rows_spanned - 1):
             next_row_node = next_rows.next()
             rows_to_wrap.append(next_row_node)
             # compute the start and end nodes
@@ -631,17 +653,21 @@ class Template(MarkupTemplate):
         svg_height = '{%s}height' % svg_namespace
         xpath_expr = "//draw:frame[starts-with(@draw:name, 'image:')]"
         for draw in tree.xpath(xpath_expr, namespaces=self.namespaces):
+            cache_id = id(draw)
             d_name = draw.attrib[draw_name][6:].strip()
-            attr_expr = "__relatorio_make_href(%s)" % d_name
+            draw.attrib[draw_name] = ''  # clean template code
+            attr_expr = ("__relatorio_make_href(__relatorio_get_cache(%s))" %
+                         cache_id)
             image_node = EtreeElement(draw_image,
                                       attrib={py_attrs: attr_expr},
                                       nsmap={'draw': draw_namespace,
                                              'py': GENSHI_URI})
             draw.replace(draw[0], image_node)
-            width = draw.attrib.pop(svg_width, None)
-            height = draw.attrib.pop(svg_height, None)
-            attr_expr = "__relatorio_make_dimension(%s, '%s', '%s')" % \
-                    (d_name, width, height)
+            width = draw.attrib.pop(svg_width, '')
+            height = draw.attrib.pop(svg_height, '')
+            attr_expr = ("__relatorio_make_dimension("
+                         "__relatorio_store_cache(%s, %s), '%s', '%s')" %
+                         (cache_id, d_name, width, height))
             draw.attrib[py_attrs] = attr_expr
 
     def _handle_innerdocs(self, tree):
@@ -676,6 +702,10 @@ class Template(MarkupTemplate):
         kwargs['__relatorio_inc_col_count'] = counter.inc
         kwargs['__relatorio_store_col_count'] = counter.store
 
+        cache = ExpressionCache()
+        kwargs['__relatorio_store_cache'] = cache.store
+        kwargs['__relatorio_get_cache'] = cache.get
+
         stream = super(Template, self).generate(*args, **kwargs)
         if self.has_col_loop:
             # Note that we can't simply add a "number-columns-repeated"
@@ -738,12 +768,62 @@ class Manifest(object):
                                   nsmap={'manifest': manifest_namespace})
         self.root.append(entry_node)
 
+    def remove_file_entry(self, path):
+        manifest_namespace = self.namespaces['manifest']
+        entry = self.root.find('{%s}%s[@{%s}full-path="%s"]' %
+                               (manifest_namespace, 'file-entry',
+                                manifest_namespace, path))
+        if entry is not None:
+            self.root.remove(entry)
+
+
+class Meta(object):
+
+    def __init__(self, content):
+        self.tree = lxml.etree.parse(StringIO(content))
+        root = self.tree.getroot()
+        self.namespaces = root.nsmap
+        path = '/office:document-meta/office:meta'
+        self.office_meta, = self.tree.xpath(path, namespaces=self.namespaces)
+
+    def set(self, name, value, namespace='meta'):
+        namespace = self.namespaces[namespace]
+        meta = self.office_meta.find('{%s}%s' % (namespace, name))
+        if meta is None:
+            meta = EtreeElement('{%s}%s' % (namespace, name),
+                                            nsmap={'meta': namespace})
+            self.office_meta.append(meta)
+        meta.text = value
+
+    def remove(self, name, namespace='meta'):
+        namespace = self.namespaces[namespace]
+        meta = self.office_meta.find('{%s}%s' % (namespace, name))
+        if meta is not None:
+            self.office_meta.remove(meta)
+
+    def __str__(self):
+        now = datetime.datetime.now()
+        self.set('creation-date', now.isoformat())
+        self.set('date', now.isoformat())
+        self.remove('document-statistic')
+        self.set('editing-cycles', '1')
+        self.remove('editing-duration')
+        self.set('generator', 'relatorio/%s' % relatorio.__version__)
+        self.remove('initial-creator')
+        self.remove('print-date')
+        self.remove('printed-by')
+        self.remove('creator', 'dc')
+        self.remove('date', 'dc')
+        return lxml.etree.tostring(self.tree, encoding='UTF-8',
+                                   xml_declaration=True)
+
 
 class OOSerializer:
 
     def __init__(self, oo_path):
         self.inzip = zipfile.ZipFile(oo_path)
         self.manifest = Manifest(self.inzip.read(MANIFEST))
+        self.meta = Meta(self.inzip.read(META))
         self.new_oo = StringIO()
         self.outzip = zipfile.ZipFile(self.new_oo, 'w')
         self.xml_serializer = genshi.output.XMLSerializer()
@@ -757,6 +837,7 @@ class OOSerializer:
             files.setdefault(stream_for, []).append((kind, data, pos))
 
         now = time.localtime()[:6]
+        manifest_info = None
         for f_info in self.inzip.infolist():
             if f_info.filename.startswith('ObjectReplacements'):
                 continue
@@ -770,9 +851,16 @@ class OOSerializer:
                 serialized_stream = output_encode(self.xml_serializer(stream))
                 self.outzip.writestr(new_info, serialized_stream)
             elif f_info.filename == MANIFEST:
-                self.outzip.writestr(f_info, str(self.manifest))
+                manifest_info = f_info
+            elif f_info.filename == META:
+                self.outzip.writestr(f_info, str(self.meta))
+            elif f_info.filename.startswith(THUMBNAILS + '/'):
+                self.manifest.remove_file_entry(f_info.filename)
             else:
                 self.outzip.writestr(f_info, self.inzip.read(f_info.filename))
+        self.manifest.remove_file_entry(THUMBNAILS + '/')
+        if manifest_info:
+            self.outzip.writestr(manifest_info, str(self.manifest))
         self.inzip.close()
         self.outzip.close()
 
diff --git a/relatorio/templates/pdf.py b/relatorio/templates/pdf.py
index 20ac2a4..c99024c 100644
--- a/relatorio/templates/pdf.py
+++ b/relatorio/templates/pdf.py
@@ -24,7 +24,10 @@ import os
 import shutil
 import tempfile
 import subprocess
-from cStringIO import StringIO
+try:
+    from cStringIO import StringIO
+except ImportError:
+    from StringIO import StringIO
 
 import genshi
 import genshi.output
commit 1f9ab11c2434763fc4f3a288a0fe6bbe70c773c3
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Sun Aug 14 14:19:43 2011 +0200

    Releasing debian version 0.5.5-4.

diff --git a/debian/changelog b/debian/changelog
index c1110ca..c573638 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,10 @@
+relatorio (0.5.5-4) unstable; urgency=low
+
+  * Removing deprecated XB-Python-Version for dh_python2.
+  * Uploading to unstable.
+
+ -- Mathias Behrle <mathiasb at m9s.biz>  Sun, 14 Aug 2011 14:14:46 +0200
+
 relatorio (0.5.5-3) experimental; urgency=low
 
   [ Mathias Behrle ]
commit fa78b2cd362232d618551f97929685ac7d7452dd
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Fri Jul 22 12:26:53 2011 +0200

    Removing deprecated XB-Python-Version for dh_python2.

diff --git a/debian/control b/debian/control
index 591fefe..bccdfa7 100644
--- a/debian/control
+++ b/debian/control
@@ -17,7 +17,6 @@ Architecture: all
 Depends:
  ${misc:Depends}, ${python:Depends}, python-genshi, python-lxml,
  python-pkg-resources
-XB-Python-Version: ${python:Versions}
 Suggests: python-pycha, python-yaml
 Description: Python module to create reports from Python objects
  This is a Python module to create reports from Python objects. Output plugins
commit 8af9583c0385a01465c5055e7d5d24c1cc076dfa
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Sun Jul 17 19:38:57 2011 +0200

    Releasing debian version 0.5.5-3.

diff --git a/debian/changelog b/debian/changelog
index 543e662..c1110ca 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,20 @@
+relatorio (0.5.5-3) experimental; urgency=low
+
+  [ Mathias Behrle ]
+  * Changing my email address.
+  * Updating Copyright.
+  * Updating to standards version 3.9.2.
+
+  [ Daniel Baumann ]
+  * Not wrapping uploaders field, it does not exceed 80 chars.
+  * Compacting copyright file.
+  * Moving to source format 3.0 (quilt).
+
+  [ Mathias Behrle ]
+  * Moving from deprecated python-support to dh_python2.
+
+ -- Mathias Behrle <mathiasb at m9s.biz>  Sun, 17 Jul 2011 19:38:47 +0200
+
 relatorio (0.5.5-2) experimental; urgency=low
 
   * Updating to debhelper version 8.
commit 2daf89c5757bfc638a123a2ad19593f5339819e8
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Sun Jul 17 18:32:30 2011 +0200

    Moving from deprecated python-support to dh_python2.

diff --git a/debian/control b/debian/control
index 00b5599..591fefe 100644
--- a/debian/control
+++ b/debian/control
@@ -5,11 +5,12 @@ Maintainer: Debian Tryton Maintainers <tryton at lists.debian-maintainers.org>
 Uploaders: Daniel Baumann <daniel at debian.org>, Mathias Behrle <mathiasb at m9s.biz>
 Dm-Upload-Allowed: yes
 Build-Depends:
- debhelper (>= 8), python, python-genshi, python-setuptools, python-support
+ debhelper (>= 8), python (>= 2.6.6-3~), python-genshi, python-setuptools
 Standards-Version: 3.9.2
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
 Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
+X-Python-Version: >= 2.4
 
 Package: python-relatorio
 Architecture: all
diff --git a/debian/pycompat b/debian/pycompat
deleted file mode 100644
index 0cfbf08..0000000
--- a/debian/pycompat
+++ /dev/null
@@ -1 +0,0 @@
-2
diff --git a/debian/pydist-overrides b/debian/pydist-overrides
new file mode 100644
index 0000000..85771df
--- /dev/null
+++ b/debian/pydist-overrides
@@ -0,0 +1 @@
+lxml python-lxml
diff --git a/debian/pyversions b/debian/pyversions
deleted file mode 100644
index 8b253bc..0000000
--- a/debian/pyversions
+++ /dev/null
@@ -1 +0,0 @@
-2.4-
diff --git a/debian/rules b/debian/rules
index 000210b..e32b791 100755
--- a/debian/rules
+++ b/debian/rules
@@ -1,4 +1,9 @@
 #!/usr/bin/make -f
 
 %:
-	dh ${@}
+	dh ${@} --with python2
+
+override_dh_auto_clean:
+	dh_auto_clean
+
+	rm -rf *.egg-info
commit 569c644956808f0f27cb28034ef9faac7615a7f6
Author: Daniel Baumann <daniel at debian.org>
Date:   Sun Jul 10 14:58:21 2011 +0200

    Moving to source format 3.0 (quilt).

diff --git a/debian/README.source b/debian/README.source
deleted file mode 100644
index 18b6b24..0000000
--- a/debian/README.source
+++ /dev/null
@@ -1,37 +0,0 @@
-Package Repositories
---------------------
-
-Backports for the current stable debian distribution as well as snapshots of
-unreleased versions may be available in repositories listed on the maintainers
-homepage. The current URL of the maintainer homepage can be seen in
-debian/copyright.
-
-
-Source Access
--------------
-
-You can obtain the sources of this package with:
-
-  $ apt-get source ${PACKAGE}
-
-whereas '${PACKAGE}' has to be replaced with the actual name of the package.
-
-This package is maintained with the Git version control system. The current git
-source tree can be obtained with:
-
-  $ git clone ${GIT_URI}
-
-whereas '${GIT_URI}' has to be replaced with the actual URI for the Git
-repository. The current Git URI can be seen in debian/control in the extracted
-package sources.
-
-More information about Git can be found in the git-core package.
-
-This package may use the Quilt patch system to manage all modifications to the
-upstream source. Changes, if any, are stored in the source package as diffs in
-debian/diff and are applied during the build. Current modifications can be
-applied to the source tree with:
-
-  $ QUILT_PATCHES=debian/patches quilt push -a
-
-More information about Quilt can be found in the quilt package.
diff --git a/debian/source/options b/debian/source/options
new file mode 100644
index 0000000..d053b65
--- /dev/null
+++ b/debian/source/options
@@ -0,0 +1,2 @@
+compression = gzip
+compression-level = 9
commit e78f0874ef6f1a0ab181692a11c457f86e9cf887
Author: Daniel Baumann <daniel at debian.org>
Date:   Sun Jul 10 14:58:03 2011 +0200

    Compacting copyright file.

diff --git a/debian/copyright b/debian/copyright
index 8e72e45..92747f7 100644
--- a/debian/copyright
+++ b/debian/copyright
@@ -1,30 +1,12 @@
-Upstream-Contact: Relatorio project <relatorio at openhex.org>
-Upstream-Homepage: http://relatorio.openhex.org/
-Maintainer-Contact: Debian Tryton Maintainers <tryton at lists.debian-maintainers.org>
-Maintainer-Homepage: http://tryton.debian-maintainers.org/
-
 Files: *
 Copyright: (C) 2007-2010 OpenHex SPRL <http://www.openhex.com/>
 License: GPL-3+
- This program 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, either version 3 of the License, or
- (at your option) any later version.
- .
- This program 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.
- .
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- .
- On Debian systems, the complete text of the GNU General Public License
- can be found in /usr/share/common-licenses/GPL-3 file.
 
 Files: debian/*
 Copyright: (C) 2009-2011 Daniel Baumann <daniel at debian.org>
 License: GPL-3+
+
+License: GPL-3+
  This program 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, either version 3 of the License, or
@@ -38,5 +20,5 @@ License: GPL-3+
  You should have received a copy of the GNU General Public License
  along with this program. If not, see <http://www.gnu.org/licenses/>.
  .
- On Debian systems, the complete text of the GNU General Public License
+ The complete text of the GNU General Public License
  can be found in /usr/share/common-licenses/GPL-3 file.
commit 13ae1e5dbf5513814836d1015d2966feb1cac5aa
Author: Daniel Baumann <daniel at debian.org>
Date:   Sun Jul 10 14:57:37 2011 +0200

    Not wrapping uploaders field, it does not exceed 80 chars.

diff --git a/debian/control b/debian/control
index 9d2496d..00b5599 100644
--- a/debian/control
+++ b/debian/control
@@ -2,9 +2,7 @@ Source: relatorio
 Section: python
 Priority: optional
 Maintainer: Debian Tryton Maintainers <tryton at lists.debian-maintainers.org>
-Uploaders:
- Daniel Baumann <daniel at debian.org>,
- Mathias Behrle <mathiasb at m9s.biz>
+Uploaders: Daniel Baumann <daniel at debian.org>, Mathias Behrle <mathiasb at m9s.biz>
 Dm-Upload-Allowed: yes
 Build-Depends:
  debhelper (>= 8), python, python-genshi, python-setuptools, python-support
commit 30aa388ca79a993d2736ec0f080d06b0a417d180
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Tue Apr 26 21:08:51 2011 +0200

    Updating to standards version 3.9.2.

diff --git a/debian/control b/debian/control
index 796e64f..9d2496d 100644
--- a/debian/control
+++ b/debian/control
@@ -8,7 +8,7 @@ Uploaders:
 Dm-Upload-Allowed: yes
 Build-Depends:
  debhelper (>= 8), python, python-genshi, python-setuptools, python-support
-Standards-Version: 3.9.1
+Standards-Version: 3.9.2
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
 Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
commit 22e803cfc1bec6f5fea8cb6367098ce08f327c28
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Tue Apr 26 19:59:13 2011 +0200

    Updating Copyright.

diff --git a/debian/copyright b/debian/copyright
index 1892a2d..8e72e45 100644
--- a/debian/copyright
+++ b/debian/copyright
@@ -23,7 +23,7 @@ License: GPL-3+
  can be found in /usr/share/common-licenses/GPL-3 file.
 
 Files: debian/*
-Copyright: (C) 2009-2010 Daniel Baumann <daniel at debian.org>
+Copyright: (C) 2009-2011 Daniel Baumann <daniel at debian.org>
 License: GPL-3+
  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
commit 444acf57394b6ee901ec8809937f9d7c6c6e1973
Author: Mathias Behrle <mathiasb at m9s.biz>
Date:   Sat Nov 20 11:48:50 2010 +0100

    Changing my email address.

diff --git a/debian/control b/debian/control
index 93bc437..796e64f 100644
--- a/debian/control
+++ b/debian/control
@@ -4,7 +4,7 @@ Priority: optional
 Maintainer: Debian Tryton Maintainers <tryton at lists.debian-maintainers.org>
 Uploaders:
  Daniel Baumann <daniel at debian.org>,
- Mathias Behrle <mathiasb at mbsolutions.selfip.biz>
+ Mathias Behrle <mathiasb at m9s.biz>
 Dm-Upload-Allowed: yes
 Build-Depends:
  debhelper (>= 8), python, python-genshi, python-setuptools, python-support
commit 6771ee5d27db79d3da406ccf253a35b21e99a764
Author: Daniel Baumann <daniel at debian.org>
Date:   Fri Nov 12 14:17:33 2010 +0100

    Releasing debian version 0.5.5-2.

diff --git a/debian/changelog b/debian/changelog
index def13ad..543e662 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,11 @@
+relatorio (0.5.5-2) experimental; urgency=low
+
+  * Updating to debhelper version 8.
+  * Updating to standards version 3.9.1.
+  * Switching to source format 3.0 (quilt).
+
+ -- Daniel Baumann <daniel at debian.org>  Fri, 12 Nov 2010 14:17:25 +0100
+
 relatorio (0.5.5-1) unstable; urgency=low
 
   [ Daniel Baumann ]
commit df0a8f21a99caf8013f8c0267001c2e17e5fbe28
Author: Daniel Baumann <daniel at debian.org>
Date:   Tue Nov 2 14:23:21 2010 +0100

    Switching to source format 3.0 (quilt).

diff --git a/debian/source/format b/debian/source/format
index d3827e7..163aaf8 100644
--- a/debian/source/format
+++ b/debian/source/format
@@ -1 +1 @@
-1.0
+3.0 (quilt)
commit 743c0261cd9f9aa3fbd3797e65afb2f86a92fb87
Author: Daniel Baumann <daniel at debian.org>
Date:   Thu Sep 30 01:04:54 2010 +0200

    Updating to standards version 3.9.1.

diff --git a/debian/control b/debian/control
index 0bd150e..93bc437 100644
--- a/debian/control
+++ b/debian/control
@@ -8,7 +8,7 @@ Uploaders:
 Dm-Upload-Allowed: yes
 Build-Depends:
  debhelper (>= 8), python, python-genshi, python-setuptools, python-support
-Standards-Version: 3.9.0
+Standards-Version: 3.9.1
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
 Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
commit b7576fb4416ad8d2465415d127ae127ec28773c4
Author: Daniel Baumann <daniel at debian.org>
Date:   Thu Sep 30 01:04:04 2010 +0200

    Updating to debhelper version 8.

diff --git a/debian/compat b/debian/compat
index 7f8f011..45a4fb7 100644
--- a/debian/compat
+++ b/debian/compat
@@ -1 +1 @@
-7
+8
diff --git a/debian/control b/debian/control
index aa6bc5a..0bd150e 100644
--- a/debian/control
+++ b/debian/control
@@ -7,7 +7,7 @@ Uploaders:
  Mathias Behrle <mathiasb at mbsolutions.selfip.biz>
 Dm-Upload-Allowed: yes
 Build-Depends:
- debhelper (>= 7), python, python-genshi, python-setuptools, python-support
+ debhelper (>= 8), python, python-genshi, python-setuptools, python-support
 Standards-Version: 3.9.0
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
commit e78a4589e37b96cd781b4b9109e0d969aa1abb41
Author: Mathias Behrle <mathiasb at mbsolutions.selfip.biz>
Date:   Mon Jul 19 23:42:46 2010 +0200

    Releasing debian version 0.5.5-1.

diff --git a/debian/changelog b/debian/changelog
index 68025e2..def13ad 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,12 @@
+relatorio (0.5.5-1) unstable; urgency=low
+
+  [ Daniel Baumann ]
+  * Wrapping depends.
+  * Updating standards version to 3.9.0.
+  * Merging upstream version 0.5.5.
+
+ -- Mathias Behrle <mathiasb at mbsolutions.selfip.biz>  Mon, 19 Jul 2010 23:40:03 +0200
+
 relatorio (0.5.4-1) unstable; urgency=low
 
   * Adding Dm-Upload-Allowed in control in preparation for Mathias.
commit 79128b5d38b8128f57fe3e318c399b9dcb7a425a
Author: Daniel Baumann <daniel at debian.org>
Date:   Mon Jul 19 21:06:57 2010 +0200

    Merging upstream version 0.5.5.

diff --git a/CHANGES b/CHANGES
index ed0d702..5faf36d 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,6 @@
+0.5.5 - 20100719
+ * Fix namespace in opendocument manifest
+
 0.5.4 - 20100330
  * Update manifest.xml with added files in opendocument
  * Do not write empty width or height attributes in opendocument
diff --git a/PKG-INFO b/PKG-INFO
new file mode 100644
index 0000000..cb0069e
--- /dev/null
+++ b/PKG-INFO
@@ -0,0 +1,27 @@
+Metadata-Version: 1.0
+Name: relatorio
+Version: 0.5.5
+Summary: A templating library able to output odt and pdf files
+Home-page: http://relatorio.openhex.org/
+Author: Cedric Krier
+Author-email: cedric.krier at b2ck.com
+License: GPL License
+Description: 
+        relatorio
+        =========
+        
+        A templating library which provides a way to easily output all kind of
+        different files (odt, ods, png, svg, ...). Adding support for more filetype is
+        easy: you just have to create a plugin for this.
+        
+        relatorio also provides a report repository allowing you to link python objects
+        and report together, find reports by mimetypes/name/python objects.
+        
+Platform: UNKNOWN
+Classifier: Development Status :: 4 - Beta
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: GNU General Public License (GPL)
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Topic :: Text Processing
diff --git a/examples/basic.odt b/examples/basic.odt
deleted file mode 100644
index f82485e..0000000
Binary files a/examples/basic.odt and /dev/null differ
diff --git a/examples/basic.tex b/examples/basic.tex
deleted file mode 100644
index 5316a30..0000000
--- a/examples/basic.tex
+++ /dev/null
@@ -1,21 +0,0 @@
-\enableregime [utf-8]
-\mainlanguage [fr]
-
-\starttext
-
-Dear $o.customer.name,
-
-Here is the list of your purchases:
-
-\starttable[|l|l|l|l|l|]
-\HL
-\NC Name \VL Reference \VL Quantity \VL Unit Price \VL Amount \SR
-\HL
-{% for line in o.lines%} \
-\NC $line.item.name \VL $line.item.reference \VL $line.quantity
-\VL $line.item.price \VL $line.amount \SR
-\HL \
-{% end %}
-\stoptable
-
-\stoptext
diff --git a/examples/bouteille.png b/examples/bouteille.png
deleted file mode 100644
index ce076c3..0000000
Binary files a/examples/bouteille.png and /dev/null differ
diff --git a/examples/columns.odt b/examples/columns.odt
deleted file mode 100644
index 017e251..0000000
Binary files a/examples/columns.odt and /dev/null differ
diff --git a/examples/common.py b/examples/common.py
deleted file mode 100644
index 5eb636b..0000000
--- a/examples/common.py
+++ /dev/null
@@ -1,43 +0,0 @@
-from os.path import join, dirname
-
-class Invoice(dict):
-
-    @property
-    def total(self):
-        return sum(l['amount'] for l in self['lines'])
-
-    @property
-    def vat(self):
-        return self.total * 0.21
-
-
-inv = Invoice(customer={'name': 'John Bonham',
-                        'address': {'street': 'Smirnov street',
-                                    'zip': 1000,
-                                    'city': 'Montreux'}},
-              lines=[{'item': {'name': 'Vodka 70cl',
-                               'reference': 'VDKA-001',
-                               'price': 10.34},
-                      'quantity': 7,
-                      'amount': 7*10.34},
-                     {'item': {'name': 'Cognac 70cl',
-                               'reference': 'CGNC-067',
-                               'price': 13.46},
-                      'quantity': 12,
-                      'amount': 12*13.46},
-                     {'item': {'name': 'Sparkling water 25cl',
-                               'reference': 'WATR-007',
-                               'price': 4},
-                      'quantity': 1,
-                      'amount': 4},
-                     {'item': {'name': 'Good customer',
-                               'reference': 'BONM-001',
-                               'price': -20},
-                      'quantity': 1,
-                      'amount': -20},
-                    ],
-              id='MZY-20080703',
-              status='late',
-              bottle=(file(join(dirname(__file__), 'bouteille.png'), 'r'),
-                  'image/png'))
-
diff --git a/examples/complicated.odt b/examples/complicated.odt
deleted file mode 100644
index c36ce6a..0000000
Binary files a/examples/complicated.odt and /dev/null differ
diff --git a/examples/demo_chart.py b/examples/demo_chart.py
deleted file mode 100644
index 06392fd..0000000
--- a/examples/demo_chart.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from os.path import abspath, join, dirname
-from relatorio import Report
-
-# test data
-from common import inv
-
-if __name__ == '__main__':
-    pie_report = Report(abspath(join(dirname(__file__), 'pie_chart')),
-            'image/png')
-    file(join(dirname(__file__), 'pie.png'), 'wb').write(
-            pie_report(o=inv).render().getvalue())
-    hbar_report = Report(abspath(join(dirname(__file__), 'hbar_chart')),
-            'image/svg')
-    file(join(dirname(__file__), 'hbar.svg'), 'wb').write(
-            hbar_report(o=inv).render().getvalue())
-    vbar_report = Report(abspath(join(dirname(__file__), 'vbar_chart')),
-            'image/svg')
-    file(join(dirname(__file__), 'vbar.svg'), 'wb').write(
-            vbar_report(o=inv).render().getvalue())
-    line_report = Report(abspath(join(dirname(__file__), 'line_chart')),
-            'image/png')
-    file(join(dirname(__file__), 'line.png'), 'wb').write(
-            line_report(o=inv).render().getvalue())
diff --git a/examples/demo_context.py b/examples/demo_context.py
deleted file mode 100644
index 0013e0a..0000000
--- a/examples/demo_context.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from os.path import abspath, join, dirname
-from relatorio import Report
-
-# test data
-from common import inv
-
-#PDF
-if __name__ == '__main__':
-    print "generating output_basic.pdf... ",
-    report = Report(abspath(join(dirname(__file__), 'basic.tex')),
-        'application/pdf')
-    content = report(o=inv).render().getvalue()
-    file(join(dirname(__file__), 'output_basic.pdf'), 'wb').write(content)
-    print "done"
-
diff --git a/examples/demo_odf.py b/examples/demo_odf.py
deleted file mode 100644
index d4fae8f..0000000
--- a/examples/demo_odf.py
+++ /dev/null
@@ -1,64 +0,0 @@
-from os.path import abspath, join, dirname
-from relatorio import Report
-
-# test data
-from common import inv
-
-ODT_MIME = 'application/vnd.oasis.opendocument.text'
-ODS_MIME = 'application/vnd.oasis.opendocument.spreadsheet'
-ODP_MIME = 'application/vnd.oasis.opendocument.presentation'
-
-if __name__ == '__main__':
-    # ODT
-    print "generating output_basic.odt... ",
-    report = Report(abspath(join(dirname(__file__), 'basic.odt')), ODT_MIME)
-    content = report(o=inv).render().getvalue()
-    file(join(dirname(__file__), 'output_basic.odt'), 'wb').write(content)
-    print "done"
-
-    # we could also use an opendocument template directly
-#    from relatorio.templates import opendocument
-#    template = opendocument.Template(source=None, filepath='basic.odt')
-#    content = template.generate(o=inv).render().getvalue()
-#    file('output_basic.odt', 'wb').write(content)
-
-    print "generating output_complicated.odt... ",
-    # Add a chart to the invoice
-    inv['chart'] = (Report(abspath(join(dirname(__file__), 'pie_chart')),
-        'image/png'), 'image/png')
-    report = Report(abspath(join(dirname(__file__), 'complicated.odt')),
-            ODT_MIME)
-    content = report(o=inv).render().getvalue()
-    file(join(dirname(__file__), 'output_complicated.odt'), 'wb').write(content)
-    print "done"
-
-    print "generating output_columns.odt... ",
-    report = Report(abspath(join(dirname(__file__), 'columns.odt')), ODT_MIME)
-    lst = [[], ['i'], ['a', 'b'], [1, 2, 3], ['I', 'II', 'III', 'IV']]
-    titles = ['first', 'second', 'third', 'fourth']
-    content = report(titles=titles, lst=lst).render().getvalue()
-    file(join(dirname(__file__), 'output_columns.odt'), 'wb').write(content)
-    print "done"
-
-    # ODS
-    print "generating output_pivot.ods... ",
-    report = Report(abspath(join(dirname(__file__), 'pivot.ods')), ODS_MIME)
-    content = report(o=inv).render().getvalue()
-    file(join(dirname(__file__), 'output_pivot.ods'), 'wb').write(content)
-    print "done"
-
-    print "generating output_sheets.ods... ",
-    report = Report(abspath(join(dirname(__file__), 'demo_sheets.ods')),
-            ODS_MIME)
-    content = report(lst=lst).render().getvalue()
-    file(join(dirname(__file__), 'output_sheets.ods'), 'wb').write(content)
-    print "done"
-
-    # ODP
-    print "generating output_presentation.odp... ",
-    report = Report(abspath(join(dirname(__file__), 'presentation.odp')),
-            ODP_MIME)
-    content = report(o=inv).render().getvalue()
-    file(join(dirname(__file__), 'output_presentation.odp'), 'wb').write(content)
-    print "done"
-
diff --git a/examples/demo_repository.py b/examples/demo_repository.py
deleted file mode 100644
index 84bdd92..0000000
--- a/examples/demo_repository.py
+++ /dev/null
@@ -1,32 +0,0 @@
-import relatorio
-from common import Invoice, inv
-from os.path import join, dirname
-
-ODT_MIME = 'application/vnd.oasis.opendocument.text'
-ODS_MIME = 'application/vnd.oasis.opendocument.spreadsheet'
-ODP_MIME = 'application/vnd.oasis.opendocument.presentation'
-
-repository = relatorio.ReportRepository()
-repository.add_report(Invoice, ODT_MIME, 'basic.odt', report_name='basic')
-repository.add_report(Invoice, ODT_MIME,
-                      'complicated.odt', report_name='complicated')
-repository.add_report(Invoice, ODS_MIME, 'pivot.ods', report_name='pivot')
-repository.add_report(Invoice, ODP_MIME,
-                      'presentation.odp', report_name='presentation')
-repository.add_report(Invoice, 'image/png', 'pie_chart', report_name='pie')
-
-if __name__ == '__main__':
-    # Add a chart to the invoice
-    inv['chart'] = repository.by_id(Invoice, 'pie')[:2]
-
-    # Generate all reports on the invoice class
-    for report_name, ext in (('basic', '.odt'),
-                             ('complicated', '.odt'),
-                             ('pivot', '.ods'),
-                             ('presentation', '.odp')):
-        filename = 'output_%s%s' % (report_name, ext)
-        print "generating '%s'..." % filename,
-        report, mimetype, desc = repository.by_id(Invoice, report_name)
-        data = report(o=inv).render().getvalue()
-        file(join(dirname(__file__), filename), 'wb').write(data)
-        print "done"
diff --git a/examples/demo_sheets.ods b/examples/demo_sheets.ods
deleted file mode 100644
index 61c4706..0000000
Binary files a/examples/demo_sheets.ods and /dev/null differ
diff --git a/examples/hbar_chart b/examples/hbar_chart
deleted file mode 100644
index 0f6607b..0000000
--- a/examples/hbar_chart
+++ /dev/null
@@ -1,32 +0,0 @@
-options:
-  width: 600
-  height: 500
-  legend: 
-    hide: false
-    position: 
-      right: 40
-  padding: {bottom: 70, left: 70, right: 10, top: 10}
-  axis:
-    y:
-      interval: 15
-      padding: 5
-    x:
-      ticks:
-      {% for idx, line in enumerate(o.lines) %}
-        - v: $idx
-          label: $line.item.name
-      {% end %}
-chart:
-  type: hbar
-  output_type: svg
-  dataset:
-    - - Sales
-      -
-      {% for idx, line in enumerate(o.lines) %}
-        - [$idx, $line.amount]
-      {% end %}
-    - - Absolute sales
-      -
-      {% for idx, line in enumerate(o.lines) %}
-        - [$idx, ${abs(line.amount)}]
-      {% end %}
diff --git a/examples/line_chart b/examples/line_chart
deleted file mode 100644
index 1457845..0000000
--- a/examples/line_chart
+++ /dev/null
@@ -1,27 +0,0 @@
-options:
-  width: 600
-  height: 500
-  legend: 
-    hide: false
-    position: 
-      right: 40
-  padding: {bottom: 70, left: 70, right: 10, top: 10}
-  axis:
-    y:
-      interval: 10
-      padding: 10
-    x:
-      ticks:
-      {% for idx, line in enumerate(o.lines) %}
-        - v: $idx
-          label: $line.item.name
-      {% end %}
-chart:
-  type: line
-  output_type: png
-  dataset:
-    - - Sales
-      -
-      {% for idx, line in enumerate(o.lines) %}
-        - [$idx, $line.amount]
-      {% end %}
diff --git a/examples/pie_chart b/examples/pie_chart
deleted file mode 100644
index 4b24054..0000000
--- a/examples/pie_chart
+++ /dev/null
@@ -1,15 +0,0 @@
-options:
-    width: 600
-    height: 400
-    background: {hide: true}
-    legend: {hide: true}
-    axis: {labelFontSize: 14}
-    padding: {bottom: 10, left: 10, right: 10, top: 10}
-chart:
-    type: pie
-    output_type: png
-    dataset:
-    {% for line in o.lines %}
-      - - ${line.item.name}
-        - - [0, $line.amount]
-    {% end %}
diff --git a/examples/pivot.ods b/examples/pivot.ods
deleted file mode 100644
index 0d0b40f..0000000
Binary files a/examples/pivot.ods and /dev/null differ
diff --git a/examples/presentation.odp b/examples/presentation.odp
deleted file mode 100644
index 7d08b92..0000000
Binary files a/examples/presentation.odp and /dev/null differ
diff --git a/examples/vbar_chart b/examples/vbar_chart
deleted file mode 100644
index 56c6790..0000000
--- a/examples/vbar_chart
+++ /dev/null
@@ -1,32 +0,0 @@
-options:
-  width: 600
-  height: 500
-  legend: 
-    hide: false
-    position: 
-      right: 40
-  padding: {bottom: 70, left: 70, right: 10, top: 10}
-  axis:
-    y:
-      interval: 20
-      padding: 5
-    x:
-      ticks:
-      {% for idx, line in enumerate(o.lines) %}
-        - v: $idx
-          label: $line.item.name
-      {% end %}
-chart:
-  type: vbar
-  output_type: svg
-  dataset:
-    - - Sales
-      -
-      {% for idx, line in enumerate(o.lines) %}
-        - [$idx, $line.amount]
-      {% end %}
-    - - Absolute sales
-      -
-      {% for idx, line in enumerate(o.lines) %}
-        - [$idx, ${abs(line.amount)}]
-      {% end %}
diff --git a/relatorio.egg-info/PKG-INFO b/relatorio.egg-info/PKG-INFO
new file mode 100644
index 0000000..cb0069e
--- /dev/null
+++ b/relatorio.egg-info/PKG-INFO
@@ -0,0 +1,27 @@
+Metadata-Version: 1.0
+Name: relatorio
+Version: 0.5.5
+Summary: A templating library able to output odt and pdf files
+Home-page: http://relatorio.openhex.org/
+Author: Cedric Krier
+Author-email: cedric.krier at b2ck.com
+License: GPL License
+Description: 
+        relatorio
+        =========
+        
+        A templating library which provides a way to easily output all kind of
+        different files (odt, ods, png, svg, ...). Adding support for more filetype is
+        easy: you just have to create a plugin for this.
+        
+        relatorio also provides a report repository allowing you to link python objects
+        and report together, find reports by mimetypes/name/python objects.
+        
+Platform: UNKNOWN
+Classifier: Development Status :: 4 - Beta
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: GNU General Public License (GPL)
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Topic :: Text Processing
diff --git a/relatorio.egg-info/SOURCES.txt b/relatorio.egg-info/SOURCES.txt
new file mode 100644
index 0000000..99038ab
--- /dev/null
+++ b/relatorio.egg-info/SOURCES.txt
@@ -0,0 +1,19 @@
+AUTHORS
+CHANGES
+LICENSE
+MANIFEST.in
+README
+setup.cfg
+setup.py
+relatorio/__init__.py
+relatorio/reporting.py
+relatorio.egg-info/PKG-INFO
+relatorio.egg-info/SOURCES.txt
+relatorio.egg-info/dependency_links.txt
+relatorio.egg-info/requires.txt
+relatorio.egg-info/top_level.txt
+relatorio/templates/__init__.py
+relatorio/templates/base.py
+relatorio/templates/chart.py
+relatorio/templates/opendocument.py
+relatorio/templates/pdf.py
\ No newline at end of file
diff --git a/relatorio.egg-info/dependency_links.txt b/relatorio.egg-info/dependency_links.txt
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/relatorio.egg-info/dependency_links.txt
@@ -0,0 +1 @@
+
diff --git a/relatorio.egg-info/requires.txt b/relatorio.egg-info/requires.txt
new file mode 100644
index 0000000..a315bff
--- /dev/null
+++ b/relatorio.egg-info/requires.txt
@@ -0,0 +1,2 @@
+Genshi >= 0.5
+lxml >= 2.0
\ No newline at end of file
diff --git a/relatorio.egg-info/top_level.txt b/relatorio.egg-info/top_level.txt
new file mode 100644
index 0000000..efe4489
--- /dev/null
+++ b/relatorio.egg-info/top_level.txt
@@ -0,0 +1 @@
+relatorio
diff --git a/relatorio/templates/opendocument.py b/relatorio/templates/opendocument.py
index 568eb2e..72486d2 100644
--- a/relatorio/templates/opendocument.py
+++ b/relatorio/templates/opendocument.py
@@ -730,8 +730,8 @@ class Manifest(object):
 
     def add_file_entry(self, path, mimetype=None):
         manifest_namespace = self.namespaces['manifest']
-        attribs = {'media-type': mimetype or '',
-                   'full-path': path}
+        attribs = {'{%s}media-type' % manifest_namespace: mimetype or '',
+                   '{%s}full-path' % manifest_namespace: path}
         entry_node = EtreeElement('{%s}%s' % (manifest_namespace,
                                               'file-entry'),
                                   attrib=attribs,
diff --git a/relatorio/tests/__init__.py b/relatorio/tests/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/relatorio/tests/egg.jpg b/relatorio/tests/egg.jpg
deleted file mode 100644
index 2700e16..0000000
Binary files a/relatorio/tests/egg.jpg and /dev/null differ
diff --git a/relatorio/tests/one.jpg b/relatorio/tests/one.jpg
deleted file mode 100644
index 48723f0..0000000
Binary files a/relatorio/tests/one.jpg and /dev/null differ
diff --git a/relatorio/tests/templates/include.tmpl b/relatorio/tests/templates/include.tmpl
deleted file mode 100644
index cb46df8..0000000
--- a/relatorio/tests/templates/include.tmpl
+++ /dev/null
@@ -1 +0,0 @@
-{% include other.tmpl %}
diff --git a/relatorio/tests/templates/other.tmpl b/relatorio/tests/templates/other.tmpl
deleted file mode 100644
index 224a5d0..0000000
--- a/relatorio/tests/templates/other.tmpl
+++ /dev/null
@@ -1 +0,0 @@
-Another Hello.
diff --git a/relatorio/tests/templates/test.tmpl b/relatorio/tests/templates/test.tmpl
deleted file mode 100644
index 3b06a49..0000000
--- a/relatorio/tests/templates/test.tmpl
+++ /dev/null
@@ -1 +0,0 @@
-Hello ${o.name}.
diff --git a/relatorio/tests/templates/time.tmpl b/relatorio/tests/templates/time.tmpl
deleted file mode 100644
index 8467d56..0000000
--- a/relatorio/tests/templates/time.tmpl
+++ /dev/null
@@ -1,2 +0,0 @@
-Hi ${o.name},
-It's ${time} to ${func(y)} !
diff --git a/relatorio/tests/test.odt b/relatorio/tests/test.odt
deleted file mode 100644
index 6c3e196..0000000
Binary files a/relatorio/tests/test.odt and /dev/null differ
diff --git a/relatorio/tests/test_api.py b/relatorio/tests/test_api.py
deleted file mode 100644
index 09d7727..0000000
--- a/relatorio/tests/test_api.py
+++ /dev/null
@@ -1,122 +0,0 @@
-###############################################################################
-#
-# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
-# Reserved.
-#
-# This program 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; either version 3 of the License, or (at your option) any later
-# version.
-#
-# This program 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.
-#
-# You should have received a copy of the GNU General Public License along with
-# this program.  If not, see <http://www.gnu.org/licenses/>.
-#
-###############################################################################
-
-
-import os
-from nose.tools import *
-
-from relatorio.reporting import (ReportRepository, Report, MIMETemplateLoader,
-                                 DefaultFactory, _absolute, _guess_type)
-
-
-class StubObject(object):
-
-    def __init__(self, **kwargs):
-        for key, val in kwargs.iteritems():
-            setattr(self, key, val)
-
-
-class TestRepository(object):
-
-    def test_register(self):
-        "Testing the registration"
-        reporting = ReportRepository()
-        reporting.add_report(StubObject, 'text/plain',
-                             os.path.join('templates', 'test.tmpl'),
-                             description='Test report')
-
-        assert_true(StubObject in reporting.classes)
-        assert_true('default' in reporting.classes[StubObject].ids)
-        assert_true('text/plain' in reporting.classes[StubObject].mimetypes)
-
-        report, mime, desc = reporting.classes[StubObject].ids['default']
-        eq_(mime, 'text/plain')
-        eq_(desc, 'Test report')
-        eq_(report.mimetype, 'text/plain')
-        assert_true(report.fpath.endswith(os.path.join('templates',
-                                                       'test.tmpl')))
-
-        report2, name = reporting.classes[StubObject].mimetypes['text/plain'][0]
-        eq_(name, 'default')
-        eq_(report, report2)
-
-    def test_mimeguesser(self):
-        eq_(_guess_type('application/pdf'), 'pdf')
-        eq_(_guess_type('text/plain'), 'text')
-        eq_(_guess_type('text/xhtml'), 'markup')
-        eq_(_guess_type('application/vnd.oasis.opendocument.text'), 'oo.org')
-
-    def abspath_helper(self, path):
-        return _absolute(path)
-
-    def test_absolute(self):
-        "Test the absolute path calculation"
-        eq_("/home/nicoe/python/mock.py",
-            _absolute("/home/nicoe/python/mock.py"))
-
-        our_dir, _ = os.path.split(__file__)
-        # We use this because me go up by two frames
-        new_path = self.abspath_helper(os.path.join('brol', 'toto'))
-        eq_(os.path.join(our_dir, 'brol', 'toto'), new_path)
-
-
-class TestReport(object):
-
-    def setup(self):
-        self.loader = MIMETemplateLoader()
-        our_dir, _ = os.path.split(__file__)
-        self.report = Report(os.path.join(our_dir, 'templates', 'test.tmpl'),
-                             'text/plain', DefaultFactory(), self.loader)
-
-    def test_report(self):
-        "Testing the report generation"
-        a = StubObject(name='OpenHex')
-        eq_(self.report(o=a).render(), 'Hello OpenHex.\n')
-
-    def test_factory(self):
-        "Testing the data factory"
-        class MyFactory:
-            def __call__(self, o, time, y=1):
-                d = dict()
-                d['o'] = o
-                d['y'] = y
-                d['time'] = time
-                d['func'] = lambda x: x+1
-                return d
-
-        our_dir, _ = os.path.split(__file__)
-        report = Report(os.path.join(our_dir, 'templates', 'time.tmpl'),
-                        'text/plain', MyFactory(), self.loader)
-
-        a = StubObject(name='Foo')
-        eq_(report(o=a, time="One o'clock").render(),
-            "Hi Foo,\nIt's One o'clock to 2 !\n")
-        eq_(report(o=a, time="One o'clock", y=4).render(),
-            "Hi Foo,\nIt's One o'clock to 5 !\n")
-        assert_raises(TypeError, report, a)
-
-class TestReportInclude(object):
-
-    def test_include(self):
-        our_dir = os.path.dirname(__file__)
-        template_path = os.path.join(our_dir, 'templates')
-        relative_report = Report(os.path.join(template_path, 'include.tmpl'),
-                                 'text/plain')
-        eq_(relative_report().render(), 'Another Hello.\n\n')
diff --git a/relatorio/tests/test_odt.py b/relatorio/tests/test_odt.py
deleted file mode 100644
index 1923e6b..0000000
--- a/relatorio/tests/test_odt.py
+++ /dev/null
@@ -1,308 +0,0 @@
-# -*- encoding: utf-8 -*-
-###############################################################################
-#
-# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
-# Reserved.
-#
-# This program 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; either version 3 of the License, or (at your option) any later
-# version.
-#
-# This program 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.
-#
-# You should have received a copy of the GNU General Public License along with
-# this program.  If not, see <http://www.gnu.org/licenses/>.
-#
-###############################################################################
-
-
-import os
-import re
-from cStringIO import StringIO
-
-import lxml.etree
-from nose.tools import *
-import genshi
-from genshi.filters import Translator
-from genshi.core import PI
-from genshi.template.eval import UndefinedError
-
-from relatorio.templates.opendocument import Template, GENSHI_EXPR, GENSHI_URI,\
-                                   RELATORIO_URI
-
-OO_TABLE_NS = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"
-
-def pseudo_gettext(string):
-    catalog = {'Mes collègues sont:': 'My colleagues are:',
-               'Bonjour,': 'Hello,',
-               'Je suis un test de templating en odt.':
-                'I am an odt templating test',
-               'Felix da housecat': unicode('Félix le chat de la maison',
-                                            'utf8'),
-               'We sell stuff': u'On vend des choses',
-              }
-    return catalog.get(string, string)
-
-
-class TestOOTemplating(object):
-
-    def setup(self):
-        thisdir = os.path.dirname(__file__)
-        filepath = os.path.join(thisdir, 'test.odt')
-        self.oot = Template(file(filepath), filepath)
-        self.data = {'first_name': u'Trente',
-                     'last_name': unicode('Møller', 'utf8'),
-                     'ville': unicode('Liège', 'utf8'),
-                     'friends': [{'first_name': u'Camille',
-                                  'last_name': u'Salauhpe'},
-                                 {'first_name': u'Mathias',
-                                  'last_name': u'Lechat'}],
-                     'hobbies': [u'Music', u'Dancing', u'DJing'],
-                     'animals': [u'Felix da housecat', u'Dog eat Dog'],
-                     'images': [(file(os.path.join(thisdir, 'one.jpg')),
-                                 'image/jpeg'),
-                                (file(os.path.join(thisdir, 'two.png')),
-                                 'image/png')],
-                     'oeuf': file(os.path.join(thisdir, 'egg.jpg')),
-                     'footer': u'We sell stuff'}
-
-    def test_init(self):
-        "Testing the correct handling of the styles.xml and content.xml files"
-        ok_(isinstance(self.oot.stream, list))
-        eq_(self.oot.stream[0], (PI, ('relatorio', 'content.xml'), None))
-        ok_((PI, ('relatorio', 'content.xml'), None) in self.oot.stream)
-
-    def test_directives(self):
-        "Testing the directives interpolation"
-        xml = '''<xml xmlns:text="urn:text" xmlns:xlink="urn:xlink">
-                    <text:a xlink:href="relatorio://foo">foo</text:a>
-                 </xml>'''
-        interpolated = self.oot.insert_directives(xml)
-        root_interpolated = lxml.etree.parse(interpolated).getroot()
-        child = root_interpolated[0]
-        eq_(child.get('{http://genshi.edgewall.org/}replace'), 'foo')
-
-    def test_column_looping(self):
-        xml = '''
-<table:table
-    xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
-    xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
-    xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
-    xmlns:xlink="http://www.w3.org/1999/xlink"
-    table:name="Tableau1"
-    table:style-name="Tableau1">
-    <table:table-column table:style-name="Tableau1.A"
-                        table:number-columns-repeated="2"/>
-    <table:table-column table:style-name="Tableau1.C"/>
-    <table:table-column table:style-name="Tableau1.A"/>
-    <table:table-column table:style-name="Tableau1.E"/>
-    <table:table-header-rows>
-        <table:table-row table:style-name="Tableau1.1">
-            <table:table-cell table:style-name="Tableau1.A1"
-                              office:value-type="string">
-                <text:p text:style-name="Table_20_Heading">Brol</text:p>
-            </table:table-cell>
-            <table:table-cell table:style-name="Tableau1.A1"
-                              office:value-type="string">
-                <text:p text:style-name="Table_20_Heading">
-                    <text:a xlink:type="simple"
-                            xlink:href="relatorio://for each="title in titles"">for each="title in titles"</text:a>
-                </text:p>
-            </table:table-cell>
-            <table:table-cell table:style-name="Tableau1.A1"
-                              office:value-type="string">
-                <text:p text:style-name="Table_20_Heading">${title}</text:p>
-                <text:p text:style-name="Table_20_Heading"/>
-            </table:table-cell>
-            <table:table-cell table:style-name="Tableau1.A1"
-                              office:value-type="string">
-                <text:p text:style-name="Table_20_Heading">
-                    <text:a xlink:type="simple"
-                            xlink:href="relatorio:///for">/for</text:a>
-                </text:p>
-            </table:table-cell>
-            <table:table-cell table:style-name="Tableau1.E1"
-                              office:value-type="string">
-                <text:p text:style-name="Table_20_Heading">Truc</text:p>
-            </table:table-cell>
-        </table:table-row>
-    </table:table-header-rows>
-    <table:table-row>
-        <table:table-cell table:style-name="Tableau1.A2"
-                          table:number-columns-spanned="5"
-                          office:value-type="string">
-            <text:p text:style-name="Table_20_Contents">
-                <text:a xlink:type="simple"
-                        xlink:href="relatorio://for%20each=%22items%20in%20lst%22">for each="items in lst"</text:a>
-            </text:p>
-        </table:table-cell>
-        <table:covered-table-cell/>
-        <table:covered-table-cell/>
-        <table:covered-table-cell/>
-        <table:covered-table-cell/>
-    </table:table-row>
-    <table:table-row>
-        <table:table-cell table:style-name="Tableau1.A3"
-                          office:value-type="string">
-            <text:p text:style-name="Table_20_Contents">Brol</text:p>
-        </table:table-cell>
-        <table:table-cell table:style-name="Tableau1.A3"
-                          office:value-type="string">
-            <text:p text:style-name="Table_20_Contents">
-                <text:a xlink:type="simple"
-                        xlink:href="relatorio://for%20each=%22item%20in%20items%22">for each="item in items"</text:a>
-            </text:p>
-        </table:table-cell>
-        <table:table-cell table:style-name="Tableau1.A3"
-                          office:value-type="string">
-            <text:p text:style-name="Table_20_Contents">${item}</text:p>
-            <text:p text:style-name="Table_20_Contents"/>
-        </table:table-cell>
-        <table:table-cell table:style-name="Tableau1.A3"
-                          office:value-type="string">
-            <text:p text:style-name="Table_20_Contents">
-                <text:a xlink:type="simple"
-                        xlink:href="relatorio:///for">/for</text:a>
-            </text:p>
-        </table:table-cell>
-        <table:table-cell table:style-name="Tableau1.A2"
-                          office:value-type="string">
-            <text:p text:style-name="Table_20_Contents">Truc</text:p>
-        </table:table-cell>
-    </table:table-row>
-    <table:table-row>
-        <table:table-cell table:style-name="Tableau1.A2"
-                          table:number-columns-spanned="5"
-                          office:value-type="string">
-            <text:p text:style-name="Table_20_Contents">
-                <text:a xlink:type="simple"
-                        xlink:href="relatorio:///for">/for</text:a>
-            </text:p>
-        </table:table-cell>
-        <table:covered-table-cell/>
-        <table:covered-table-cell/>
-        <table:covered-table-cell/>
-        <table:covered-table-cell/>
-    </table:table-row>
-</table:table>'''
-        interpolated = self.oot.insert_directives(xml)
-        root = lxml.etree.parse(interpolated).getroot()
-        child2 = root[1]
-        eq_(child2.tag, "{%s}repeat" % RELATORIO_URI)
-        eq_(child2.get("closing"), "3")
-        eq_(child2.get("opening"), "1")
-        eq_(len(child2), 1)
-        child4 = root[3]
-        eq_(child4.tag, "{%s}table-header-rows" % OO_TABLE_NS)
-        row1 = child4[0]
-        ok_(row1.get("{%s}attrs" % GENSHI_URI)
-                .startswith('__relatorio_reset_col_count'))
-        eq_(len(row1), 4)
-        loop = row1[1]
-        eq_(loop.tag, "{%s}for" % GENSHI_URI)
-        cell = loop[0]
-        ok_(cell.get("{%s}attrs" % GENSHI_URI)
-                .startswith('__relatorio_inc_col_count'))
-        last_row_node = row1[3]
-        eq_(last_row_node.tag, "{%s}replace" % GENSHI_URI)
-        ok_(last_row_node.get("value")
-                         .startswith('__relatorio_store_col_count'))
-
-    def test_text_outside_p(self):
-        "Testing that the tail text of a directive node is handled properly"
-        xml = '''<xml xmlns:text="urn:text" xmlns:xlink="urn:xlink">
-                    <text:a xlink:href="relatorio://if%20test=%22True%22">if test="True"</text:a>
-                    xxx
-                    <text:p text:style-name="other">yyy</text:p>
-                    zzz
-                    <text:a xlink:href="relatorio:///if">/if</text:a>
-                 </xml>'''
-        interpolated = self.oot.insert_directives(xml)
-        root_interpolated = lxml.etree.parse(interpolated).getroot()
-        child = root_interpolated[0]
-        eq_(child.tag, '{http://genshi.edgewall.org/}if')
-        eq_(child.text.strip(), 'xxx')
-
-    def test_styles(self):
-        "Testing that styles get rendered"
-        stream = self.oot.generate(**self.data)
-        rendered = stream.events.render()
-        ok_('We sell stuff' in rendered)
-
-        dico = self.data.copy()
-        del dico['footer']
-        stream = self.oot.generate(**dico)
-        assert_raises(UndefinedError, lambda: stream.events.render())
-
-    def test_generate(self):
-        "Testing that content get rendered"
-        stream = self.oot.generate(**self.data)
-        rendered = stream.events.render()
-        ok_('Bonjour,' in rendered)
-        ok_('Trente' in rendered)
-        ok_('Møller' in rendered)
-        ok_('Dog eat Dog' in rendered)
-        ok_('Felix da housecat' in rendered)
-
-    def test_filters(self):
-        "Testing the filters with the Translator filter"
-        stream = self.oot.generate(**self.data)
-        translated = stream.filter(Translator(pseudo_gettext))
-        translated_xml = translated.events.render()
-        ok_("Hello," in translated_xml)
-        ok_("I am an odt templating test" in translated_xml)
-        ok_('Felix da housecat' not in translated_xml)
-        ok_('Félix le chat de la maison' in translated_xml)
-        ok_('We sell stuff' not in translated_xml)
-        ok_('On vend des choses' in translated_xml)
-
-    def test_images(self):
-        "Testing the image replacement directive"
-        stream = self.oot.generate(**self.data)
-        rendered = stream.events.render()
-        styles_idx = rendered.find('<?relatorio styles.xml?>')
-        tree = lxml.etree.parse(StringIO(rendered[25:styles_idx]))
-        root = tree.getroot()
-        images = root.xpath('//draw:frame', namespaces=self.oot.namespaces)
-        eq_(len(images), 3)
-        eq_(images[0].get('{%s}name' % self.oot.namespaces['draw']),
-            "image: (oeuf, 'image/png')")
-        eq_(images[1].get('{%s}name' % self.oot.namespaces['draw']),
-            'image: img')
-        eq_(images[1].get('{%s}width' % self.oot.namespaces['svg']),
-            '1.732cm')
-        eq_(images[1].get('{%s}height' % self.oot.namespaces['svg']),
-            '1.513cm')
-        eq_(images[2].get('{%s}width' % self.oot.namespaces['svg']),
-            '1.732cm')
-        eq_(images[2].get('{%s}height' % self.oot.namespaces['svg']),
-            '1.513cm')
-
-    def test_regexp(self):
-        "Testing the regexp used to find relatorio tags"
-        # a valid expression
-        group = GENSHI_EXPR.match('for each="foo in bar"').groups()
-        eq_(group, (None, 'for', 'each', 'foo in bar'))
-
-        # invalid expr
-        group = GENSHI_EXPR.match('foreach="foo in bar"').groups()
-        eq_(group, (None, None, None, None))
-
-        # valid closing tags
-        group = GENSHI_EXPR.match('/for').groups()
-        eq_(group, ('/', 'for', None, None))
-        group = GENSHI_EXPR.match('/for ').groups()
-        eq_(group, ('/', 'for', None, None))
-
-        # another non matching expr
-        group = GENSHI_EXPR.match('formatLang("en")').groups()
-        eq_(group, (None, None, None, None))
-
-    def test_str(self):
-        "Testing that a RelatorioStream str returns a bitstream"
-        stream = str(self.oot.generate(**self.data))
-        ok_(isinstance(stream, str))
diff --git a/relatorio/tests/two.png b/relatorio/tests/two.png
deleted file mode 100644
index f7d65d5..0000000
Binary files a/relatorio/tests/two.png and /dev/null differ
diff --git a/setup.cfg b/setup.cfg
index f22112a..861a9f5 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -1,2 +1,5 @@
 [egg_info]
+tag_build = 
+tag_date = 0
+tag_svn_revision = 0
 
commit 4f381a7571d9b611f1a1842718bc1a8ef46cee0f
Author: Daniel Baumann <daniel at debian.org>
Date:   Mon Jun 28 20:35:29 2010 +0200

    Updating standards version to 3.9.0.

diff --git a/debian/control b/debian/control
index ad5ba98..aa6bc5a 100644
--- a/debian/control
+++ b/debian/control
@@ -8,7 +8,7 @@ Uploaders:
 Dm-Upload-Allowed: yes
 Build-Depends:
  debhelper (>= 7), python, python-genshi, python-setuptools, python-support
-Standards-Version: 3.8.4
+Standards-Version: 3.9.0
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
 Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
commit a209d8d0eb7cb3c34a04e850d1ac61d8cc94a664
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat May 15 12:52:18 2010 +0200

    Wrapping depends.

diff --git a/debian/control b/debian/control
index e1b1f40..ad5ba98 100644
--- a/debian/control
+++ b/debian/control
@@ -15,7 +15,9 @@ Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
 
 Package: python-relatorio
 Architecture: all
-Depends: ${misc:Depends}, ${python:Depends}, python-genshi, python-lxml, python-pkg-resources
+Depends:
+ ${misc:Depends}, ${python:Depends}, python-genshi, python-lxml,
+ python-pkg-resources
 XB-Python-Version: ${python:Versions}
 Suggests: python-pycha, python-yaml
 Description: Python module to create reports from Python objects
commit 3d59f5401095320beb05ae006e65db7f8f7d9197
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat Apr 24 11:13:39 2010 +0200

    Releasing debian version 0.5.4-1.

diff --git a/debian/changelog b/debian/changelog
index 3e54562..68025e2 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,10 @@
+relatorio (0.5.4-1) unstable; urgency=low
+
+  * Adding Dm-Upload-Allowed in control in preparation for Mathias.
+  * Merging upstream version 0.5.4.
+
+ -- Daniel Baumann <daniel at debian.org>  Sat, 24 Apr 2010 11:13:29 +0200
+
 relatorio (0.5.3-1) unstable; urgency=low
 
   * Merging upstream version 0.5.3.
commit 9ab7f7d355d4423e610b1584266ccd813287260d
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat Apr 24 11:13:06 2010 +0200

    Merging upstream version 0.5.4.

diff --git a/CHANGES b/CHANGES
index cd70c7a..ed0d702 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,6 @@
+0.5.4 - 20100330
+ * Update manifest.xml with added files in opendocument
+ * Do not write empty width or height attributes in opendocument
  * Update py:attrs attributes in opendocument
 
 0.5.3 - 20100110
diff --git a/relatorio/__init__.py b/relatorio/__init__.py
index 6d06e8c..f28b310 100644
--- a/relatorio/__init__.py
+++ b/relatorio/__init__.py
@@ -12,4 +12,4 @@ and report together, find reports by mimetypes/name/python objects.
 from relatorio.reporting import MIMETemplateLoader, ReportRepository, Report
 import templates
 
-__version__ = '0.5.4'
+__version__ = '0.5.5'
diff --git a/relatorio/templates/opendocument.py b/relatorio/templates/opendocument.py
index 41730d7..568eb2e 100644
--- a/relatorio/templates/opendocument.py
+++ b/relatorio/templates/opendocument.py
@@ -74,6 +74,7 @@ EXTENSIONS = {'image/png': 'png',
 
 RELATORIO_URI = 'http://relatorio.openhex.org/'
 GENSHI_URI = 'http://genshi.edgewall.org/'
+MANIFEST = 'META-INF/manifest.xml'
 output_encode = genshi.output.encode
 EtreeElement = lxml.etree.Element
 
@@ -109,8 +110,9 @@ class OOTemplateError(genshi.template.base.TemplateSyntaxError):
 class ImageHref:
     "A class used to add images in the odf zipfile"
 
-    def __init__(self, zfile, context):
+    def __init__(self, zfile, manifest, context):
         self.zip = zfile
+        self.manifest = manifest
         self.context = context.copy()
 
     def __call__(self, expr):
@@ -125,6 +127,7 @@ class ImageHref:
         path = 'Pictures/%s.%s' % (name, EXTENSIONS[mimetype])
         if path not in self.zip.namelist():
             self.zip.writestr(path, file_content)
+            self.manifest.add_file_entry(path, mimetype)
         return {'{http://www.w3.org/1999/xlink}href': path}
 
 
@@ -139,8 +142,12 @@ class ImageDimension:
         # or (bitstreamm mimetype, width, height)
         if len(expr) == 4:
             width, height = expr[2:]
-        return {'{%s}width' % self.namespaces['svg']: width,
-                '{%s}height' % self.namespaces['svg']: height}
+        attrs = {}
+        if width:
+            attrs['{%s}width' % self.namespaces['svg']] = width
+        if height:
+            attrs['{%s}height' % self.namespaces['svg']] = height
+        return attrs
 
 
 class ColumnCounter:
@@ -658,7 +665,9 @@ class Template(MarkupTemplate):
     def generate(self, *args, **kwargs):
         "creates the RelatorioStream."
         serializer = OOSerializer(self.filepath)
-        kwargs['__relatorio_make_href'] = ImageHref(serializer.outzip, kwargs)
+        kwargs['__relatorio_make_href'] = ImageHref(serializer.outzip,
+                                                    serializer.manifest,
+                                                    kwargs)
         kwargs['__relatorio_make_dimension'] = ImageDimension(self.namespaces)
         kwargs['__relatorio_guess_type'] = guess_type
 
@@ -708,10 +717,33 @@ class DuplicateColumnHeaders(object):
                 yield mark, (kind, data, pos)
 
 
+class Manifest(object):
+
+    def __init__(self, content):
+        self.tree = lxml.etree.parse(StringIO(content))
+        self.root = self.tree.getroot()
+        self.namespaces = self.root.nsmap
+
+    def __str__(self):
+        return lxml.etree.tostring(self.tree, encoding='UTF-8',
+                                   xml_declaration=True)
+
+    def add_file_entry(self, path, mimetype=None):
+        manifest_namespace = self.namespaces['manifest']
+        attribs = {'media-type': mimetype or '',
+                   'full-path': path}
+        entry_node = EtreeElement('{%s}%s' % (manifest_namespace,
+                                              'file-entry'),
+                                  attrib=attribs,
+                                  nsmap={'manifest': manifest_namespace})
+        self.root.append(entry_node)
+
+
 class OOSerializer:
 
     def __init__(self, oo_path):
         self.inzip = zipfile.ZipFile(oo_path)
+        self.manifest = Manifest(self.inzip.read(MANIFEST))
         self.new_oo = StringIO()
         self.outzip = zipfile.ZipFile(self.new_oo, 'w')
         self.xml_serializer = genshi.output.XMLSerializer()
@@ -737,6 +769,8 @@ class OOSerializer:
                     setattr(new_info, attr, getattr(f_info, attr))
                 serialized_stream = output_encode(self.xml_serializer(stream))
                 self.outzip.writestr(new_info, serialized_stream)
+            elif f_info.filename == MANIFEST:
+                self.outzip.writestr(f_info, str(self.manifest))
             else:
                 self.outzip.writestr(f_info, self.inzip.read(f_info.filename))
         self.inzip.close()
diff --git a/setup.py b/setup.py
index 844ea8c..ef10e1a 100644
--- a/setup.py
+++ b/setup.py
@@ -31,7 +31,7 @@ and report together, find reports by mimetypes/name/python objects.
     packages=find_packages(exclude=['relatorio.tests', 'examples']),
     install_requires=[
         "Genshi >= 0.5",
-        "lxml >= 1.3.6"
+        "lxml >= 2.0"
     ],
     classifiers=[
         "Development Status :: 4 - Beta",
commit 8e398975cb0bd2bdbb5acc9d73c821f8743ad346
Author: Daniel Baumann <daniel at debian.org>
Date:   Fri Apr 9 14:31:32 2010 +0200

    Adding Dm-Upload-Allowed in control in preparation for Mathias.

diff --git a/debian/control b/debian/control
index 209acb6..e1b1f40 100644
--- a/debian/control
+++ b/debian/control
@@ -5,6 +5,7 @@ Maintainer: Debian Tryton Maintainers <tryton at lists.debian-maintainers.org>
 Uploaders:
  Daniel Baumann <daniel at debian.org>,
  Mathias Behrle <mathiasb at mbsolutions.selfip.biz>
+Dm-Upload-Allowed: yes
 Build-Depends:
  debhelper (>= 7), python, python-genshi, python-setuptools, python-support
 Standards-Version: 3.8.4
commit 5d133c70c48a2b83de57afb0ea436a1fa0dbdfe8
Author: Daniel Baumann <daniel at debian.org>
Date:   Sun Mar 14 13:27:59 2010 +0100

    Releasing debian version 0.5.3-1.

diff --git a/debian/changelog b/debian/changelog
index 366757e..3e54562 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,11 @@
+relatorio (0.5.3-1) unstable; urgency=low
+
+  * Merging upstream version 0.5.3.
+  * Updating copyright file to reflect license changes (GPL-2+ to GPL-
+    3+).
+
+ -- Daniel Baumann <daniel at debian.org>  Sun, 14 Mar 2010 13:27:47 +0100
+
 relatorio (0.5.2-2) unstable; urgency=low
 
   * Adding explicit debian source version 1.0 until switch to 3.0.
commit 13f0ba7e8a5b9c32326cfaeaa77bcf5f0880cb58
Author: Daniel Baumann <daniel at debian.org>
Date:   Sun Mar 14 13:27:28 2010 +0100

    Updating copyright file to reflect license changes (GPL-2+ to GPL-3+).

diff --git a/debian/copyright b/debian/copyright
index f075842..1892a2d 100644
--- a/debian/copyright
+++ b/debian/copyright
@@ -4,12 +4,12 @@ Maintainer-Contact: Debian Tryton Maintainers <tryton at lists.debian-maintainers.o
 Maintainer-Homepage: http://tryton.debian-maintainers.org/
 
 Files: *
-Copyright: (C) 2007-2009 OpenHex SPRL <http://www.openhex.com/>
-License: GPL-2+
- This program 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; either version 2
- of the License, or (at your option) any later version.
+Copyright: (C) 2007-2010 OpenHex SPRL <http://www.openhex.com/>
+License: GPL-3+
+ This program 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, either version 3 of the License, or
+ (at your option) any later version.
  .
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -17,19 +17,18 @@ License: GPL-2+
  GNU General Public License for more details.
  .
  You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
  .
  On Debian systems, the complete text of the GNU General Public License
- can be found in /usr/share/common-licenses/GPL-2 file.
+ can be found in /usr/share/common-licenses/GPL-3 file.
 
 Files: debian/*
 Copyright: (C) 2009-2010 Daniel Baumann <daniel at debian.org>
-License: GPL-2+
- This program 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; either version 2
- of the License, or (at your option) any later version.
+License: GPL-3+
+ This program 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, either version 3 of the License, or
+ (at your option) any later version.
  .
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -37,8 +36,7 @@ License: GPL-2+
  GNU General Public License for more details.
  .
  You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
  .
  On Debian systems, the complete text of the GNU General Public License
- can be found in /usr/share/common-licenses/GPL-2 file.
+ can be found in /usr/share/common-licenses/GPL-3 file.
commit 0f899afdadf90b629d5ab6b18e856a71b58884f4
Author: Daniel Baumann <daniel at debian.org>
Date:   Sun Mar 14 13:25:56 2010 +0100

    Merging upstream version 0.5.3.

diff --git a/CHANGES b/CHANGES
index da475e5..cd70c7a 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,4 +1,12 @@
-0.5.2
+ * Update py:attrs attributes in opendocument
+
+0.5.3 - 20100110
+ * Escape elements values in opendocument template
+
+0.5.2 - 20091108
+ * Fix guess_type for long value
+ * Add width, height arguments for "image:" in odf
+ * Switch to GPL-3
  * Added support for Genshi {% include %} tags (patch by Simon Jagoe)
  * Nicer traceback message upon failed import
 
diff --git a/LICENSE b/LICENSE
index e37680c..94a9ed0 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,280 +1,674 @@
-		    GNU GENERAL PUBLIC LICENSE
-		       Version 2, June 1991
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
 
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
  Everyone is permitted to copy and distribute verbatim copies
  of this license document, but changing it is not allowed.
 
-			    Preamble
+                            Preamble
 
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.)  You can apply it to
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
 your programs, too.
 
   When we speak of free software, we are referring to freedom, not
 price.  Our General Public Licenses are designed to make sure that you
 have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
 
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
 
   For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
-
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
 
   The precise terms and conditions for copying, distribution and
 modification follow.
 
-		    GNU GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-  0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term "modification".)  Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
-  1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
-  2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
-    a) You must cause the modified files to carry prominent notices
-    stating that you changed the files and the date of any change.
-
-    b) You must cause any work that you distribute or publish, that in
-    whole or in part contains or is derived from the Program or any
-    part thereof, to be licensed as a whole at no charge to all third
-    parties under the terms of this License.
-
-    c) If the modified program normally reads commands interactively
-    when run, you must cause it, when started running for such
-    interactive use in the most ordinary way, to print or display an
-    announcement including an appropriate copyright notice and a
-    notice that there is no warranty (or else, saying that you provide
-    a warranty) and that users may redistribute the program under
-    these conditions, and telling the user how to view a copy of this
-    License.  (Exception: if the Program itself is interactive but
-    does not normally print such an announcement, your work based on
-    the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-  3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
-    a) Accompany it with the complete corresponding machine-readable
-    source code, which must be distributed under the terms of Sections
-    1 and 2 above on a medium customarily used for software interchange; or,
-
-    b) Accompany it with a written offer, valid for at least three
-    years, to give any third party, for a charge no more than your
-    cost of physically performing source distribution, a complete
-    machine-readable copy of the corresponding source code, to be
-    distributed under the terms of Sections 1 and 2 above on a medium
-    customarily used for software interchange; or,
-
-    c) Accompany it with the information you received as to the offer
-    to distribute corresponding source code.  (This alternative is
-    allowed only for noncommercial distribution and only if you
-    received the program in object code or executable form with such
-    an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable.  However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-  4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
-  5. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
-  6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
 this License.
 
-  7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
 otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
-
-  9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time.  Such new versions will
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
 be similar in spirit to the present version, but may differ in detail to
 address new problems or concerns.
 
-Each version is given a distinguishing version number.  If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation.  If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
-  10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission.  For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this.  Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
-			    NO WARRANTY
-
-  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
-  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-		     END OF TERMS AND CONDITIONS
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program 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, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program 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.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..a72bf8f
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,3 @@
+include AUTHORS
+include CHANGES
+include LICENSE
diff --git a/examples/basic.odt b/examples/basic.odt
index 3c74963..f82485e 100644
Binary files a/examples/basic.odt and b/examples/basic.odt differ
diff --git a/examples/columns.odt b/examples/columns.odt
index 0deafd5..017e251 100644
Binary files a/examples/columns.odt and b/examples/columns.odt differ
diff --git a/examples/common.py b/examples/common.py
index 4806372..5eb636b 100644
--- a/examples/common.py
+++ b/examples/common.py
@@ -1,3 +1,5 @@
+from os.path import join, dirname
+
 class Invoice(dict):
 
     @property
@@ -36,5 +38,6 @@ inv = Invoice(customer={'name': 'John Bonham',
                     ],
               id='MZY-20080703',
               status='late',
-              bottle=(file('bouteille.png', 'r'), 'image/png'))
+              bottle=(file(join(dirname(__file__), 'bouteille.png'), 'r'),
+                  'image/png'))
 
diff --git a/examples/demo_chart.py b/examples/demo_chart.py
index d2b621c..06392fd 100644
--- a/examples/demo_chart.py
+++ b/examples/demo_chart.py
@@ -1,15 +1,23 @@
-from os.path import abspath
+from os.path import abspath, join, dirname
 from relatorio import Report
 
 # test data
 from common import inv
 
 if __name__ == '__main__':
-    pie_report = Report(abspath('pie_chart'), 'image/png')
-    file('pie.png', 'wb').write(pie_report(o=inv).render().getvalue())
-    hbar_report = Report(abspath('hbar_chart'), 'image/svg')
-    file('hbar.svg', 'wb').write(hbar_report(o=inv).render().getvalue())
-    vbar_report = Report(abspath('vbar_chart'), 'image/svg')
-    file('vbar.svg', 'wb').write(vbar_report(o=inv).render().getvalue())
-    line_report = Report(abspath('line_chart'), 'image/png')
-    file('line.png', 'wb').write(line_report(o=inv).render().getvalue())
+    pie_report = Report(abspath(join(dirname(__file__), 'pie_chart')),
+            'image/png')
+    file(join(dirname(__file__), 'pie.png'), 'wb').write(
+            pie_report(o=inv).render().getvalue())
+    hbar_report = Report(abspath(join(dirname(__file__), 'hbar_chart')),
+            'image/svg')
+    file(join(dirname(__file__), 'hbar.svg'), 'wb').write(
+            hbar_report(o=inv).render().getvalue())
+    vbar_report = Report(abspath(join(dirname(__file__), 'vbar_chart')),
+            'image/svg')
+    file(join(dirname(__file__), 'vbar.svg'), 'wb').write(
+            vbar_report(o=inv).render().getvalue())
+    line_report = Report(abspath(join(dirname(__file__), 'line_chart')),
+            'image/png')
+    file(join(dirname(__file__), 'line.png'), 'wb').write(
+            line_report(o=inv).render().getvalue())
diff --git a/examples/demo_context.py b/examples/demo_context.py
index 67a2897..0013e0a 100644
--- a/examples/demo_context.py
+++ b/examples/demo_context.py
@@ -1,4 +1,4 @@
-from os.path import abspath
+from os.path import abspath, join, dirname
 from relatorio import Report
 
 # test data
@@ -7,8 +7,9 @@ from common import inv
 #PDF
 if __name__ == '__main__':
     print "generating output_basic.pdf... ",
-    report = Report(abspath('basic.tex'), 'application/pdf')
+    report = Report(abspath(join(dirname(__file__), 'basic.tex')),
+        'application/pdf')
     content = report(o=inv).render().getvalue()
-    file('output_basic.pdf', 'wb').write(content)
+    file(join(dirname(__file__), 'output_basic.pdf'), 'wb').write(content)
     print "done"
 
diff --git a/examples/demo_odf.py b/examples/demo_odf.py
index b6ed72a..d4fae8f 100644
--- a/examples/demo_odf.py
+++ b/examples/demo_odf.py
@@ -1,4 +1,4 @@
-from os.path import abspath
+from os.path import abspath, join, dirname
 from relatorio import Report
 
 # test data
@@ -11,9 +11,9 @@ ODP_MIME = 'application/vnd.oasis.opendocument.presentation'
 if __name__ == '__main__':
     # ODT
     print "generating output_basic.odt... ",
-    report = Report(abspath('basic.odt'), ODT_MIME)
+    report = Report(abspath(join(dirname(__file__), 'basic.odt')), ODT_MIME)
     content = report(o=inv).render().getvalue()
-    file('output_basic.odt', 'wb').write(content)
+    file(join(dirname(__file__), 'output_basic.odt'), 'wb').write(content)
     print "done"
 
     # we could also use an opendocument template directly
@@ -24,37 +24,41 @@ if __name__ == '__main__':
 
     print "generating output_complicated.odt... ",
     # Add a chart to the invoice
-    inv['chart'] = (Report(abspath('pie_chart'), 'image/png'), 'image/png')
-    report = Report(abspath('complicated.odt'), ODT_MIME)
+    inv['chart'] = (Report(abspath(join(dirname(__file__), 'pie_chart')),
+        'image/png'), 'image/png')
+    report = Report(abspath(join(dirname(__file__), 'complicated.odt')),
+            ODT_MIME)
     content = report(o=inv).render().getvalue()
-    file('output_complicated.odt', 'wb').write(content)
+    file(join(dirname(__file__), 'output_complicated.odt'), 'wb').write(content)
     print "done"
 
     print "generating output_columns.odt... ",
-    report = Report(abspath('columns.odt'), ODT_MIME)
+    report = Report(abspath(join(dirname(__file__), 'columns.odt')), ODT_MIME)
     lst = [[], ['i'], ['a', 'b'], [1, 2, 3], ['I', 'II', 'III', 'IV']]
     titles = ['first', 'second', 'third', 'fourth']
     content = report(titles=titles, lst=lst).render().getvalue()
-    file('output_columns.odt', 'wb').write(content)
+    file(join(dirname(__file__), 'output_columns.odt'), 'wb').write(content)
     print "done"
 
     # ODS
     print "generating output_pivot.ods... ",
-    report = Report(abspath('pivot.ods'), ODS_MIME)
+    report = Report(abspath(join(dirname(__file__), 'pivot.ods')), ODS_MIME)
     content = report(o=inv).render().getvalue()
-    file('output_pivot.ods', 'wb').write(content)
+    file(join(dirname(__file__), 'output_pivot.ods'), 'wb').write(content)
     print "done"
 
     print "generating output_sheets.ods... ",
-    report = Report(abspath('demo_sheets.ods'), ODS_MIME)
+    report = Report(abspath(join(dirname(__file__), 'demo_sheets.ods')),
+            ODS_MIME)
     content = report(lst=lst).render().getvalue()
-    file('output_sheets.ods', 'wb').write(content)
+    file(join(dirname(__file__), 'output_sheets.ods'), 'wb').write(content)
     print "done"
 
     # ODP
     print "generating output_presentation.odp... ",
-    report = Report(abspath('presentation.odp'), ODP_MIME)
+    report = Report(abspath(join(dirname(__file__), 'presentation.odp')),
+            ODP_MIME)
     content = report(o=inv).render().getvalue()
-    file('output_presentation.odp', 'wb').write(content)
+    file(join(dirname(__file__), 'output_presentation.odp'), 'wb').write(content)
     print "done"
 
diff --git a/examples/demo_repository.py b/examples/demo_repository.py
index 38ac4df..84bdd92 100644
--- a/examples/demo_repository.py
+++ b/examples/demo_repository.py
@@ -1,5 +1,6 @@
 import relatorio
 from common import Invoice, inv
+from os.path import join, dirname
 
 ODT_MIME = 'application/vnd.oasis.opendocument.text'
 ODS_MIME = 'application/vnd.oasis.opendocument.spreadsheet'
@@ -27,5 +28,5 @@ if __name__ == '__main__':
         print "generating '%s'..." % filename,
         report, mimetype, desc = repository.by_id(Invoice, report_name)
         data = report(o=inv).render().getvalue()
-        file(filename, 'wb').write(data)
+        file(join(dirname(__file__), filename), 'wb').write(data)
         print "done"
diff --git a/examples/demo_sheets.ods b/examples/demo_sheets.ods
index 81c321d..61c4706 100644
Binary files a/examples/demo_sheets.ods and b/examples/demo_sheets.ods differ
diff --git a/examples/presentation.odp b/examples/presentation.odp
index 26a7980..7d08b92 100644
Binary files a/examples/presentation.odp and b/examples/presentation.odp differ
diff --git a/relatorio/__init__.py b/relatorio/__init__.py
index 8812033..6d06e8c 100644
--- a/relatorio/__init__.py
+++ b/relatorio/__init__.py
@@ -12,4 +12,4 @@ and report together, find reports by mimetypes/name/python objects.
 from relatorio.reporting import MIMETemplateLoader, ReportRepository, Report
 import templates
 
-__version__ = '0.5.1'
+__version__ = '0.5.4'
diff --git a/relatorio/reporting.py b/relatorio/reporting.py
index d29fd28..676e8d3 100644
--- a/relatorio/reporting.py
+++ b/relatorio/reporting.py
@@ -5,7 +5,7 @@
 #
 # This program 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; either version 2 of the License, or (at your option) any later
+# Foundation; either version 3 of the License, or (at your option) any later
 # version.
 #
 # This program is distributed in the hope that it will be useful, but WITHOUT
diff --git a/relatorio/templates/__init__.py b/relatorio/templates/__init__.py
index 7034973..8bc7307 100644
--- a/relatorio/templates/__init__.py
+++ b/relatorio/templates/__init__.py
@@ -5,7 +5,7 @@
 #
 # This program 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; either version 2 of the License, or (at your option) any later
+# Foundation; either version 3 of the License, or (at your option) any later
 # version.
 #
 # This program is distributed in the hope that it will be useful, but WITHOUT
diff --git a/relatorio/templates/base.py b/relatorio/templates/base.py
index ba9c1c9..dfc9a38 100644
--- a/relatorio/templates/base.py
+++ b/relatorio/templates/base.py
@@ -5,7 +5,7 @@
 #
 # This program 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; either version 2 of the License, or (at your option) any later
+# Foundation; either version 3 of the License, or (at your option) any later
 # version.
 #
 # This program is distributed in the hope that it will be useful, but WITHOUT
diff --git a/relatorio/templates/chart.py b/relatorio/templates/chart.py
index 8b4765c..6c6ba8a 100644
--- a/relatorio/templates/chart.py
+++ b/relatorio/templates/chart.py
@@ -5,7 +5,7 @@
 #
 # This program 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; either version 2 of the License, or (at your option) any later
+# Foundation; either version 3 of the License, or (at your option) any later
 # version.
 #
 # This program is distributed in the hope that it will be useful, but WITHOUT
diff --git a/relatorio/templates/opendocument.py b/relatorio/templates/opendocument.py
index d0eef78..41730d7 100644
--- a/relatorio/templates/opendocument.py
+++ b/relatorio/templates/opendocument.py
@@ -1,11 +1,12 @@
 ###############################################################################
 #
+# Copyright (c) 2009 Cedric Krier.
 # Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
 # Reserved.
 #
 # This program 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; either version 2 of the License, or (at your option) any later
+# Foundation; either version 3 of the License, or (at your option) any later
 # version.
 #
 # This program is distributed in the hope that it will be useful, but WITHOUT
@@ -44,6 +45,7 @@ from genshi.template import MarkupTemplate
 from genshi.filters import Transformer
 from genshi.filters.transform import ENTER, EXIT
 from genshi.core import Stream
+from genshi.template.interpolation import PREFIX
 
 
 from relatorio.templates.base import RelatorioStream
@@ -97,7 +99,7 @@ EtreeElement = lxml.etree.Element
 def guess_type(val):
     if isinstance(val, (str, unicode)):
         return 'string'
-    elif isinstance(val, (int, float)):
+    elif isinstance(val, (int, float, long)):
         return 'float'
 
 class OOTemplateError(genshi.template.base.TemplateSyntaxError):
@@ -112,7 +114,7 @@ class ImageHref:
         self.context = context.copy()
 
     def __call__(self, expr):
-        bitstream, mimetype = expr
+        bitstream, mimetype = expr[:2]
         if isinstance(bitstream, Report):
             bitstream = bitstream(**self.context).render()
         elif isinstance(bitstream, ChartTemplate):
@@ -126,6 +128,21 @@ class ImageHref:
         return {'{http://www.w3.org/1999/xlink}href': path}
 
 
+class ImageDimension:
+    "A class used to set dimension in draw tags"
+
+    def __init__(self, namespaces):
+        self.namespaces = namespaces
+
+    def __call__(self, expr, width, height):
+        # expr could be (bitstream, mimetype)
+        # or (bitstreamm mimetype, width, height)
+        if len(expr) == 4:
+            width, height = expr[2:]
+        return {'{%s}width' % self.namespaces['svg']: width,
+                '{%s}height' % self.namespaces['svg']: height}
+
+
 class ColumnCounter:
     """A class used to count the actual maximum number of cells (and thus
     columns) a table contains accross its rows.
@@ -168,6 +185,20 @@ def wrap_nodes_between(first, last, new_parent):
     old_parent.remove(last)
 
 
+def update_py_attrs(node, value):
+    """An helper function to update py_attrs of a node.
+    """
+    if not value:
+        return
+    py_attrs_attr = '{%s}attrs' % GENSHI_URI
+    if not py_attrs_attr in node.attrib:
+        node.attrib[py_attrs_attr] = value
+    else:
+        node.attrib[py_attrs_attr] = \
+                "(lambda x, y: x.update(y) or x)(%s or {}, %s or {})" % \
+                (node.attrib[py_attrs_attr], value)
+
+
 class Template(MarkupTemplate):
 
     def __init__(self, source, filepath=None, filename=None, loader=None,
@@ -227,7 +258,8 @@ class Template(MarkupTemplate):
             "draw": "urn:draw",
             "table": "urn:table",
             "office": "urn:office",
-            "xlink": "urn:xlink"
+            "xlink": "urn:xlink",
+            "svg": "urn:svg",
         }
         # but override them with the real namespaces
         self.namespaces.update(root.nsmap)
@@ -242,6 +274,7 @@ class Template(MarkupTemplate):
         self._handle_relatorio_tags(tree)
         self._handle_images(tree)
         self._handle_innerdocs(tree)
+        self._escape_values(tree)
         return StringIO(lxml.etree.tostring(tree))
 
     def _invert_style(self, tree):
@@ -397,8 +430,8 @@ class Template(MarkupTemplate):
                 # The grand-parent tag is a table cell we should set the
                 # correct value and type for this cell.
                 dico = "{'%s': %s, '%s': __relatorio_guess_type(%s)}"
-                parent.attrib[py_attrs_attr] = dico % (office_name, expr,
-                                                       office_valuetype, expr)
+                update_py_attrs(parent, dico %
+                        (office_name, expr, office_valuetype, expr))
                 parent.attrib.pop(office_valuetype, None)
                 parent.attrib.pop(office_name, None)
 
@@ -428,16 +461,15 @@ class Template(MarkupTemplate):
         # Note that table_name is not needed in the first two
         # operations, but a unique id within the table is required
         # to support nested column repetition
-        ancestor.attrib[py_attrs_attr] = \
-            "__relatorio_reset_col_count(%d)" % loop_id
+        update_py_attrs(ancestor, "__relatorio_reset_col_count(%d)" % loop_id)
 
         # 2) add increment code (through a py:attrs attribute) on
         #    the first cell node after the opening (cell node)
         #    ancestor
         enclosed_cell = outer_o_node.getnext()
         assert enclosed_cell.tag == '{%s}table-cell' % table_namespace
-        enclosed_cell.attrib[py_attrs_attr] = \
-            "__relatorio_inc_col_count(%d)" % loop_id
+        update_py_attrs(enclosed_cell, "__relatorio_inc_col_count(%d)" %
+                loop_id)
 
         # 3) add "store count" code as a py:replace node, as the
         #    last child of the row
@@ -587,15 +619,23 @@ class Template(MarkupTemplate):
         draw_name = '{%s}name' % draw_namespace
         draw_image = '{%s}image' % draw_namespace
         py_attrs = '{%s}attrs' % self.namespaces['py']
+        svg_namespace = self.namespaces['svg']
+        svg_width = '{%s}width' % svg_namespace
+        svg_height = '{%s}height' % svg_namespace
         xpath_expr = "//draw:frame[starts-with(@draw:name, 'image:')]"
         for draw in tree.xpath(xpath_expr, namespaces=self.namespaces):
-            d_name = draw.attrib[draw_name]
-            attr_expr = "__relatorio_make_href(%s)" % d_name[7:]
+            d_name = draw.attrib[draw_name][6:].strip()
+            attr_expr = "__relatorio_make_href(%s)" % d_name
             image_node = EtreeElement(draw_image,
                                       attrib={py_attrs: attr_expr},
                                       nsmap={'draw': draw_namespace,
                                              'py': GENSHI_URI})
             draw.replace(draw[0], image_node)
+            width = draw.attrib.pop(svg_width, None)
+            height = draw.attrib.pop(svg_height, None)
+            attr_expr = "__relatorio_make_dimension(%s, '%s', '%s')" % \
+                    (d_name, width, height)
+            draw.attrib[py_attrs] = attr_expr
 
     def _handle_innerdocs(self, tree):
         "finds inner_docs and adds them to the processing stack."
@@ -605,10 +645,21 @@ class Template(MarkupTemplate):
         for draw in tree.xpath(xpath_expr, namespaces=self.namespaces):
             self.inner_docs.append(draw.attrib[href_attrib][2:])
 
+    def _escape_values(self, tree):
+        "escapes element values"
+        for element in tree.iter():
+            for attrs in element.keys():
+                if not attrs.startswith('{%s}' % GENSHI_URI):
+                    element.attrib[attrs] = element.attrib[attrs]\
+                            .replace(PREFIX, PREFIX * 2)
+            if element.text:
+                element.text = element.text.replace(PREFIX, PREFIX * 2)
+
     def generate(self, *args, **kwargs):
         "creates the RelatorioStream."
         serializer = OOSerializer(self.filepath)
         kwargs['__relatorio_make_href'] = ImageHref(serializer.outzip, kwargs)
+        kwargs['__relatorio_make_dimension'] = ImageDimension(self.namespaces)
         kwargs['__relatorio_guess_type'] = guess_type
 
         counter = ColumnCounter()
diff --git a/relatorio/templates/pdf.py b/relatorio/templates/pdf.py
index d515af1..20ac2a4 100644
--- a/relatorio/templates/pdf.py
+++ b/relatorio/templates/pdf.py
@@ -5,7 +5,7 @@
 #
 # This program 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; either version 2 of the License, or (at your option) any later
+# Foundation; either version 3 of the License, or (at your option) any later
 # version.
 #
 # This program is distributed in the hope that it will be useful, but WITHOUT
@@ -33,7 +33,7 @@ from genshi.template import NewTextTemplate
 from relatorio.templates.base import RelatorioStream
 from relatorio.reporting import MIMETemplateLoader
 
-TEXEXEC_PATH = '/usr/bin/texexec'
+TEXEXEC = 'texexec'
 _encode = genshi.output.encode
 
 
@@ -57,7 +57,7 @@ class PDFSerializer:
         tex_file.write(_encode(self.text_serializer(stream)))
         tex_file.close()
 
-        subprocess.check_call([TEXEXEC_PATH, '--purge', 'report.tex'],
+        subprocess.check_call([TEXEXEC, '--purge', 'report.tex'],
                               cwd=self.working_dir)
 
         pdf = StringIO()
diff --git a/relatorio/tests/test.odt b/relatorio/tests/test.odt
index a077357..6c3e196 100644
Binary files a/relatorio/tests/test.odt and b/relatorio/tests/test.odt differ
diff --git a/relatorio/tests/test_api.py b/relatorio/tests/test_api.py
index 990e0d6..09d7727 100644
--- a/relatorio/tests/test_api.py
+++ b/relatorio/tests/test_api.py
@@ -5,7 +5,7 @@
 #
 # This program 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; either version 2 of the License, or (at your option) any later
+# Foundation; either version 3 of the License, or (at your option) any later
 # version.
 #
 # This program is distributed in the hope that it will be useful, but WITHOUT
diff --git a/relatorio/tests/test_odt.py b/relatorio/tests/test_odt.py
index 853f966..1923e6b 100644
--- a/relatorio/tests/test_odt.py
+++ b/relatorio/tests/test_odt.py
@@ -6,7 +6,7 @@
 #
 # This program 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; either version 2 of the License, or (at your option) any later
+# Foundation; either version 3 of the License, or (at your option) any later
 # version.
 #
 # This program is distributed in the hope that it will be useful, but WITHOUT
@@ -31,7 +31,7 @@ from genshi.filters import Translator
 from genshi.core import PI
 from genshi.template.eval import UndefinedError
 
-from templates.opendocument import Template, GENSHI_EXPR, GENSHI_URI, \
+from relatorio.templates.opendocument import Template, GENSHI_EXPR, GENSHI_URI,\
                                    RELATORIO_URI
 
 OO_TABLE_NS = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"
diff --git a/setup.py b/setup.py
index ccb93e2..844ea8c 100644
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,3 @@
-# -*- encoding: utf-8 -*-
 import os
 import re
 from setuptools import setup, find_packages
@@ -10,9 +9,11 @@ def get_version():
 
 setup(
     name="relatorio",
-    url="http://relatorio.openhex.org",
+    url="http://relatorio.openhex.org/",
     author="Nicolas Evrard",
     author_email="nicoe at openhex.org",
+    maintainer=u"Cedric Krier",
+    maintainer_email="cedric.krier at b2ck.com",
     description="A templating library able to output odt and pdf files",
     long_description="""
 relatorio
commit fb17a63b5fde763917047c2e27f6b26febd78aa5
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat Feb 20 09:36:54 2010 +0100

    Releasing debian version 0.5.2-2.

diff --git a/debian/changelog b/debian/changelog
index b0bfddf..366757e 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,13 @@
+relatorio (0.5.2-2) unstable; urgency=low
+
+  * Adding explicit debian source version 1.0 until switch to 3.0.
+  * Updating year in copyright file.
+  * Removing unneeded python-all-dev from build-depends.
+  * Updating to standards 3.8.4.
+  * Updating README.source.
+
+ -- Daniel Baumann <daniel at debian.org>  Sat, 20 Feb 2010 09:36:50 +0100
+
 relatorio (0.5.2-1) unstable; urgency=low
 
   * Merging upstream version 0.5.2.
commit 6fe5279d9e33f9530c92c5bc9752dc64917210f7
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat Feb 20 09:36:21 2010 +0100

    Updating README.source.

diff --git a/debian/README.source b/debian/README.source
index dcc7ba3..18b6b24 100644
--- a/debian/README.source
+++ b/debian/README.source
@@ -32,6 +32,6 @@ upstream source. Changes, if any, are stored in the source package as diffs in
 debian/diff and are applied during the build. Current modifications can be
 applied to the source tree with:
 
-  $ quilt push -a
+  $ QUILT_PATCHES=debian/patches quilt push -a
 
 More information about Quilt can be found in the quilt package.
commit e291cc0f5af866b29cde7b45b0b18137284f7867
Author: Daniel Baumann <daniel at debian.org>
Date:   Thu Jan 28 07:53:20 2010 +0100

    Updating to standards 3.8.4.

diff --git a/debian/control b/debian/control
index c15265e..209acb6 100644
--- a/debian/control
+++ b/debian/control
@@ -7,7 +7,7 @@ Uploaders:
  Mathias Behrle <mathiasb at mbsolutions.selfip.biz>
 Build-Depends:
  debhelper (>= 7), python, python-genshi, python-setuptools, python-support
-Standards-Version: 3.8.3
+Standards-Version: 3.8.4
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
 Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
commit aa78d1d1c0c45a955b5dfbbff6603224119d3dde
Author: Daniel Baumann <daniel at debian.org>
Date:   Mon Jan 25 10:12:02 2010 +0100

    Removing unneeded python-all-dev from build-depends.

diff --git a/debian/control b/debian/control
index 6210b28..c15265e 100644
--- a/debian/control
+++ b/debian/control
@@ -6,8 +6,7 @@ Uploaders:
  Daniel Baumann <daniel at debian.org>,
  Mathias Behrle <mathiasb at mbsolutions.selfip.biz>
 Build-Depends:
- debhelper (>= 7), python, python-all-dev, python-genshi, python-setuptools,
- python-support
+ debhelper (>= 7), python, python-genshi, python-setuptools, python-support
 Standards-Version: 3.8.3
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
commit dfd13f41c5b7bc692bd73d206960f90b3a8be98a
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat Jan 2 11:34:50 2010 +0100

    Updating year in copyright file.

diff --git a/debian/copyright b/debian/copyright
index 264867c..f075842 100644
--- a/debian/copyright
+++ b/debian/copyright
@@ -24,7 +24,7 @@ License: GPL-2+
  can be found in /usr/share/common-licenses/GPL-2 file.
 
 Files: debian/*
-Copyright: (C) 2009 Daniel Baumann <daniel at debian.org>
+Copyright: (C) 2009-2010 Daniel Baumann <daniel at debian.org>
 License: GPL-2+
  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
commit fa922f93faf155609fba0913b55ba4e95f4c37b4
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat Dec 12 10:06:07 2009 +0100

    Adding explicit debian source version 1.0 until switch to 3.0.

diff --git a/debian/source/format b/debian/source/format
new file mode 100644
index 0000000..d3827e7
--- /dev/null
+++ b/debian/source/format
@@ -0,0 +1 @@
+1.0
commit e1cba07a33a1b93da2aff3be13e4aa4fea544cc0
Author: Daniel Baumann <daniel at debian.org>
Date:   Tue Oct 6 21:01:09 2009 +0200

    Releasing debian version 0.5.2-1.

diff --git a/debian/changelog b/debian/changelog
index 571071b..b0bfddf 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,9 @@
+relatorio (0.5.2-1) unstable; urgency=low
+
+  * Merging upstream version 0.5.2.
+
+ -- Daniel Baumann <daniel at debian.org>  Tue, 06 Oct 2009 21:00:59 +0200
+
 relatorio (0.5.1-5) unstable; urgency=low
 
   [ Mathias Behrle ]
commit 0c201ad6d1d78d4920bc5f203f7e5e883c9a913b
Author: Daniel Baumann <daniel at debian.org>
Date:   Tue Oct 6 21:00:44 2009 +0200

    Merging upstream version 0.5.2.

diff --git a/CHANGES b/CHANGES
index e0b42f9..da475e5 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,7 @@
+0.5.2
+ * Added support for Genshi {% include %} tags (patch by Simon Jagoe)
+ * Nicer traceback message upon failed import
+
 0.5.1 - 20090416
  * Simplified the examples
  * Fix usage of tags without attributes (choose & otherwise)
diff --git a/examples/demo_repository.py b/examples/demo_repository.py
index e3c9900..38ac4df 100644
--- a/examples/demo_repository.py
+++ b/examples/demo_repository.py
@@ -16,7 +16,7 @@ repository.add_report(Invoice, 'image/png', 'pie_chart', report_name='pie')
 
 if __name__ == '__main__':
     # Add a chart to the invoice
-    inv['chart'] = repository.by_id(Invoice, 'pie')
+    inv['chart'] = repository.by_id(Invoice, 'pie')[:2]
 
     # Generate all reports on the invoice class
     for report_name, ext in (('basic', '.odt'),
@@ -25,7 +25,7 @@ if __name__ == '__main__':
                              ('presentation', '.odp')):
         filename = 'output_%s%s' % (report_name, ext)
         print "generating '%s'..." % filename,
-        report, mimetype = repository.by_id(Invoice, report_name)
+        report, mimetype, desc = repository.by_id(Invoice, report_name)
         data = report(o=inv).render().getvalue()
         file(filename, 'wb').write(data)
         print "done"
diff --git a/relatorio/reporting.py b/relatorio/reporting.py
index cccd6c1..d29fd28 100644
--- a/relatorio/reporting.py
+++ b/relatorio/reporting.py
@@ -68,11 +68,15 @@ class MIMETemplateLoader(TemplateLoader):
             if codename is not None:
                 return codename
 
-    def load(self, path, mime):
+    def load(self, path, mime=None, relative_to=None, cls=None):
         "returns a template object based on path"
-        rtype = self.get_type(mime)
-        return super(MIMETemplateLoader, self).load(path,
-                                                    cls=self.factories[rtype])
+        assert mime is not None or cls is not None
+
+        if mime is not None:
+            cls = self.factories[self.get_type(mime)]
+
+        return super(MIMETemplateLoader, self).load(
+            path, cls=cls, relative_to=relative_to)
 
     @classmethod
     def add_factory(cls, abbr_mimetype, template_factory, id_function=None):
@@ -89,6 +93,9 @@ class DefaultFactory:
 
     It just returns a copy of the data it receives"""
 
+    def __init__(self, *args, **kwargs):
+        pass
+
     def __call__(self, **kwargs):
         data = kwargs.copy()
         return data
@@ -138,7 +145,7 @@ class ReportRepository:
         self.loader = default_loader
 
     def add_report(self, klass, mimetype, template_path, data_factory=None,
-                   report_name='default'):
+                   report_name='default', description=''):
         """adds a report to the repository.
 
         You will be able to find the report via
@@ -151,9 +158,9 @@ class ReportRepository:
         if data_factory is None:
             data_factory = self.default_factory
         reports = self.classes.setdefault(klass, ReportDict())
-        report = Report(_absolute(template_path), mimetype, data_factory(),
-                        self.loader)
-        reports.ids[report_name] = report, mimetype
+        report = Report(_absolute(template_path), mimetype,
+                        data_factory(klass, mimetype), self.loader)
+        reports.ids[report_name] = report, mimetype, description
         reports.mimetypes.setdefault(mimetype, []) \
                          .append((report, report_name))
 
diff --git a/relatorio/templates/__init__.py b/relatorio/templates/__init__.py
index 21e20f2..7034973 100644
--- a/relatorio/templates/__init__.py
+++ b/relatorio/templates/__init__.py
@@ -20,6 +20,7 @@
 
 import traceback
 import warnings
+from cStringIO import StringIO
 
 plugins = ['base', 'opendocument', 'pdf', 'chart']
 
@@ -27,9 +28,13 @@ for name in plugins:
     try:
         __import__('relatorio.templates.%s' % name)
     except Exception, e:
-        warnings.warn("Unable to load plugin '%s', you will not be able "
-                      "to use it" % name)
-        print 'Original traceback'
-        print '-' * 80
-        print
-        traceback.print_exc()
+        tb_file = StringIO()
+
+        print >> tb_file, ("Unable to load plugin '%s', you will not be able "
+                           "to use it" % name)
+        print >> tb_file
+        print >> tb_file, 'Original traceback:'
+        print >> tb_file, '-------------------'
+        traceback.print_exc(file=tb_file)
+        print >> tb_file
+        warnings.warn(tb_file.getvalue())
diff --git a/relatorio/templates/opendocument.py b/relatorio/templates/opendocument.py
index e2b7a58..d0eef78 100644
--- a/relatorio/templates/opendocument.py
+++ b/relatorio/templates/opendocument.py
@@ -21,7 +21,12 @@
 __metaclass__ = type
 
 import re
-import md5
+try:
+    # requires python 2.5+
+    from hashlib import md5
+except ImportError:
+    from md5 import md5
+
 import time
 import urllib
 import zipfile
@@ -114,7 +119,7 @@ class ImageHref:
             bitstream = bitstream.generate(**self.context).render()
         bitstream.seek(0)
         file_content = bitstream.read()
-        name = md5.new(file_content).hexdigest()
+        name = md5(file_content).hexdigest()
         path = 'Pictures/%s.%s' % (name, EXTENSIONS[mimetype])
         if path not in self.zip.namelist():
             self.zip.writestr(path, file_content)
diff --git a/relatorio/tests/templates/include.tmpl b/relatorio/tests/templates/include.tmpl
new file mode 100644
index 0000000..cb46df8
--- /dev/null
+++ b/relatorio/tests/templates/include.tmpl
@@ -0,0 +1 @@
+{% include other.tmpl %}
diff --git a/relatorio/tests/test_api.py b/relatorio/tests/test_api.py
index 22f4336..990e0d6 100644
--- a/relatorio/tests/test_api.py
+++ b/relatorio/tests/test_api.py
@@ -39,14 +39,16 @@ class TestRepository(object):
         "Testing the registration"
         reporting = ReportRepository()
         reporting.add_report(StubObject, 'text/plain',
-                             os.path.join('templates', 'test.tmpl'))
+                             os.path.join('templates', 'test.tmpl'),
+                             description='Test report')
 
         assert_true(StubObject in reporting.classes)
         assert_true('default' in reporting.classes[StubObject].ids)
         assert_true('text/plain' in reporting.classes[StubObject].mimetypes)
 
-        report, mime = reporting.classes[StubObject].ids['default']
+        report, mime, desc = reporting.classes[StubObject].ids['default']
         eq_(mime, 'text/plain')
+        eq_(desc, 'Test report')
         eq_(report.mimetype, 'text/plain')
         assert_true(report.fpath.endswith(os.path.join('templates',
                                                        'test.tmpl')))
@@ -110,3 +112,11 @@ class TestReport(object):
             "Hi Foo,\nIt's One o'clock to 5 !\n")
         assert_raises(TypeError, report, a)
 
+class TestReportInclude(object):
+
+    def test_include(self):
+        our_dir = os.path.dirname(__file__)
+        template_path = os.path.join(our_dir, 'templates')
+        relative_report = Report(os.path.join(template_path, 'include.tmpl'),
+                                 'text/plain')
+        eq_(relative_report().render(), 'Another Hello.\n\n')
commit 942a062eba210fc11e2a8b3ccf7dbdb60efcc079
Author: Daniel Baumann <daniel at debian.org>
Date:   Fri Oct 2 07:57:34 2009 +0200

    Releasing debian version 0.5.1-5.

diff --git a/debian/changelog b/debian/changelog
index 2a5dd34..571071b 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,14 @@
+relatorio (0.5.1-5) unstable; urgency=low
+
+  [ Mathias Behrle ]
+  * Adding python-yaml and python-pycha to Suggests (Closes: #548634).
+  * Adding python-lxml to Depends.
+
+  [ Daniel Baumann ]
+  * Sorting suggests.
+
+ -- Daniel Baumann <daniel at debian.org>  Fri, 02 Oct 2009 07:57:24 +0200
+
 relatorio (0.5.1-4) unstable; urgency=low
 
   [ Mathias Behrle ]
commit d06b0559a014e185e3ffbd18ce819c3ff451430c
Author: Daniel Baumann <daniel at debian.org>
Date:   Mon Sep 28 12:42:44 2009 +0200

    Sorting suggests.

diff --git a/debian/control b/debian/control
index 46d01ff..6210b28 100644
--- a/debian/control
+++ b/debian/control
@@ -17,7 +17,7 @@ Package: python-relatorio
 Architecture: all
 Depends: ${misc:Depends}, ${python:Depends}, python-genshi, python-lxml, python-pkg-resources
 XB-Python-Version: ${python:Versions}
-Suggests: python-yaml, python-pycha
+Suggests: python-pycha, python-yaml
 Description: Python module to create reports from Python objects
  This is a Python module to create reports from Python objects. Output plugins
  to several formats are included, such as documents (odt, ods, pdf) or images
commit bde895f0739306918acd8e6319de04bc1761b234
Author: Mathias Behrle <mathiasb at mbsolutions.selfip.biz>
Date:   Mon Sep 28 12:32:52 2009 +0200

    Adding python-lxml to Depends.

diff --git a/debian/control b/debian/control
index eaf56fc..46d01ff 100644
--- a/debian/control
+++ b/debian/control
@@ -15,7 +15,7 @@ Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
 
 Package: python-relatorio
 Architecture: all
-Depends: ${misc:Depends}, ${python:Depends}, python-genshi, python-pkg-resources
+Depends: ${misc:Depends}, ${python:Depends}, python-genshi, python-lxml, python-pkg-resources
 XB-Python-Version: ${python:Versions}
 Suggests: python-yaml, python-pycha
 Description: Python module to create reports from Python objects
commit bb7929750ff2d4b35087b526695b3fc25dc8e4bd
Author: Mathias Behrle <mathiasb at mbsolutions.selfip.biz>
Date:   Mon Sep 28 12:29:22 2009 +0200

    Adding python-yaml and python-pycha to Suggests (Closes: #548634).

diff --git a/debian/control b/debian/control
index eb6aa62..eaf56fc 100644
--- a/debian/control
+++ b/debian/control
@@ -17,6 +17,7 @@ Package: python-relatorio
 Architecture: all
 Depends: ${misc:Depends}, ${python:Depends}, python-genshi, python-pkg-resources
 XB-Python-Version: ${python:Versions}
+Suggests: python-yaml, python-pycha
 Description: Python module to create reports from Python objects
  This is a Python module to create reports from Python objects. Output plugins
  to several formats are included, such as documents (odt, ods, pdf) or images
commit a2351f5aee62d9e35e84003bba82f9c3ccc82d5c
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat Sep 5 09:35:36 2009 +0200

    Releasing debian version 0.5.1-4.

diff --git a/debian/changelog b/debian/changelog
index b692193..2a5dd34 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,17 @@
+relatorio (0.5.1-4) unstable; urgency=low
+
+  [ Mathias Behrle ]
+  * Correcting spelling error in package long-description.
+
+  [ Daniel Baumann ]
+  * Updating to standards version 3.8.3.
+  * Adding maintainer homepage field to control.
+  * Adding README.source.
+  * Moving maintainer homepage field to copyright.
+  * Updating README.source.
+
+ -- Daniel Baumann <daniel at debian.org>  Sat, 05 Sep 2009 09:35:32 +0200
+
 relatorio (0.5.1-3) unstable; urgency=low
 
   * Updating maintainer field.
commit 9aafaa2ef020da31d0f75cdfa6f241b8ea6b2afe
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat Sep 5 09:31:18 2009 +0200

    Updating README.source.

diff --git a/debian/README.source b/debian/README.source
index 259f923..dcc7ba3 100644
--- a/debian/README.source
+++ b/debian/README.source
@@ -4,7 +4,7 @@ Package Repositories
 Backports for the current stable debian distribution as well as snapshots of
 unreleased versions may be available in repositories listed on the maintainers
 homepage. The current URL of the maintainer homepage can be seen in
-debian/control.
+debian/copyright.
 
 
 Source Access
commit 4cf1d1435470003984727f4b4f73adce5005b99e
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat Sep 5 08:50:43 2009 +0200

    Moving maintainer homepage field to copyright.

diff --git a/debian/control b/debian/control
index b204d53..eb6aa62 100644
--- a/debian/control
+++ b/debian/control
@@ -12,7 +12,6 @@ Standards-Version: 3.8.3
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
 Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
-XSBC-Maintainer-Homepage: http://tryton.debian-maintainers.org/
 
 Package: python-relatorio
 Architecture: all
diff --git a/debian/copyright b/debian/copyright
index 64f2cd3..264867c 100644
--- a/debian/copyright
+++ b/debian/copyright
@@ -1,5 +1,7 @@
-Authors: Nicolas Evrard <nicoe at openhex.org>
-Download: http://relatorio.openhex.org/
+Upstream-Contact: Relatorio project <relatorio at openhex.org>
+Upstream-Homepage: http://relatorio.openhex.org/
+Maintainer-Contact: Debian Tryton Maintainers <tryton at lists.debian-maintainers.org>
+Maintainer-Homepage: http://tryton.debian-maintainers.org/
 
 Files: *
 Copyright: (C) 2007-2009 OpenHex SPRL <http://www.openhex.com/>
commit b6f8729e5c9ba0fa996b925010aedbb0b80ecff0
Author: Daniel Baumann <daniel at debian.org>
Date:   Tue Aug 25 08:18:12 2009 +0200

    Adding README.source.

diff --git a/debian/README.source b/debian/README.source
new file mode 100644
index 0000000..259f923
--- /dev/null
+++ b/debian/README.source
@@ -0,0 +1,37 @@
+Package Repositories
+--------------------
+
+Backports for the current stable debian distribution as well as snapshots of
+unreleased versions may be available in repositories listed on the maintainers
+homepage. The current URL of the maintainer homepage can be seen in
+debian/control.
+
+
+Source Access
+-------------
+
+You can obtain the sources of this package with:
+
+  $ apt-get source ${PACKAGE}
+
+whereas '${PACKAGE}' has to be replaced with the actual name of the package.
+
+This package is maintained with the Git version control system. The current git
+source tree can be obtained with:
+
+  $ git clone ${GIT_URI}
+
+whereas '${GIT_URI}' has to be replaced with the actual URI for the Git
+repository. The current Git URI can be seen in debian/control in the extracted
+package sources.
+
+More information about Git can be found in the git-core package.
+
+This package may use the Quilt patch system to manage all modifications to the
+upstream source. Changes, if any, are stored in the source package as diffs in
+debian/diff and are applied during the build. Current modifications can be
+applied to the source tree with:
+
+  $ quilt push -a
+
+More information about Quilt can be found in the quilt package.
commit 7d3323a355370b771cbc1481fbd21f311b39fbb6
Author: Daniel Baumann <daniel at debian.org>
Date:   Mon Aug 24 17:49:45 2009 +0200

    Adding maintainer homepage field to control.

diff --git a/debian/control b/debian/control
index eb6aa62..b204d53 100644
--- a/debian/control
+++ b/debian/control
@@ -12,6 +12,7 @@ Standards-Version: 3.8.3
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
 Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
+XSBC-Maintainer-Homepage: http://tryton.debian-maintainers.org/
 
 Package: python-relatorio
 Architecture: all
commit c12b3de56172f76eddcb84c3f7b77d1ed5bcda54
Author: Daniel Baumann <daniel at debian.org>
Date:   Sun Aug 16 10:12:38 2009 +0200

    Updating to standards version 3.8.3.

diff --git a/debian/control b/debian/control
index a3bd76a..eb6aa62 100644
--- a/debian/control
+++ b/debian/control
@@ -8,7 +8,7 @@ Uploaders:
 Build-Depends:
  debhelper (>= 7), python, python-all-dev, python-genshi, python-setuptools,
  python-support
-Standards-Version: 3.8.2
+Standards-Version: 3.8.3
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
 Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
commit 81ec37ebb17d29603ca3130c4b7bf78c4177a9f8
Author: Mathias Behrle <mathiasb at mbsolutions.selfip.biz>
Date:   Tue Aug 11 22:04:20 2009 +0200

    Correcting spelling error in package long-description.

diff --git a/debian/control b/debian/control
index 4603844..a3bd76a 100644
--- a/debian/control
+++ b/debian/control
@@ -19,5 +19,5 @@ Depends: ${misc:Depends}, ${python:Depends}, python-genshi, python-pkg-resources
 XB-Python-Version: ${python:Versions}
 Description: Python module to create reports from Python objects
  This is a Python module to create reports from Python objects. Output plugins
- to several formats are included, such as document (odt, ods, pdf) or images
+ to several formats are included, such as documents (odt, ods, pdf) or images
  (png, svg).
commit bf7a5c4b87e70456562a7a6fe296a0fc2d6d66ea
Author: Daniel Baumann <daniel at debian.org>
Date:   Mon Aug 10 19:11:04 2009 +0200

    Releasing debian version 0.5.1-3.

diff --git a/debian/changelog b/debian/changelog
index 51bc6d3..b692193 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,12 @@
+relatorio (0.5.1-3) unstable; urgency=low
+
+  * Updating maintainer field.
+  * Updating vcs fields.
+  * Adding Mathias as co-maintainer.
+  * Wrapping lines in control.
+
+ -- Daniel Baumann <daniel at debian.org>  Mon, 10 Aug 2009 19:10:58 +0200
+
 relatorio (0.5.1-2) unstable; urgency=low
 
   * Using correct rfc-2822 date formats in changelog.
commit 4ce336f2b394d44ced830d52a7f0d933b0617d3e
Author: Daniel Baumann <daniel at debian.org>
Date:   Mon Aug 10 19:10:37 2009 +0200

    Wrapping lines in control.

diff --git a/debian/control b/debian/control
index c3a4f91..4603844 100644
--- a/debian/control
+++ b/debian/control
@@ -2,8 +2,12 @@ Source: relatorio
 Section: python
 Priority: optional
 Maintainer: Debian Tryton Maintainers <tryton at lists.debian-maintainers.org>
-Uploaders: Daniel Baumann <daniel at debian.org>, Mathias Behrle <mathiasb at mbsolutions.selfip.biz>
-Build-Depends: debhelper (>= 7), python, python-all-dev, python-genshi, python-setuptools, python-support
+Uploaders:
+ Daniel Baumann <daniel at debian.org>,
+ Mathias Behrle <mathiasb at mbsolutions.selfip.biz>
+Build-Depends:
+ debhelper (>= 7), python, python-all-dev, python-genshi, python-setuptools,
+ python-support
 Standards-Version: 3.8.2
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
commit bf5477b7cff11dd98676c48c473ac3752d3b3cd5
Author: Daniel Baumann <daniel at debian.org>
Date:   Mon Aug 10 12:34:59 2009 +0200

    Adding Mathias as co-maintainer.

diff --git a/debian/control b/debian/control
index 85b4e88..c3a4f91 100644
--- a/debian/control
+++ b/debian/control
@@ -2,7 +2,7 @@ Source: relatorio
 Section: python
 Priority: optional
 Maintainer: Debian Tryton Maintainers <tryton at lists.debian-maintainers.org>
-Uploaders: Daniel Baumann <daniel at debian.org>
+Uploaders: Daniel Baumann <daniel at debian.org>, Mathias Behrle <mathiasb at mbsolutions.selfip.biz>
 Build-Depends: debhelper (>= 7), python, python-all-dev, python-genshi, python-setuptools, python-support
 Standards-Version: 3.8.2
 Homepage: http://relatorio.openhex.org/
commit d161b6d676719f6d0b228fdf92a6fa9a8a0325e7
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat Aug 8 23:26:50 2009 +0200

    Updating vcs fields.

diff --git a/debian/control b/debian/control
index e525d79..85b4e88 100644
--- a/debian/control
+++ b/debian/control
@@ -6,8 +6,8 @@ Uploaders: Daniel Baumann <daniel at debian.org>
 Build-Depends: debhelper (>= 7), python, python-all-dev, python-genshi, python-setuptools, python-support
 Standards-Version: 3.8.2
 Homepage: http://relatorio.openhex.org/
-Vcs-Browser: http://git.debian.net/?p=debian/relatorio.git
-Vcs-Git: git://git.debian.net/git/debian/relatorio.git
+Vcs-Browser: http://git.debian-maintainers.org/?p=tryton/relatorio.git
+Vcs-Git: git://git.debian-maintainers.org/git/tryton/relatorio.git
 
 Package: python-relatorio
 Architecture: all
commit 11205ffc0758f40ca927e4294df999c7e8603d95
Author: Daniel Baumann <daniel at debian.org>
Date:   Sat Aug 8 23:19:30 2009 +0200

    Updating maintainer field.

diff --git a/debian/control b/debian/control
index 2fd23ff..e525d79 100644
--- a/debian/control
+++ b/debian/control
@@ -1,7 +1,8 @@
 Source: relatorio
 Section: python
 Priority: optional
-Maintainer: Daniel Baumann <daniel at debian.org>
+Maintainer: Debian Tryton Maintainers <tryton at lists.debian-maintainers.org>
+Uploaders: Daniel Baumann <daniel at debian.org>
 Build-Depends: debhelper (>= 7), python, python-all-dev, python-genshi, python-setuptools, python-support
 Standards-Version: 3.8.2
 Homepage: http://relatorio.openhex.org/
commit 96ee019b2ed0cc61d17d5fdacbc1c843cf294675
Author: Daniel Baumann <daniel at debian.org>
Date:   Mon Jul 27 14:55:51 2009 +0200

    Releasing debian version 0.5.1-2.

diff --git a/debian/changelog b/debian/changelog
index 464b54d..51bc6d3 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,11 @@
+relatorio (0.5.1-2) unstable; urgency=low
+
+  * Using correct rfc-2822 date formats in changelog.
+  * Updating package to standards version 3.8.2.
+  * Minimizing rules file.
+
+ -- Daniel Baumann <daniel at debian.org>  Mon, 27 Jul 2009 14:55:48 +0200
+
 relatorio (0.5.1-1) unstable; urgency=low
 
   * Merging upstream version 0.5.1.
commit cd56901cb9267f447c6ae3dbac4b660367210089
Author: Daniel Baumann <daniel at debian.org>
Date:   Mon Jul 27 14:54:43 2009 +0200

    Minimizing rules file.

diff --git a/debian/rules b/debian/rules
index 59495ef..000210b 100755
--- a/debian/rules
+++ b/debian/rules
@@ -1,43 +1,4 @@
 #!/usr/bin/make -f
 
-clean:
-	dh_testdir
-	dh_testroot
-	rm -f build-stamp
-
-	python setup.py clean
-	rm -rf dist build
-	find . -type f -name "*.pyc" | xargs rm -f
-
-	dh_clean
-
-build:
-
-install:
-	dh_testdir
-	dh_testroot
-	dh_prep
-
-	python setup.py install --single-version-externally-managed --root=$(CURDIR)/debian/python-relatorio --install-lib /usr/share/python-support/python-relatorio
-
-	find debian/python-relatorio -type f -name "*.pyc" | xargs rm -f
-
-binary: binary-indep
-
-binary-arch:
-
-binary-indep: install
-	dh_testdir
-	dh_testroot
-	dh_installchangelogs CHANGES
-	dh_installdocs
-	dh_installexamples
-	dh_pysupport
-	dh_compress
-	dh_fixperms
-	dh_installdeb
-	dh_gencontrol
-	dh_md5sums
-	dh_builddeb
-
-.PHONY: clean build install binary binary-arch binary-indep
+%:
+	dh ${@}
commit 9f4b6ff1cce45ebff2db9af1726bf31f1e0e2d0c
Author: Daniel Baumann <daniel at debian.org>
Date:   Mon Jul 27 14:54:38 2009 +0200

    Updating package to standards version 3.8.2.

diff --git a/debian/control b/debian/control
index ccbb927..2fd23ff 100644
--- a/debian/control
+++ b/debian/control
@@ -3,7 +3,7 @@ Section: python
 Priority: optional
 Maintainer: Daniel Baumann <daniel at debian.org>
 Build-Depends: debhelper (>= 7), python, python-all-dev, python-genshi, python-setuptools, python-support
-Standards-Version: 3.8.1
+Standards-Version: 3.8.2
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian.net/?p=debian/relatorio.git
 Vcs-Git: git://git.debian.net/git/debian/relatorio.git
commit 18618e3f57c7d59d2a1c9660ad2769ca9d188d18
Author: Daniel Baumann <daniel at debian.org>
Date:   Mon May 4 11:47:16 2009 +0200

    Using correct rfc-2822 date formats in changelog.

diff --git a/debian/changelog b/debian/changelog
index 8996220..464b54d 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -17,4 +17,4 @@ relatorio (0.5.0-1) unstable; urgency=low
 
   * Initial release (Closes: #507460).
 
- -- Daniel Baumann <daniel at debian.org>  Wed,  4 Feb 2009 18:31:00 +0100
+ -- Daniel Baumann <daniel at debian.org>  Wed, 04 Feb 2009 18:31:00 +0100
commit 6b41558b42bcc127f0f3e6ac9f326badb5115c32
Author: Daniel Baumann <daniel at debian.org>
Date:   Fri Apr 17 21:39:12 2009 +0200

    Releasing debian version 0.5.1-1.

diff --git a/debian/changelog b/debian/changelog
index 1ea38e8..8996220 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,10 @@
+relatorio (0.5.1-1) unstable; urgency=low
+
+  * Merging upstream version 0.5.1.
+  * Tidy rules file.
+
+ -- Daniel Baumann <daniel at debian.org>  Fri, 17 Apr 2009 21:39:00 +0200
+
 relatorio (0.5.0-2) unstable; urgency=low
 
   * Correcting typo in name of the upstream author in copyright file
commit 249c6473911c6b9428ca9b54735cec9645239e93
Author: Daniel Baumann <daniel at debian.org>
Date:   Fri Apr 17 21:38:44 2009 +0200

    Tidy rules file.

diff --git a/debian/rules b/debian/rules
index c2527f3..59495ef 100755
--- a/debian/rules
+++ b/debian/rules
@@ -17,7 +17,6 @@ install:
 	dh_testdir
 	dh_testroot
 	dh_prep
-	dh_installdirs
 
 	python setup.py install --single-version-externally-managed --root=$(CURDIR)/debian/python-relatorio --install-lib /usr/share/python-support/python-relatorio
 
commit f4b719fef01e85096f231e6290abd53fff7da4cc
Author: Daniel Baumann <daniel at debian.org>
Date:   Fri Apr 17 21:37:03 2009 +0200

    Merging upstream version 0.5.1.

diff --git a/CHANGES b/CHANGES
index c4683a8..e0b42f9 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,11 @@
+0.5.1 - 20090416
+ * Simplified the examples
+ * Fix usage of tags without attributes (choose & otherwise)
+ * Print original traceback when a module can not be loaded
+ * Do not import relatorio in setup.py
+ * Better handling of namespaces
+ * Added some tests
+
 0.5.0 - 20090123
  * Added Text and XML Template to the TemplateLoader
  * Splitted mimetypes and ids in the ReportRepository
diff --git a/README b/README
index b5e6f6a..73c54f8 100644
--- a/README
+++ b/README
@@ -1,19 +1,20 @@
-relatorio
+Relatorio
 =========
 
-A templating library which provides a way to easily output all kind of
-different files (odt, ods, png, svg, ...). Adding support for more filetype is
-easy: you just have to create a plugin for this.
+Relatorio is a templating library which provides a way to easily output several
+kinds of files (odt, ods, png, svg, ...). Support for more filetypes can
+be easily added by creating plugins for them.
 
-relatorio also provides a report repository allowing you to link python objects
+Relatorio also provides a report repository allowing you to link python objects
 and report together, find reports by mimetype/name/python object.
 
 Note on PyCha
 =============
 
-Since the last release, pycha upstream author included most of my patches. So
-there is no more need to use my friendly fork of the project. Although you can
-use this version for the SVG support you should use the 'trunk' version.
+Since the 0.4.0 release, pycha upstream author included most of our patches. So
+it is not necessary anymore to use our friendly fork of the project.
+
+For SVG support, you need PyCha 0.4.2 or later.
 
     http://www.lorenzogil.com/projects/pycha/
 
diff --git a/relatorio/__init__.py b/relatorio/__init__.py
index 6b4d39a..8812033 100644
--- a/relatorio/__init__.py
+++ b/relatorio/__init__.py
@@ -12,4 +12,4 @@ and report together, find reports by mimetypes/name/python objects.
 from relatorio.reporting import MIMETemplateLoader, ReportRepository, Report
 import templates
 
-__version__ = 'development'
+__version__ = '0.5.1'
diff --git a/relatorio/templates/__init__.py b/relatorio/templates/__init__.py
index 5b61bdf..21e20f2 100644
--- a/relatorio/templates/__init__.py
+++ b/relatorio/templates/__init__.py
@@ -10,7 +10,7 @@
 #
 # This program 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 
+# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 # details.
 #
 # You should have received a copy of the GNU General Public License along with
@@ -18,6 +18,7 @@
 #
 ###############################################################################
 
+import traceback
 import warnings
 
 plugins = ['base', 'opendocument', 'pdf', 'chart']
@@ -25,6 +26,10 @@ plugins = ['base', 'opendocument', 'pdf', 'chart']
 for name in plugins:
     try:
         __import__('relatorio.templates.%s' % name)
-    except:
+    except Exception, e:
         warnings.warn("Unable to load plugin '%s', you will not be able "
                       "to use it" % name)
+        print 'Original traceback'
+        print '-' * 80
+        print
+        traceback.print_exc()
diff --git a/relatorio/templates/opendocument.py b/relatorio/templates/opendocument.py
index 1519ea2..e2b7a58 100644
--- a/relatorio/templates/opendocument.py
+++ b/relatorio/templates/opendocument.py
@@ -66,9 +66,29 @@ EXTENSIONS = {'image/png': 'png',
              }
 
 RELATORIO_URI = 'http://relatorio.openhex.org/'
+GENSHI_URI = 'http://genshi.edgewall.org/'
 output_encode = genshi.output.encode
 EtreeElement = lxml.etree.Element
 
+# A note regarding OpenDocument namespaces:
+#
+# The current code assumes the original OpenOffice document uses default
+# namespace prefix ("table", "xlink", "draw", ...). We derive the actual
+# namespaces URIs from their prefix, instead of the other way round. This has
+# the advantage that if a new version of the format use different namespaces
+# (this is not the case for ODF 1.1 but could be the case in the future since
+# there is a version number in those namespaces after all), Relatorio will
+# support those new formats out of the box.
+
+
+# A note about attribute namespaces:
+#
+# Ideally, we should update the namespace map of all the nodes we add
+# (Genshi) attributes to, so that the attributes use a nice "py" prefix instead
+# of a generated one (eg. "ns0", which is correct but ugly) in the case no
+# parent node defines it. Unfortunately, lxml doesn't support this:
+# the nsmap attribute of Element objects is (currently) readonly.
+
 def guess_type(val):
     if isinstance(val, (str, unicode)):
         return 'string'
@@ -126,6 +146,13 @@ def wrap_nodes_between(first, last, new_parent):
     removed in the process.
     """
     old_parent = first.getparent()
+
+    # Any text after the opening tag (and not within a tag) need to be handled
+    # explicitly. For example in <if>xxx<span>yyy</span>zzz</if>, zzz is
+    # copied along the span tag, but not xxx, which corresponds to the tail
+    # attribute of the opening tag.
+    if first.tail:
+        new_parent.text = first.tail
     for node in first.itersiblings():
         if node is last:
             break
@@ -187,8 +214,23 @@ class Template(MarkupTemplate):
         """
         tree = lxml.etree.parse(StringIO(content))
         root = tree.getroot()
-        self.namespaces = root.nsmap.copy()
-        self.namespaces['py'] = 'http://genshi.edgewall.org/'
+
+        # assign default/fake namespaces so that documents do not need to
+        # define them if they don't use them
+        self.namespaces = {
+            "text": "urn:text",
+            "draw": "urn:draw",
+            "table": "urn:table",
+            "office": "urn:office",
+            "xlink": "urn:xlink"
+        }
+        # but override them with the real namespaces
+        self.namespaces.update(root.nsmap)
+
+        # remove any "root" namespace as lxml.xpath do not support them
+        self.namespaces.pop(None, None)
+
+        self.namespaces['py'] = GENSHI_URI
         self.namespaces['relatorio'] = RELATORIO_URI
 
         self._invert_style(tree)
@@ -279,9 +321,8 @@ class Template(MarkupTemplate):
         office_name = '{%s}value' % self.namespaces['office']
         office_valuetype = '{%s}value-type' % self.namespaces['office']
 
-        py_namespace = self.namespaces['py']
-        py_attrs_attr = '{%s}attrs' % py_namespace
-        py_replace = '{%s}replace' % py_namespace
+        py_attrs_attr = '{%s}attrs' % GENSHI_URI
+        py_replace = '{%s}replace' % GENSHI_URI
 
         r_statements, closing_tags = self._relatorio_statements(tree)
 
@@ -329,10 +370,10 @@ class Template(MarkupTemplate):
                     attribs = {attr: a_val}
                 else:
                     attribs = {}
-                genshi_node = EtreeElement('{%s}%s' % (py_namespace,
+                genshi_node = EtreeElement('{%s}%s' % (GENSHI_URI,
                                                        directive),
                                            attrib=attribs,
-                                           nsmap=self.namespaces)
+                                           nsmap={'py': GENSHI_URI})
 
                 # - we move all the nodes between the opening and closing
                 #   statements to this new node (append also removes from old
@@ -366,10 +407,8 @@ class Template(MarkupTemplate):
         table_col_tag = '{%s}table-column' % table_namespace
         table_num_col_attr = '{%s}number-columns-repeated' % table_namespace
 
-        py_namespace = self.namespaces['py']
-        py_attrs_attr = '{%s}attrs' % py_namespace
-
-        repeat_tag = '{%s}repeat' % self.namespaces['relatorio']
+        py_attrs_attr = '{%s}attrs' % GENSHI_URI
+        repeat_tag = '{%s}repeat' % RELATORIO_URI
 
         # table node (it is not necessarily the direct parent of ancestor)
         table_node = ancestor.iterancestors('{%s}table' % table_namespace) \
@@ -399,9 +438,9 @@ class Template(MarkupTemplate):
         #    last child of the row
         attr_value = "__relatorio_store_col_count(%d, %r)" \
                      % (loop_id, table_name)
-        replace_node = EtreeElement('{%s}replace' % py_namespace,
+        replace_node = EtreeElement('{%s}replace' % GENSHI_URI,
                                     attrib={'value': attr_value},
-                                    nsmap=self.namespaces)
+                                    nsmap={'py': GENSHI_URI})
         ancestor.append(replace_node)
 
         # find the position in the row of the cells holding the
@@ -471,7 +510,7 @@ class Template(MarkupTemplate):
                "table": table_name
             }
             repeat_node = EtreeElement(repeat_tag, attrib=attribs,
-                                       nsmap=self.namespaces)
+                                       nsmap={'relatorio': RELATORIO_URI})
             wrap_nodes_between(first, last, repeat_node)
         return a_val
 
@@ -482,16 +521,14 @@ class Template(MarkupTemplate):
         original iterable as to not exhaust generators."""
 
         _, directive, attr, a_val = statement
-        table_rowspan_attr = '{%s}number-rows-spanned' \
-                             % self.namespaces['table']
+        table_namespace = self.namespaces['table']
+        table_rowspan_attr = '{%s}number-rows-spanned' % table_namespace
 
         # checks wether there is a (meaningful) rowspan
         rows_spanned = int(outer_o_node.attrib.get(table_rowspan_attr, 1))
         if rows_spanned == 1:
             return a_val
 
-        py_namespace = self.namespaces['py']
-        table_namespace = self.namespaces['table']
         table_row_tag = '{%s}table-row' % table_namespace
         table_cov_cell_tag = '{%s}covered-table-cell' % table_namespace
 
@@ -502,9 +539,9 @@ class Template(MarkupTemplate):
         # a_val == "target in iterable"
         target, iterable = a_val.split(' in ', 1)
         vars = "%s = list(%s)" % (temp_var, iterable.strip())
-        with_node = EtreeElement('{%s}with' % py_namespace,
+        with_node = EtreeElement('{%s}with' % GENSHI_URI,
                                  attrib={"vars": vars},
-                                 nsmap=self.namespaces)
+                                 nsmap={'py': GENSHI_URI})
 
         # 2) transform a_val to use that temporary variable
         a_val = "%s in %s" % (target, temp_var)
@@ -527,10 +564,10 @@ class Template(MarkupTemplate):
             assert first.tag == table_cov_cell_tag
             assert last.tag == table_cov_cell_tag
             # wrap them
-            tag = '{%s}%s' % (py_namespace, directive)
+            tag = '{%s}%s' % (GENSHI_URI, directive)
             for_node = EtreeElement(tag,
                                     attrib={attr: a_val},
-                                    nsmap=self.namespaces)
+                                    nsmap={'py': GENSHI_URI})
             wrap_nodes_between(first, last, for_node)
 
         # 4) wrap all the corresponding rows indide the "with"
@@ -541,8 +578,9 @@ class Template(MarkupTemplate):
 
     def _handle_images(self, tree):
         "replaces all draw:frame named 'image: ...' by draw:image nodes"
-        draw_name = '{%s}name' % self.namespaces['draw']
-        draw_image = '{%s}image' % self.namespaces['draw']
+        draw_namespace = self.namespaces['draw']
+        draw_name = '{%s}name' % draw_namespace
+        draw_image = '{%s}image' % draw_namespace
         py_attrs = '{%s}attrs' % self.namespaces['py']
         xpath_expr = "//draw:frame[starts-with(@draw:name, 'image:')]"
         for draw in tree.xpath(xpath_expr, namespaces=self.namespaces):
@@ -550,7 +588,8 @@ class Template(MarkupTemplate):
             attr_expr = "__relatorio_make_href(%s)" % d_name[7:]
             image_node = EtreeElement(draw_image,
                                       attrib={py_attrs: attr_expr},
-                                      nsmap=self.namespaces)
+                                      nsmap={'draw': draw_namespace,
+                                             'py': GENSHI_URI})
             draw.replace(draw[0], image_node)
 
     def _handle_innerdocs(self, tree):
@@ -574,6 +613,9 @@ class Template(MarkupTemplate):
 
         stream = super(Template, self).generate(*args, **kwargs)
         if self.has_col_loop:
+            # Note that we can't simply add a "number-columns-repeated"
+            # attribute and then fill it with the correct number of columns
+            # because that wouldn't work if more than one column is repeated.
             transformation = DuplicateColumnHeaders(counter)
             col_filter = Transformer('//repeat[namespace-uri()="%s"]'
                                      % RELATORIO_URI)
diff --git a/relatorio/tests/test_odt.py b/relatorio/tests/test_odt.py
index 5351d2a..853f966 100644
--- a/relatorio/tests/test_odt.py
+++ b/relatorio/tests/test_odt.py
@@ -31,7 +31,10 @@ from genshi.filters import Translator
 from genshi.core import PI
 from genshi.template.eval import UndefinedError
 
-from templates.opendocument import Template, GENSHI_EXPR
+from templates.opendocument import Template, GENSHI_EXPR, GENSHI_URI, \
+                                   RELATORIO_URI
+
+OO_TABLE_NS = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"
 
 def pseudo_gettext(string):
     catalog = {'Mes collègues sont:': 'My colleagues are:',
@@ -75,15 +78,154 @@ class TestOOTemplating(object):
 
     def test_directives(self):
         "Testing the directives interpolation"
-        xml = '''<b:a xmlns:b="urn:b" xmlns:text="%s" xmlns:draw="urn:draw"
-        xmlns:table="urn:table" xmlns:office="urn:office"
-        xmlns:xlink="urn:xlink">
-        <text:a xlink:href="relatorio://foo">foo</text:a>
-        </b:a>''' % 'urn:text'
+        xml = '''<xml xmlns:text="urn:text" xmlns:xlink="urn:xlink">
+                    <text:a xlink:href="relatorio://foo">foo</text:a>
+                 </xml>'''
+        interpolated = self.oot.insert_directives(xml)
+        root_interpolated = lxml.etree.parse(interpolated).getroot()
+        child = root_interpolated[0]
+        eq_(child.get('{http://genshi.edgewall.org/}replace'), 'foo')
+
+    def test_column_looping(self):
+        xml = '''
+<table:table
+    xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
+    xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+    xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
+    xmlns:xlink="http://www.w3.org/1999/xlink"
+    table:name="Tableau1"
+    table:style-name="Tableau1">
+    <table:table-column table:style-name="Tableau1.A"
+                        table:number-columns-repeated="2"/>
+    <table:table-column table:style-name="Tableau1.C"/>
+    <table:table-column table:style-name="Tableau1.A"/>
+    <table:table-column table:style-name="Tableau1.E"/>
+    <table:table-header-rows>
+        <table:table-row table:style-name="Tableau1.1">
+            <table:table-cell table:style-name="Tableau1.A1"
+                              office:value-type="string">
+                <text:p text:style-name="Table_20_Heading">Brol</text:p>
+            </table:table-cell>
+            <table:table-cell table:style-name="Tableau1.A1"
+                              office:value-type="string">
+                <text:p text:style-name="Table_20_Heading">
+                    <text:a xlink:type="simple"
+                            xlink:href="relatorio://for each="title in titles"">for each="title in titles"</text:a>
+                </text:p>
+            </table:table-cell>
+            <table:table-cell table:style-name="Tableau1.A1"
+                              office:value-type="string">
+                <text:p text:style-name="Table_20_Heading">${title}</text:p>
+                <text:p text:style-name="Table_20_Heading"/>
+            </table:table-cell>
+            <table:table-cell table:style-name="Tableau1.A1"
+                              office:value-type="string">
+                <text:p text:style-name="Table_20_Heading">
+                    <text:a xlink:type="simple"
+                            xlink:href="relatorio:///for">/for</text:a>
+                </text:p>
+            </table:table-cell>
+            <table:table-cell table:style-name="Tableau1.E1"
+                              office:value-type="string">
+                <text:p text:style-name="Table_20_Heading">Truc</text:p>
+            </table:table-cell>
+        </table:table-row>
+    </table:table-header-rows>
+    <table:table-row>
+        <table:table-cell table:style-name="Tableau1.A2"
+                          table:number-columns-spanned="5"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">
+                <text:a xlink:type="simple"
+                        xlink:href="relatorio://for%20each=%22items%20in%20lst%22">for each="items in lst"</text:a>
+            </text:p>
+        </table:table-cell>
+        <table:covered-table-cell/>
+        <table:covered-table-cell/>
+        <table:covered-table-cell/>
+        <table:covered-table-cell/>
+    </table:table-row>
+    <table:table-row>
+        <table:table-cell table:style-name="Tableau1.A3"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">Brol</text:p>
+        </table:table-cell>
+        <table:table-cell table:style-name="Tableau1.A3"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">
+                <text:a xlink:type="simple"
+                        xlink:href="relatorio://for%20each=%22item%20in%20items%22">for each="item in items"</text:a>
+            </text:p>
+        </table:table-cell>
+        <table:table-cell table:style-name="Tableau1.A3"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">${item}</text:p>
+            <text:p text:style-name="Table_20_Contents"/>
+        </table:table-cell>
+        <table:table-cell table:style-name="Tableau1.A3"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">
+                <text:a xlink:type="simple"
+                        xlink:href="relatorio:///for">/for</text:a>
+            </text:p>
+        </table:table-cell>
+        <table:table-cell table:style-name="Tableau1.A2"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">Truc</text:p>
+        </table:table-cell>
+    </table:table-row>
+    <table:table-row>
+        <table:table-cell table:style-name="Tableau1.A2"
+                          table:number-columns-spanned="5"
+                          office:value-type="string">
+            <text:p text:style-name="Table_20_Contents">
+                <text:a xlink:type="simple"
+                        xlink:href="relatorio:///for">/for</text:a>
+            </text:p>
+        </table:table-cell>
+        <table:covered-table-cell/>
+        <table:covered-table-cell/>
+        <table:covered-table-cell/>
+        <table:covered-table-cell/>
+    </table:table-row>
+</table:table>'''
+        interpolated = self.oot.insert_directives(xml)
+        root = lxml.etree.parse(interpolated).getroot()
+        child2 = root[1]
+        eq_(child2.tag, "{%s}repeat" % RELATORIO_URI)
+        eq_(child2.get("closing"), "3")
+        eq_(child2.get("opening"), "1")
+        eq_(len(child2), 1)
+        child4 = root[3]
+        eq_(child4.tag, "{%s}table-header-rows" % OO_TABLE_NS)
+        row1 = child4[0]
+        ok_(row1.get("{%s}attrs" % GENSHI_URI)
+                .startswith('__relatorio_reset_col_count'))
+        eq_(len(row1), 4)
+        loop = row1[1]
+        eq_(loop.tag, "{%s}for" % GENSHI_URI)
+        cell = loop[0]
+        ok_(cell.get("{%s}attrs" % GENSHI_URI)
+                .startswith('__relatorio_inc_col_count'))
+        last_row_node = row1[3]
+        eq_(last_row_node.tag, "{%s}replace" % GENSHI_URI)
+        ok_(last_row_node.get("value")
+                         .startswith('__relatorio_store_col_count'))
+
+    def test_text_outside_p(self):
+        "Testing that the tail text of a directive node is handled properly"
+        xml = '''<xml xmlns:text="urn:text" xmlns:xlink="urn:xlink">
+                    <text:a xlink:href="relatorio://if%20test=%22True%22">if test="True"</text:a>
+                    xxx
+                    <text:p text:style-name="other">yyy</text:p>
+                    zzz
+                    <text:a xlink:href="relatorio:///if">/if</text:a>
+                 </xml>'''
         interpolated = self.oot.insert_directives(xml)
         root_interpolated = lxml.etree.parse(interpolated).getroot()
-        root_attrs = root_interpolated[0].attrib
-        eq_(root_attrs['{http://genshi.edgewall.org/}replace'], 'foo')
+        child = root_interpolated[0]
+        eq_(child.tag, '{http://genshi.edgewall.org/}if')
+        eq_(child.text.strip(), 'xxx')
 
     def test_styles(self):
         "Testing that styles get rendered"
@@ -127,17 +269,17 @@ class TestOOTemplating(object):
         root = tree.getroot()
         images = root.xpath('//draw:frame', namespaces=self.oot.namespaces)
         eq_(len(images), 3)
-        eq_(images[0].attrib['{%s}name' % self.oot.namespaces['draw']],
+        eq_(images[0].get('{%s}name' % self.oot.namespaces['draw']),
             "image: (oeuf, 'image/png')")
-        eq_(images[1].attrib['{%s}name' % self.oot.namespaces['draw']],
+        eq_(images[1].get('{%s}name' % self.oot.namespaces['draw']),
             'image: img')
-        eq_(images[1].attrib['{%s}width' % self.oot.namespaces['svg']],
+        eq_(images[1].get('{%s}width' % self.oot.namespaces['svg']),
             '1.732cm')
-        eq_(images[1].attrib['{%s}height' % self.oot.namespaces['svg']],
+        eq_(images[1].get('{%s}height' % self.oot.namespaces['svg']),
             '1.513cm')
-        eq_(images[2].attrib['{%s}width' % self.oot.namespaces['svg']],
+        eq_(images[2].get('{%s}width' % self.oot.namespaces['svg']),
             '1.732cm')
-        eq_(images[2].attrib['{%s}height' % self.oot.namespaces['svg']],
+        eq_(images[2].get('{%s}height' % self.oot.namespaces['svg']),
             '1.513cm')
 
     def test_regexp(self):
diff --git a/setup.py b/setup.py
index 9252123..ccb93e2 100644
--- a/setup.py
+++ b/setup.py
@@ -1,16 +1,32 @@
 # -*- encoding: utf-8 -*-
-import relatorio
+import os
+import re
 from setuptools import setup, find_packages
 
+def get_version():
+    init = open(os.path.join(os.path.dirname(__file__), 'relatorio',
+                             '__init__.py')).read()
+    return re.search(r"""__version__ = '([0-9.]*)'""", init).group(1)
+
 setup(
     name="relatorio",
     url="http://relatorio.openhex.org",
     author="Nicolas Evrard",
     author_email="nicoe at openhex.org",
     description="A templating library able to output odt and pdf files",
-    long_description=relatorio.__doc__,
+    long_description="""
+relatorio
+=========
+
+A templating library which provides a way to easily output all kind of
+different files (odt, ods, png, svg, ...). Adding support for more filetype is
+easy: you just have to create a plugin for this.
+
+relatorio also provides a report repository allowing you to link python objects
+and report together, find reports by mimetypes/name/python objects.
+    """,
     license="GPL License",
-    version=relatorio.__version__,
+    version=get_version(),
     packages=find_packages(exclude=['relatorio.tests', 'examples']),
     install_requires=[
         "Genshi >= 0.5",
commit dc26abacd64d35536d101c19839928e299378f93
Author: Daniel Baumann <daniel at debian.org>
Date:   Thu Mar 19 06:56:55 2009 +0100

    Releasing debian version 0.5.0-2.

diff --git a/debian/changelog b/debian/changelog
index 6214050..1ea38e8 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,11 @@
+relatorio (0.5.0-2) unstable; urgency=low
+
+  * Correcting typo in name of the upstream author in copyright file
+    (Closes: #518922).
+  * Upgrading to standards version to 3.8.1.
+
+ -- Daniel Baumann <daniel at debian.org>  Thu, 19 Mar 2009 06:56:00 +0100
+
 relatorio (0.5.0-1) unstable; urgency=low
 
   * Initial release (Closes: #507460).
commit aa9b949557c9575a0603ec04913f82eddb62d187
Author: Daniel Baumann <daniel at debian.org>
Date:   Thu Mar 19 06:56:21 2009 +0100

    Upgrading to standards version to 3.8.1.

diff --git a/debian/control b/debian/control
index 28f45df..ccbb927 100644
--- a/debian/control
+++ b/debian/control
@@ -3,7 +3,7 @@ Section: python
 Priority: optional
 Maintainer: Daniel Baumann <daniel at debian.org>
 Build-Depends: debhelper (>= 7), python, python-all-dev, python-genshi, python-setuptools, python-support
-Standards-Version: 3.8.0
+Standards-Version: 3.8.1
 Homepage: http://relatorio.openhex.org/
 Vcs-Browser: http://git.debian.net/?p=debian/relatorio.git
 Vcs-Git: git://git.debian.net/git/debian/relatorio.git
commit 229f785bef06aeebade9c6142985fcbd50b37f85
Author: Daniel Baumann <daniel at debian.org>
Date:   Thu Mar 19 06:55:46 2009 +0100

    Correcting typo in name of the upstream author in copyright file (Closes: #518922).

diff --git a/debian/copyright b/debian/copyright
index 1ac12d4..64f2cd3 100644
--- a/debian/copyright
+++ b/debian/copyright
@@ -1,4 +1,4 @@
-Authors: Nicolas Ivrard <nicoe at openhex.org>
+Authors: Nicolas Evrard <nicoe at openhex.org>
 Download: http://relatorio.openhex.org/
 
 Files: *
commit 687c7015bcd3737e1492e88f2c7dc93c0a8aaec0
Author: Daniel Baumann <daniel at debian.org>
Date:   Sun Mar 8 11:06:01 2009 +0100

    Adding debian version 0.5.0-1.

diff --git a/AUTHORS b/AUTHORS
new file mode 100644
index 0000000..160f9b9
--- /dev/null
+++ b/AUTHORS
@@ -0,0 +1,7 @@
+relatorio is the work of:
+    Nicolas Évrard <nicoe at openhex.org>
+    Gaëtan de Menten <gdementen at openhex.org>
+
+We included ideas and patches from:
+    Cédric Krier <cedric.krier at b2ck.com>
+    Udo Spallek <udono at virtual-things.biz>
diff --git a/CHANGES b/CHANGES
new file mode 100644
index 0000000..c4683a8
--- /dev/null
+++ b/CHANGES
@@ -0,0 +1,39 @@
+0.5.0 - 20090123
+ * Added Text and XML Template to the TemplateLoader
+ * Splitted mimetypes and ids in the ReportRepository
+ * RelatorioStream now has a __str__ method
+ * OOTemplate: ChartTemplate can be included
+ * OOTemplate: Correctly handle content type in the table cells
+ * OOTemplate: Better closing/opening tag detection algorithm
+ * OOTemplate: Looping on columns now work in OOTemplates
+ * OOTemplate: Using compression
+
+0.4.1 - 20081110
+ * Support for upstream PyCha since the most annoying bug has been fixed
+ * Removed the entrypoint stuff that was confusing lot of users
+
+0.4.0 - 20080910
+ * Generation of png/svg files through PyCha
+ * Code cleaning
+ * Signature of report __call__ method mimics the one of genshi templates
+ * Added the possibility to call chart report from odf ones
+
+0.3.0 - 20080806
+ * Generation of pdf files through ConTeXt
+ * Better support of cell value in opendocument table cells
+ * Better namespace support in opendocument files
+ * Better image support in opendocument files
+
+0.2.0 - 20080717
+ * Added support for templating in the styles.xml file
+ * Much more genshi-esque way to do stuff in the odt templating
+
+0.1.1 - 20080715
+ * Added an image handling feature (thanks to b2ck.com for the idea and bits of
+   implementation)
+ * Added the dependancy on Genshi
+ * test for trml2pdf presence
+ * standardize the way the template object returns their results
+
+0.1.0 - 20080707
+Initial version
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..e37680c
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,280 @@
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
diff --git a/README b/README
new file mode 100644
index 0000000..b5e6f6a
--- /dev/null
+++ b/README
@@ -0,0 +1,19 @@
+relatorio
+=========
+
+A templating library which provides a way to easily output all kind of
+different files (odt, ods, png, svg, ...). Adding support for more filetype is
+easy: you just have to create a plugin for this.
+
+relatorio also provides a report repository allowing you to link python objects
+and report together, find reports by mimetype/name/python object.
+
+Note on PyCha
+=============
+
+Since the last release, pycha upstream author included most of my patches. So
+there is no more need to use my friendly fork of the project. Although you can
+use this version for the SVG support you should use the 'trunk' version.
+
+    http://www.lorenzogil.com/projects/pycha/
+
diff --git a/debian/changelog b/debian/changelog
new file mode 100644
index 0000000..6214050
--- /dev/null
+++ b/debian/changelog
@@ -0,0 +1,5 @@
+relatorio (0.5.0-1) unstable; urgency=low
+
+  * Initial release (Closes: #507460).
+
+ -- Daniel Baumann <daniel at debian.org>  Wed,  4 Feb 2009 18:31:00 +0100
diff --git a/debian/compat b/debian/compat
new file mode 100644
index 0000000..7f8f011
--- /dev/null
+++ b/debian/compat
@@ -0,0 +1 @@
+7
diff --git a/debian/control b/debian/control
new file mode 100644
index 0000000..28f45df
--- /dev/null
+++ b/debian/control
@@ -0,0 +1,18 @@
+Source: relatorio
+Section: python
+Priority: optional
+Maintainer: Daniel Baumann <daniel at debian.org>
+Build-Depends: debhelper (>= 7), python, python-all-dev, python-genshi, python-setuptools, python-support
+Standards-Version: 3.8.0
+Homepage: http://relatorio.openhex.org/
+Vcs-Browser: http://git.debian.net/?p=debian/relatorio.git
+Vcs-Git: git://git.debian.net/git/debian/relatorio.git
+
+Package: python-relatorio
+Architecture: all
+Depends: ${misc:Depends}, ${python:Depends}, python-genshi, python-pkg-resources
+XB-Python-Version: ${python:Versions}
+Description: Python module to create reports from Python objects
+ This is a Python module to create reports from Python objects. Output plugins
+ to several formats are included, such as document (odt, ods, pdf) or images
+ (png, svg).
diff --git a/debian/copyright b/debian/copyright
new file mode 100644
index 0000000..1ac12d4
--- /dev/null
+++ b/debian/copyright
@@ -0,0 +1,42 @@
+Authors: Nicolas Ivrard <nicoe at openhex.org>
+Download: http://relatorio.openhex.org/
+
+Files: *
+Copyright: (C) 2007-2009 OpenHex SPRL <http://www.openhex.com/>
+License: GPL-2+
+ This program 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; either version 2
+ of the License, or (at your option) any later version.
+ .
+ This program 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.
+ .
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ .
+ On Debian systems, the complete text of the GNU General Public License
+ can be found in /usr/share/common-licenses/GPL-2 file.
+
+Files: debian/*
+Copyright: (C) 2009 Daniel Baumann <daniel at debian.org>
+License: GPL-2+
+ This program 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; either version 2
+ of the License, or (at your option) any later version.
+ .
+ This program 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.
+ .
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ .
+ On Debian systems, the complete text of the GNU General Public License
+ can be found in /usr/share/common-licenses/GPL-2 file.
diff --git a/debian/pycompat b/debian/pycompat
new file mode 100644
index 0000000..0cfbf08
--- /dev/null
+++ b/debian/pycompat
@@ -0,0 +1 @@
+2
diff --git a/debian/python-relatorio.docs b/debian/python-relatorio.docs
new file mode 100644
index 0000000..62deb04
--- /dev/null
+++ b/debian/python-relatorio.docs
@@ -0,0 +1 @@
+AUTHORS
diff --git a/debian/python-relatorio.examples b/debian/python-relatorio.examples
new file mode 100644
index 0000000..e39721e
--- /dev/null
+++ b/debian/python-relatorio.examples
@@ -0,0 +1 @@
+examples/*
diff --git a/debian/pyversions b/debian/pyversions
new file mode 100644
index 0000000..8b253bc
--- /dev/null
+++ b/debian/pyversions
@@ -0,0 +1 @@
+2.4-
diff --git a/debian/rules b/debian/rules
new file mode 100755
index 0000000..c2527f3
--- /dev/null
+++ b/debian/rules
@@ -0,0 +1,44 @@
+#!/usr/bin/make -f
+
+clean:
+	dh_testdir
+	dh_testroot
+	rm -f build-stamp
+
+	python setup.py clean
+	rm -rf dist build
+	find . -type f -name "*.pyc" | xargs rm -f
+
+	dh_clean
+
+build:
+
+install:
+	dh_testdir
+	dh_testroot
+	dh_prep
+	dh_installdirs
+
+	python setup.py install --single-version-externally-managed --root=$(CURDIR)/debian/python-relatorio --install-lib /usr/share/python-support/python-relatorio
+
+	find debian/python-relatorio -type f -name "*.pyc" | xargs rm -f
+
+binary: binary-indep
+
+binary-arch:
+
+binary-indep: install
+	dh_testdir
+	dh_testroot
+	dh_installchangelogs CHANGES
+	dh_installdocs
+	dh_installexamples
+	dh_pysupport
+	dh_compress
+	dh_fixperms
+	dh_installdeb
+	dh_gencontrol
+	dh_md5sums
+	dh_builddeb
+
+.PHONY: clean build install binary binary-arch binary-indep
diff --git a/examples/basic.odt b/examples/basic.odt
new file mode 100644
index 0000000..3c74963
Binary files /dev/null and b/examples/basic.odt differ
diff --git a/examples/basic.tex b/examples/basic.tex
new file mode 100644
index 0000000..5316a30
--- /dev/null
+++ b/examples/basic.tex
@@ -0,0 +1,21 @@
+\enableregime [utf-8]
+\mainlanguage [fr]
+
+\starttext
+
+Dear $o.customer.name,
+
+Here is the list of your purchases:
+
+\starttable[|l|l|l|l|l|]
+\HL
+\NC Name \VL Reference \VL Quantity \VL Unit Price \VL Amount \SR
+\HL
+{% for line in o.lines%} \
+\NC $line.item.name \VL $line.item.reference \VL $line.quantity
+\VL $line.item.price \VL $line.amount \SR
+\HL \
+{% end %}
+\stoptable
+
+\stoptext
diff --git a/examples/bouteille.png b/examples/bouteille.png
new file mode 100644
index 0000000..ce076c3
Binary files /dev/null and b/examples/bouteille.png differ
diff --git a/examples/columns.odt b/examples/columns.odt
new file mode 100644
index 0000000..0deafd5
Binary files /dev/null and b/examples/columns.odt differ
diff --git a/examples/common.py b/examples/common.py
new file mode 100644
index 0000000..4806372
--- /dev/null
+++ b/examples/common.py
@@ -0,0 +1,40 @@
+class Invoice(dict):
+
+    @property
+    def total(self):
+        return sum(l['amount'] for l in self['lines'])
+
+    @property
+    def vat(self):
+        return self.total * 0.21
+
+
+inv = Invoice(customer={'name': 'John Bonham',
+                        'address': {'street': 'Smirnov street',
+                                    'zip': 1000,
+                                    'city': 'Montreux'}},
+              lines=[{'item': {'name': 'Vodka 70cl',
+                               'reference': 'VDKA-001',
+                               'price': 10.34},
+                      'quantity': 7,
+                      'amount': 7*10.34},
+                     {'item': {'name': 'Cognac 70cl',
+                               'reference': 'CGNC-067',
+                               'price': 13.46},
+                      'quantity': 12,
+                      'amount': 12*13.46},
+                     {'item': {'name': 'Sparkling water 25cl',
+                               'reference': 'WATR-007',
+                               'price': 4},
+                      'quantity': 1,
+                      'amount': 4},
+                     {'item': {'name': 'Good customer',
+                               'reference': 'BONM-001',
+                               'price': -20},
+                      'quantity': 1,
+                      'amount': -20},
+                    ],
+              id='MZY-20080703',
+              status='late',
+              bottle=(file('bouteille.png', 'r'), 'image/png'))
+
diff --git a/examples/complicated.odt b/examples/complicated.odt
new file mode 100644
index 0000000..c36ce6a
Binary files /dev/null and b/examples/complicated.odt differ
diff --git a/examples/demo_chart.py b/examples/demo_chart.py
new file mode 100644
index 0000000..d2b621c
--- /dev/null
+++ b/examples/demo_chart.py
@@ -0,0 +1,15 @@
+from os.path import abspath
+from relatorio import Report
+
+# test data
+from common import inv
+
+if __name__ == '__main__':
+    pie_report = Report(abspath('pie_chart'), 'image/png')
+    file('pie.png', 'wb').write(pie_report(o=inv).render().getvalue())
+    hbar_report = Report(abspath('hbar_chart'), 'image/svg')
+    file('hbar.svg', 'wb').write(hbar_report(o=inv).render().getvalue())
+    vbar_report = Report(abspath('vbar_chart'), 'image/svg')
+    file('vbar.svg', 'wb').write(vbar_report(o=inv).render().getvalue())
+    line_report = Report(abspath('line_chart'), 'image/png')
+    file('line.png', 'wb').write(line_report(o=inv).render().getvalue())
diff --git a/examples/demo_context.py b/examples/demo_context.py
new file mode 100644
index 0000000..67a2897
--- /dev/null
+++ b/examples/demo_context.py
@@ -0,0 +1,14 @@
+from os.path import abspath
+from relatorio import Report
+
+# test data
+from common import inv
+
+#PDF
+if __name__ == '__main__':
+    print "generating output_basic.pdf... ",
+    report = Report(abspath('basic.tex'), 'application/pdf')
+    content = report(o=inv).render().getvalue()
+    file('output_basic.pdf', 'wb').write(content)
+    print "done"
+
diff --git a/examples/demo_odf.py b/examples/demo_odf.py
new file mode 100644
index 0000000..b6ed72a
--- /dev/null
+++ b/examples/demo_odf.py
@@ -0,0 +1,60 @@
+from os.path import abspath
+from relatorio import Report
+
+# test data
+from common import inv
+
+ODT_MIME = 'application/vnd.oasis.opendocument.text'
+ODS_MIME = 'application/vnd.oasis.opendocument.spreadsheet'
+ODP_MIME = 'application/vnd.oasis.opendocument.presentation'
+
+if __name__ == '__main__':
+    # ODT
+    print "generating output_basic.odt... ",
+    report = Report(abspath('basic.odt'), ODT_MIME)
+    content = report(o=inv).render().getvalue()
+    file('output_basic.odt', 'wb').write(content)
+    print "done"
+
+    # we could also use an opendocument template directly
+#    from relatorio.templates import opendocument
+#    template = opendocument.Template(source=None, filepath='basic.odt')
+#    content = template.generate(o=inv).render().getvalue()
+#    file('output_basic.odt', 'wb').write(content)
+
+    print "generating output_complicated.odt... ",
+    # Add a chart to the invoice
+    inv['chart'] = (Report(abspath('pie_chart'), 'image/png'), 'image/png')
+    report = Report(abspath('complicated.odt'), ODT_MIME)
+    content = report(o=inv).render().getvalue()
+    file('output_complicated.odt', 'wb').write(content)
+    print "done"
+
+    print "generating output_columns.odt... ",
+    report = Report(abspath('columns.odt'), ODT_MIME)
+    lst = [[], ['i'], ['a', 'b'], [1, 2, 3], ['I', 'II', 'III', 'IV']]
+    titles = ['first', 'second', 'third', 'fourth']
+    content = report(titles=titles, lst=lst).render().getvalue()
+    file('output_columns.odt', 'wb').write(content)
+    print "done"
+
+    # ODS
+    print "generating output_pivot.ods... ",
+    report = Report(abspath('pivot.ods'), ODS_MIME)
+    content = report(o=inv).render().getvalue()
+    file('output_pivot.ods', 'wb').write(content)
+    print "done"
+
+    print "generating output_sheets.ods... ",
+    report = Report(abspath('demo_sheets.ods'), ODS_MIME)
+    content = report(lst=lst).render().getvalue()
+    file('output_sheets.ods', 'wb').write(content)
+    print "done"
+
+    # ODP
+    print "generating output_presentation.odp... ",
+    report = Report(abspath('presentation.odp'), ODP_MIME)
+    content = report(o=inv).render().getvalue()
+    file('output_presentation.odp', 'wb').write(content)
+    print "done"
+
diff --git a/examples/demo_repository.py b/examples/demo_repository.py
new file mode 100644
index 0000000..e3c9900
--- /dev/null
+++ b/examples/demo_repository.py
@@ -0,0 +1,31 @@
+import relatorio
+from common import Invoice, inv
+
+ODT_MIME = 'application/vnd.oasis.opendocument.text'
+ODS_MIME = 'application/vnd.oasis.opendocument.spreadsheet'
+ODP_MIME = 'application/vnd.oasis.opendocument.presentation'
+
+repository = relatorio.ReportRepository()
+repository.add_report(Invoice, ODT_MIME, 'basic.odt', report_name='basic')
+repository.add_report(Invoice, ODT_MIME,
+                      'complicated.odt', report_name='complicated')
+repository.add_report(Invoice, ODS_MIME, 'pivot.ods', report_name='pivot')
+repository.add_report(Invoice, ODP_MIME,
+                      'presentation.odp', report_name='presentation')
+repository.add_report(Invoice, 'image/png', 'pie_chart', report_name='pie')
+
+if __name__ == '__main__':
+    # Add a chart to the invoice
+    inv['chart'] = repository.by_id(Invoice, 'pie')
+
+    # Generate all reports on the invoice class
+    for report_name, ext in (('basic', '.odt'),
+                             ('complicated', '.odt'),
+                             ('pivot', '.ods'),
+                             ('presentation', '.odp')):
+        filename = 'output_%s%s' % (report_name, ext)
+        print "generating '%s'..." % filename,
+        report, mimetype = repository.by_id(Invoice, report_name)
+        data = report(o=inv).render().getvalue()
+        file(filename, 'wb').write(data)
+        print "done"
diff --git a/examples/demo_sheets.ods b/examples/demo_sheets.ods
new file mode 100644
index 0000000..81c321d
Binary files /dev/null and b/examples/demo_sheets.ods differ
diff --git a/examples/hbar_chart b/examples/hbar_chart
new file mode 100644
index 0000000..0f6607b
--- /dev/null
+++ b/examples/hbar_chart
@@ -0,0 +1,32 @@
+options:
+  width: 600
+  height: 500
+  legend: 
+    hide: false
+    position: 
+      right: 40
+  padding: {bottom: 70, left: 70, right: 10, top: 10}
+  axis:
+    y:
+      interval: 15
+      padding: 5
+    x:
+      ticks:
+      {% for idx, line in enumerate(o.lines) %}
+        - v: $idx
+          label: $line.item.name
+      {% end %}
+chart:
+  type: hbar
+  output_type: svg
+  dataset:
+    - - Sales
+      -
+      {% for idx, line in enumerate(o.lines) %}
+        - [$idx, $line.amount]
+      {% end %}
+    - - Absolute sales
+      -
+      {% for idx, line in enumerate(o.lines) %}
+        - [$idx, ${abs(line.amount)}]
+      {% end %}
diff --git a/examples/line_chart b/examples/line_chart
new file mode 100644
index 0000000..1457845
--- /dev/null
+++ b/examples/line_chart
@@ -0,0 +1,27 @@
+options:
+  width: 600
+  height: 500
+  legend: 
+    hide: false
+    position: 
+      right: 40
+  padding: {bottom: 70, left: 70, right: 10, top: 10}
+  axis:
+    y:
+      interval: 10
+      padding: 10
+    x:
+      ticks:
+      {% for idx, line in enumerate(o.lines) %}
+        - v: $idx
+          label: $line.item.name
+      {% end %}
+chart:
+  type: line
+  output_type: png
+  dataset:
+    - - Sales
+      -
+      {% for idx, line in enumerate(o.lines) %}
+        - [$idx, $line.amount]
+      {% end %}
diff --git a/examples/pie_chart b/examples/pie_chart
new file mode 100644
index 0000000..4b24054
--- /dev/null
+++ b/examples/pie_chart
@@ -0,0 +1,15 @@
+options:
+    width: 600
+    height: 400
+    background: {hide: true}
+    legend: {hide: true}
+    axis: {labelFontSize: 14}
+    padding: {bottom: 10, left: 10, right: 10, top: 10}
+chart:
+    type: pie
+    output_type: png
+    dataset:
+    {% for line in o.lines %}
+      - - ${line.item.name}
+        - - [0, $line.amount]
+    {% end %}
diff --git a/examples/pivot.ods b/examples/pivot.ods
new file mode 100644
index 0000000..0d0b40f
Binary files /dev/null and b/examples/pivot.ods differ
diff --git a/examples/presentation.odp b/examples/presentation.odp
new file mode 100644
index 0000000..26a7980
Binary files /dev/null and b/examples/presentation.odp differ
diff --git a/examples/vbar_chart b/examples/vbar_chart
new file mode 100644
index 0000000..56c6790
--- /dev/null
+++ b/examples/vbar_chart
@@ -0,0 +1,32 @@
+options:
+  width: 600
+  height: 500
+  legend: 
+    hide: false
+    position: 
+      right: 40
+  padding: {bottom: 70, left: 70, right: 10, top: 10}
+  axis:
+    y:
+      interval: 20
+      padding: 5
+    x:
+      ticks:
+      {% for idx, line in enumerate(o.lines) %}
+        - v: $idx
+          label: $line.item.name
+      {% end %}
+chart:
+  type: vbar
+  output_type: svg
+  dataset:
+    - - Sales
+      -
+      {% for idx, line in enumerate(o.lines) %}
+        - [$idx, $line.amount]
+      {% end %}
+    - - Absolute sales
+      -
+      {% for idx, line in enumerate(o.lines) %}
+        - [$idx, ${abs(line.amount)}]
+      {% end %}
diff --git a/relatorio/__init__.py b/relatorio/__init__.py
new file mode 100644
index 0000000..6b4d39a
--- /dev/null
+++ b/relatorio/__init__.py
@@ -0,0 +1,15 @@
+"""
+relatorio
+=========
+
+A templating library which provides a way to easily output all kind of
+different files (odt, ods, png, svg, ...). Adding support for more filetype is
+easy: you just have to create a plugin for this.
+
+relatorio also provides a report repository allowing you to link python objects
+and report together, find reports by mimetypes/name/python objects.
+"""
+from relatorio.reporting import MIMETemplateLoader, ReportRepository, Report
+import templates
+
+__version__ = 'development'
diff --git a/relatorio/reporting.py b/relatorio/reporting.py
new file mode 100644
index 0000000..cccd6c1
--- /dev/null
+++ b/relatorio/reporting.py
@@ -0,0 +1,168 @@
+###############################################################################
+#
+# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
+# Reserved.
+#
+# This program 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; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program 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.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+###############################################################################
+
+__metaclass__ = type
+
+import os, sys
+
+import pkg_resources
+from genshi.template import TemplateLoader
+
+def _absolute(path):
+    "Compute the absolute path of path relative to the caller file"
+    if os.path.isabs(path):
+        return path
+    caller_fname = sys._getframe(2).f_globals['__file__']
+    caller_dir = os.path.dirname(caller_fname)
+    return os.path.abspath(os.path.join(caller_dir, path))
+
+def _guess_type(mime):
+    """
+    Returns the codename used by relatorio to identify which template plugin
+    it should use to render a mimetype
+    """
+    mime = mime.lower()
+    major, stype = mime.split('/', 1)
+    if major == 'application':
+        if 'opendocument' in stype:
+            return 'oo.org'
+        else:
+            return stype
+    elif major == 'text':
+        if stype in ('xml', 'html', 'xhtml'):
+            return 'markup'
+        else:
+            return 'text'
+
+
+class MIMETemplateLoader(TemplateLoader):
+    """This subclass of TemplateLoader use mimetypes to search and find
+    templates to load.
+    """
+
+    factories = {}
+
+    mime_func = [_guess_type]
+
+    def get_type(self, mime):
+        "finds the codename used by relatorio to work on a mimetype"
+        for func in reversed(self.mime_func):
+            codename = func(mime)
+            if codename is not None:
+                return codename
+
+    def load(self, path, mime):
+        "returns a template object based on path"
+        rtype = self.get_type(mime)
+        return super(MIMETemplateLoader, self).load(path,
+                                                    cls=self.factories[rtype])
+
+    @classmethod
+    def add_factory(cls, abbr_mimetype, template_factory, id_function=None):
+        """adds a template factory to the already known factories"""
+        cls.factories[abbr_mimetype] = template_factory
+        if id_function is not None:
+            cls.mime_func.append(id_function)
+
+default_loader = MIMETemplateLoader(auto_reload=True)
+
+
+class DefaultFactory:
+    """This is the default factory used by relatorio.
+
+    It just returns a copy of the data it receives"""
+
+    def __call__(self, **kwargs):
+        data = kwargs.copy()
+        return data
+
+default_factory = DefaultFactory()
+
+
+class Report:
+    """Report is a simple interface on top of a rendering template.
+    """
+
+    def __init__(self, path, mimetype,
+                 factory=default_factory, loader=default_loader):
+        self.fpath = path
+        self.mimetype = mimetype
+        self.data_factory = factory
+        self.tmpl_loader = loader
+        self.filters = []
+
+    def __call__(self, **kwargs):
+        template = self.tmpl_loader.load(self.fpath, self.mimetype)
+        data = self.data_factory(**kwargs)
+        return template.generate(**data).filter(*self.filters)
+
+    def __repr__(self):
+        return '<relatorio report on %s>' % self.fpath
+
+
+
+class ReportDict:
+
+    def __init__(self, *args, **kwargs):
+        self.mimetypes = {}
+        self.ids = {}
+
+
+class ReportRepository:
+    """ReportRepository stores the report definition associated to objects.
+
+    The report are indexed in this object by the object class they are working
+    on and the name given to it by the user.
+    """
+
+    def __init__(self, datafactory=DefaultFactory):
+        self.classes = {}
+        self.default_factory = datafactory
+        self.loader = default_loader
+
+    def add_report(self, klass, mimetype, template_path, data_factory=None,
+                   report_name='default'):
+        """adds a report to the repository.
+
+        You will be able to find the report via
+            - the class it is working on
+            - the mimetype it outputs
+            - the name of the report
+
+        You also have the opportunity to define a specific data_factory.
+        """
+        if data_factory is None:
+            data_factory = self.default_factory
+        reports = self.classes.setdefault(klass, ReportDict())
+        report = Report(_absolute(template_path), mimetype, data_factory(),
+                        self.loader)
+        reports.ids[report_name] = report, mimetype
+        reports.mimetypes.setdefault(mimetype, []) \
+                         .append((report, report_name))
+
+    def by_mime(self, klass, mimetype):
+        """gets a list of report related to a class by specifying the mimetype
+        """
+        return self.classes[klass].mimetypes[mimetype]
+
+    def by_id(self, klass, id):
+        """get a report related to a class by its id
+        """
+        return self.classes[klass].ids[id]
diff --git a/relatorio/templates/__init__.py b/relatorio/templates/__init__.py
new file mode 100644
index 0000000..5b61bdf
--- /dev/null
+++ b/relatorio/templates/__init__.py
@@ -0,0 +1,30 @@
+###############################################################################
+#
+# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
+# Reserved.
+#
+# This program 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; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program 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.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+###############################################################################
+
+import warnings
+
+plugins = ['base', 'opendocument', 'pdf', 'chart']
+
+for name in plugins:
+    try:
+        __import__('relatorio.templates.%s' % name)
+    except:
+        warnings.warn("Unable to load plugin '%s', you will not be able "
+                      "to use it" % name)
diff --git a/relatorio/templates/base.py b/relatorio/templates/base.py
new file mode 100644
index 0000000..ba9c1c9
--- /dev/null
+++ b/relatorio/templates/base.py
@@ -0,0 +1,54 @@
+###############################################################################
+#
+# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
+# Reserved.
+#
+# This program 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; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program 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.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+###############################################################################
+
+__metaclass__ = type
+
+from cStringIO import OutputType
+
+import genshi.core
+from genshi.template import NewTextTemplate, MarkupTemplate
+
+from relatorio.reporting import Report, MIMETemplateLoader
+
+
+class RelatorioStream(genshi.core.Stream):
+    "Base class for the relatorio streams."
+
+    def render(self, method=None, encoding='utf-8', out=None, **kwargs):
+        "calls the serializer to render the template"
+        return self.serializer(self.events)
+
+    def serialize(self, method='xml', **kwargs):
+        "generates the bitstream corresponding to the template"
+        return self.render(method, **kwargs)
+
+    def __or__(self, function):
+        "Support for the bitwise operator"
+        return RelatorioStream(self.events | function, self.serializer)
+
+    def __str__(self):
+        val = self.render()
+        if isinstance(val, OutputType):
+            return val.getvalue()
+        else:
+            return val
+
+MIMETemplateLoader.add_factory('text', NewTextTemplate)
+MIMETemplateLoader.add_factory('xml', MarkupTemplate)
diff --git a/relatorio/templates/chart.py b/relatorio/templates/chart.py
new file mode 100644
index 0000000..8b4765c
--- /dev/null
+++ b/relatorio/templates/chart.py
@@ -0,0 +1,93 @@
+###############################################################################
+#
+# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
+# Reserved.
+#
+# This program 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; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program 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.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+###############################################################################
+
+__metaclass__ = type
+
+from cStringIO import StringIO
+
+import yaml
+import genshi
+import genshi.output
+from genshi.template import NewTextTemplate
+
+from relatorio.templates.base import RelatorioStream
+from relatorio.reporting import MIMETemplateLoader
+
+import cairo
+import pycha
+import pycha.pie
+import pycha.line
+import pycha.bar
+
+PYCHA_TYPE = {'pie': pycha.pie.PieChart,
+              'vbar': pycha.bar.VerticalBarChart,
+              'hbar': pycha.bar.HorizontalBarChart,
+              'line': pycha.line.LineChart,
+             }
+_encode = genshi.output.encode
+
+
+class Template(NewTextTemplate):
+    "A chart templating object"
+
+    def generate(self, *args, **kwargs):
+        generated = super(Template, self).generate(*args, **kwargs)
+        return RelatorioStream(generated, CairoSerializer())
+
+    @staticmethod
+    def id_function(mimetype):
+        "The function used to return the codename."
+        if mimetype in ('image/png', 'image/svg'):
+            return 'chart'
+
+
+class CairoSerializer:
+
+    def __init__(self):
+        self.text_serializer = genshi.output.TextSerializer()
+
+    def __call__(self, stream):
+        result = StringIO()
+        yml = StringIO(_encode(self.text_serializer(stream)))
+        chart_yaml = yaml.load(yml.read())
+        chart_info = chart_yaml['chart']
+        chart_type = chart_info['output_type']
+        if chart_type == 'png':
+            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
+                                         chart_yaml['options']['width'],
+                                         chart_yaml['options']['height'])
+        elif chart_type == 'svg':
+            surface = cairo.SVGSurface(result, chart_yaml['options']['width'],
+                                       chart_yaml['options']['height'])
+        else:
+            raise NotImplementedError
+        
+        chart = PYCHA_TYPE[chart_info['type']](surface, chart_yaml['options'])
+        chart.addDataset(chart_info['dataset'])
+        chart.render()
+        
+        if chart_type == 'png':
+            surface.write_to_png(result)
+        elif chart_type == 'svg':
+            surface.finish()
+
+        return result
+
+MIMETemplateLoader.add_factory('chart', Template, Template.id_function)
diff --git a/relatorio/templates/opendocument.py b/relatorio/templates/opendocument.py
new file mode 100644
index 0000000..1519ea2
--- /dev/null
+++ b/relatorio/templates/opendocument.py
@@ -0,0 +1,649 @@
+###############################################################################
+#
+# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
+# Reserved.
+#
+# This program 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; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program 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.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+###############################################################################
+
+__metaclass__ = type
+
+import re
+import md5
+import time
+import urllib
+import zipfile
+from cStringIO import StringIO
+from copy import deepcopy
+
+
+import warnings
+warnings.filterwarnings('always', module='relatorio.templates.opendocument')
+
+import lxml.etree
+import genshi
+import genshi.output
+from genshi.template import MarkupTemplate
+from genshi.filters import Transformer
+from genshi.filters.transform import ENTER, EXIT
+from genshi.core import Stream
+
+
+from relatorio.templates.base import RelatorioStream
+from relatorio.reporting import Report, MIMETemplateLoader
+try:
+    from relatorio.templates.chart import Template as ChartTemplate
+except ImportError:
+    ChartTemplate = type(None)
+
+GENSHI_EXPR = re.compile(r'''
+        (/)?                                 # is this a closing tag?
+        (for|if|choose|when|otherwise|with)  # tag directive
+        \s*
+        (?:\s(\w+)=["'](.*)["']|$)           # match a single attr & its value
+        |
+        .*                                   # or anything else
+        ''', re.VERBOSE)
+
+EXTENSIONS = {'image/png': 'png',
+              'image/jpeg': 'jpg',
+              'image/bmp': 'bmp',
+              'image/gif': 'gif',
+              'image/tiff': 'tif',
+              'image/xbm': 'xbm',
+             }
+
+RELATORIO_URI = 'http://relatorio.openhex.org/'
+output_encode = genshi.output.encode
+EtreeElement = lxml.etree.Element
+
+def guess_type(val):
+    if isinstance(val, (str, unicode)):
+        return 'string'
+    elif isinstance(val, (int, float)):
+        return 'float'
+
+class OOTemplateError(genshi.template.base.TemplateSyntaxError):
+    "Error to raise when there is a SyntaxError in the genshi template"
+
+
+class ImageHref:
+    "A class used to add images in the odf zipfile"
+
+    def __init__(self, zfile, context):
+        self.zip = zfile
+        self.context = context.copy()
+
+    def __call__(self, expr):
+        bitstream, mimetype = expr
+        if isinstance(bitstream, Report):
+            bitstream = bitstream(**self.context).render()
+        elif isinstance(bitstream, ChartTemplate):
+            bitstream = bitstream.generate(**self.context).render()
+        bitstream.seek(0)
+        file_content = bitstream.read()
+        name = md5.new(file_content).hexdigest()
+        path = 'Pictures/%s.%s' % (name, EXTENSIONS[mimetype])
+        if path not in self.zip.namelist():
+            self.zip.writestr(path, file_content)
+        return {'{http://www.w3.org/1999/xlink}href': path}
+
+
+class ColumnCounter:
+    """A class used to count the actual maximum number of cells (and thus
+    columns) a table contains accross its rows.
+    """
+    def __init__(self):
+        self.temp_counters = {}
+        self.counters = {}
+
+    def reset(self, loop_id):
+        self.temp_counters[loop_id] = 0
+
+    def inc(self, loop_id):
+        self.temp_counters[loop_id] += 1
+
+    def store(self, loop_id, table_name):
+        self.counters[table_name] = max(self.temp_counters.pop(loop_id),
+                                        self.counters.get(table_name, 0))
+
+
+def wrap_nodes_between(first, last, new_parent):
+    """An helper function to move all nodes between two nodes to a new node
+    and add that new node to their former parent. The boundary nodes are
+    removed in the process.
+    """
+    old_parent = first.getparent()
+    for node in first.itersiblings():
+        if node is last:
+            break
+        # appending a node to a new parent also
+        # remove it from its previous parent
+        new_parent.append(node)
+    old_parent.replace(first, new_parent)
+    old_parent.remove(last)
+
+
+class Template(MarkupTemplate):
+
+    def __init__(self, source, filepath=None, filename=None, loader=None,
+                 encoding=None, lookup='strict', allow_exec=True):
+        self.namespaces = {}
+        self.inner_docs = []
+        self.has_col_loop = False
+        super(Template, self).__init__(source, filepath, filename, loader,
+                                       encoding, lookup, allow_exec)
+
+    def _parse(self, source, encoding):
+        """parses the odf file.
+
+        It adds genshi directives and finds the inner docs.
+        """
+        zf = zipfile.ZipFile(self.filepath)
+        content = zf.read('content.xml')
+        styles = zf.read('styles.xml')
+
+        template = super(Template, self)
+        content = template._parse(self.insert_directives(content), encoding)
+        styles = template._parse(self.insert_directives(styles), encoding)
+        content_files = [('content.xml', content)]
+        styles_files = [('styles.xml', styles)]
+
+        while self.inner_docs:
+            doc = self.inner_docs.pop()
+            c_path, s_path = doc + '/content.xml', doc + '/styles.xml'
+            content = zf.read(c_path)
+            styles = zf.read(s_path)
+
+            c_parsed = template._parse(self.insert_directives(content),
+                                       encoding)
+            s_parsed = template._parse(self.insert_directives(styles),
+                                       encoding)
+            content_files.append((c_path, c_parsed))
+            styles_files.append((s_path, s_parsed))
+
+        zf.close()
+        parsed = []
+        for fpath, fparsed in content_files + styles_files:
+            parsed.append((genshi.core.PI, ('relatorio', fpath), None))
+            parsed += fparsed
+
+        return parsed
+
+    def insert_directives(self, content):
+        """adds the genshi directives, handle the images and the innerdocs.
+        """
+        tree = lxml.etree.parse(StringIO(content))
+        root = tree.getroot()
+        self.namespaces = root.nsmap.copy()
+        self.namespaces['py'] = 'http://genshi.edgewall.org/'
+        self.namespaces['relatorio'] = RELATORIO_URI
+
+        self._invert_style(tree)
+        self._handle_relatorio_tags(tree)
+        self._handle_images(tree)
+        self._handle_innerdocs(tree)
+        return StringIO(lxml.etree.tostring(tree))
+
+    def _invert_style(self, tree):
+        "inverts the text:a and text:span"
+        xpath_expr = "//text:a[starts-with(@xlink:href, 'relatorio://')]" \
+                     "/text:span"
+        for span in tree.xpath(xpath_expr, namespaces=self.namespaces):
+            text_a = span.getparent()
+            outer = text_a.getparent()
+            text_a.text = span.text
+            span.text = ''
+            text_a.remove(span)
+            outer.replace(text_a, span)
+            span.append(text_a)
+
+    def _relatorio_statements(self, tree):
+        "finds the relatorio statements (text:a/text:placeholder)"
+        # If this node href matches the relatorio URL it is kept.
+        # If this node href matches a genshi directive it is kept for further
+        # processing.
+        xlink_href_attrib = '{%s}href' % self.namespaces['xlink']
+        text_a = '{%s}a' % self.namespaces['text']
+        placeholder = '{%s}placeholder' % self.namespaces['text']
+        s_xpath = "//text:a[starts-with(@xlink:href, 'relatorio://')]" \
+                  "| //text:placeholder"
+
+        r_statements = []
+        opened_tags = []
+        # We map each opening tag with its closing tag
+        closing_tags = {}
+        for statement in tree.xpath(s_xpath, namespaces=self.namespaces):
+            if statement.tag == placeholder:
+                expr = statement.text[1:-1]
+            elif statement.tag == text_a:
+                expr = urllib.unquote(statement.attrib[xlink_href_attrib][12:])
+
+            if not expr:
+                raise OOTemplateError("No expression in the tag",
+                                      self.filepath)
+            closing, directive, attr, attr_val = \
+                    GENSHI_EXPR.match(expr).groups()
+            is_opening = closing != '/'
+
+            warn_msg = None
+            if not statement.text:
+                warn_msg = "No statement text in '%s' for '%s'" \
+                           % (self.filepath, expr)
+            elif expr != statement.text and statement.tag == text_a:
+                warn_msg = "url and text do not match in %s: %s != %s" \
+                           % (self.filepath, expr,
+                              statement.text.encode('utf-8'))
+            if warn_msg:
+                if directive is not None and not is_opening:
+                    warn_msg += " corresponding to opening tag '%s'" \
+                                % opened_tags[-1].text
+                warnings.warn(warn_msg)
+
+            if directive is not None:
+                # map closing tags with their opening tag
+                if is_opening:
+                    opened_tags.append(statement)
+                else:
+                    closing_tags[id(opened_tags.pop())] = statement
+            # - we only need to return opening statements
+            if is_opening:
+                r_statements.append((statement,
+                                     (expr, directive, attr, attr_val))
+                                   )
+        assert not opened_tags
+        return r_statements, closing_tags
+
+    def _handle_relatorio_tags(self, tree):
+        """
+        Will treat all relatorio tag (py:if/for/choose/when/otherwise)
+        tags
+        """
+        # Some tag/attribute name constants
+        table_namespace = self.namespaces['table']
+        table_row_tag = '{%s}table-row' % table_namespace
+        table_cell_tag = '{%s}table-cell' % table_namespace
+
+        office_name = '{%s}value' % self.namespaces['office']
+        office_valuetype = '{%s}value-type' % self.namespaces['office']
+
+        py_namespace = self.namespaces['py']
+        py_attrs_attr = '{%s}attrs' % py_namespace
+        py_replace = '{%s}replace' % py_namespace
+
+        r_statements, closing_tags = self._relatorio_statements(tree)
+
+        for r_node, parsed in r_statements:
+            expr, directive, attr, a_val = parsed
+
+            # If the node is a genshi directive statement:
+            if directive is not None:
+                opening = r_node
+                closing = closing_tags[id(r_node)]
+
+                # - we find the nearest common ancestor of the closing and
+                #   opening statements
+                o_ancestors = [opening]
+                c_ancestors = [closing] + list(closing.iterancestors())
+                ancestor = None
+                for node in opening.iterancestors():
+                    try:
+                        idx = c_ancestors.index(node)
+                        assert c_ancestors[idx] == node
+                        # we only need ancestors up to the common one
+                        del c_ancestors[idx:]
+                        ancestor = node
+                        break
+                    except ValueError:
+                        # c_ancestors.index(node) raise ValueError if node is
+                        # not a child of c_ancestors
+                        pass
+                    o_ancestors.append(node)
+                assert ancestor is not None, \
+                       "No common ancestor found for opening and closing tag"
+
+                outermost_o_ancestor = o_ancestors[-1]
+                outermost_c_ancestor = c_ancestors[-1]
+
+                # handle horizontal repetitions (over columns)
+                if directive == "for" and ancestor.tag == table_row_tag:
+                    a_val = self._handle_column_loops(parsed, ancestor,
+                                                      opening,
+                                                      outermost_o_ancestor,
+                                                      outermost_c_ancestor)
+
+                # - we create a <py:xxx> node
+                if attr is not None:
+                    attribs = {attr: a_val}
+                else:
+                    attribs = {}
+                genshi_node = EtreeElement('{%s}%s' % (py_namespace,
+                                                       directive),
+                                           attrib=attribs,
+                                           nsmap=self.namespaces)
+
+                # - we move all the nodes between the opening and closing
+                #   statements to this new node (append also removes from old
+                #   parent)
+                # - we replace the opening statement by the <py:xxx> node
+                # - we delete the closing statement (and its ancestors)
+                wrap_nodes_between(outermost_o_ancestor, outermost_c_ancestor,
+                                   genshi_node)
+            else:
+                # It's not a genshi statement it's a python expression
+                r_node.attrib[py_replace] = expr
+                parent = r_node.getparent().getparent()
+                if parent is None or parent.tag != table_cell_tag:
+                    continue
+
+                # The grand-parent tag is a table cell we should set the
+                # correct value and type for this cell.
+                dico = "{'%s': %s, '%s': __relatorio_guess_type(%s)}"
+                parent.attrib[py_attrs_attr] = dico % (office_name, expr,
+                                                       office_valuetype, expr)
+                parent.attrib.pop(office_valuetype, None)
+                parent.attrib.pop(office_name, None)
+
+    def _handle_column_loops(self, statement, ancestor, opening,
+                             outer_o_node, outer_c_node):
+        _, directive, attr, a_val = statement
+
+        self.has_col_loop = True
+
+        table_namespace = self.namespaces['table']
+        table_col_tag = '{%s}table-column' % table_namespace
+        table_num_col_attr = '{%s}number-columns-repeated' % table_namespace
+
+        py_namespace = self.namespaces['py']
+        py_attrs_attr = '{%s}attrs' % py_namespace
+
+        repeat_tag = '{%s}repeat' % self.namespaces['relatorio']
+
+        # table node (it is not necessarily the direct parent of ancestor)
+        table_node = ancestor.iterancestors('{%s}table' % table_namespace) \
+                             .next()
+        table_name = table_node.attrib['{%s}name' % table_namespace]
+
+        # add counting instructions
+        loop_id = id(opening)
+
+        # 1) add reset counter code on the row opening tag
+        #    (through a py:attrs attribute).
+        # Note that table_name is not needed in the first two
+        # operations, but a unique id within the table is required
+        # to support nested column repetition
+        ancestor.attrib[py_attrs_attr] = \
+            "__relatorio_reset_col_count(%d)" % loop_id
+
+        # 2) add increment code (through a py:attrs attribute) on
+        #    the first cell node after the opening (cell node)
+        #    ancestor
+        enclosed_cell = outer_o_node.getnext()
+        assert enclosed_cell.tag == '{%s}table-cell' % table_namespace
+        enclosed_cell.attrib[py_attrs_attr] = \
+            "__relatorio_inc_col_count(%d)" % loop_id
+
+        # 3) add "store count" code as a py:replace node, as the
+        #    last child of the row
+        attr_value = "__relatorio_store_col_count(%d, %r)" \
+                     % (loop_id, table_name)
+        replace_node = EtreeElement('{%s}replace' % py_namespace,
+                                    attrib={'value': attr_value},
+                                    nsmap=self.namespaces)
+        ancestor.append(replace_node)
+
+        # find the position in the row of the cells holding the
+        # <for> and </for> instructions
+        # We use "*" so as to count both normal cells and covered/hidden cells
+        position_xpath_expr = 'count(preceding-sibling::*)'
+        opening_pos = \
+            int(outer_o_node.xpath(position_xpath_expr,
+                                   namespaces=self.namespaces))
+        closing_pos = \
+            int(outer_c_node.xpath(position_xpath_expr,
+                                   namespaces=self.namespaces))
+
+        # check whether or not the opening tag spans several rows
+        a_val = self._handle_row_spanned_column_loops(
+                    statement, outer_o_node, opening_pos, closing_pos)
+
+        # check if this table's headers were already processed
+        repeat_node = table_node.find(repeat_tag)
+        if repeat_node is not None:
+            prev_pos = (int(repeat_node.attrib['opening']),
+                        int(repeat_node.attrib['closing']))
+            if (opening_pos, closing_pos) != prev_pos:
+                raise Exception(
+                    'Incoherent column repetition found! '
+                    'If a table has several lines with repeated '
+                    'columns, the repetition need to be on the '
+                    'same columns across all lines.')
+        else:
+            # compute splits: oo collapses the headers of adjacent
+            # columns which use the same style. We need to split
+            # any column header which is repeated so many times
+            # that it encompasses any of the column headers that
+            # we need to repeat
+            to_split = []
+            idx = 0
+            childs = list(table_node.iterchildren(table_col_tag))
+            for tag in childs:
+                inc = int(tag.attrib.get(table_num_col_attr, 1))
+                oldidx = idx
+                idx += inc
+                if oldidx < opening_pos < idx or \
+                   oldidx < closing_pos < idx:
+                    to_split.append(tag)
+
+            # split tags
+            for tag in to_split:
+                tag_pos = table_node.index(tag)
+                num = int(tag.attrib.pop(table_num_col_attr))
+                new_tags = [deepcopy(tag) for _ in range(num)]
+                table_node[tag_pos:tag_pos+1] = new_tags
+
+            # recompute the list of column headers as it could
+            # have changed.
+            coldefs = list(table_node.iterchildren(table_col_tag))
+
+            # compute the column header nodes corresponding to
+            # the opening and closing tags.
+            first = table_node[opening_pos]
+            last = table_node[closing_pos]
+
+            # add a <relatorio:repeat> node around the column
+            # definitions nodes
+            attribs = {
+               "opening": str(opening_pos),
+               "closing": str(closing_pos),
+               "table": table_name
+            }
+            repeat_node = EtreeElement(repeat_tag, attrib=attribs,
+                                       nsmap=self.namespaces)
+            wrap_nodes_between(first, last, repeat_node)
+        return a_val
+
+    def _handle_row_spanned_column_loops(self, statement, outer_o_node,
+                                         opening_pos, closing_pos):
+        """handles column repetitions which span several rows, by duplicating
+        the py:for node for each row, and make the loops work on a copy of the
+        original iterable as to not exhaust generators."""
+
+        _, directive, attr, a_val = statement
+        table_rowspan_attr = '{%s}number-rows-spanned' \
+                             % self.namespaces['table']
+
+        # checks wether there is a (meaningful) rowspan
+        rows_spanned = int(outer_o_node.attrib.get(table_rowspan_attr, 1))
+        if rows_spanned == 1:
+            return a_val
+
+        py_namespace = self.namespaces['py']
+        table_namespace = self.namespaces['table']
+        table_row_tag = '{%s}table-row' % table_namespace
+        table_cov_cell_tag = '{%s}covered-table-cell' % table_namespace
+
+        # if so, we need to:
+
+        # 1) create a with node to define a temporary variable
+        temp_var = "__relatorio_temp%d" % id(outer_o_node)
+        # a_val == "target in iterable"
+        target, iterable = a_val.split(' in ', 1)
+        vars = "%s = list(%s)" % (temp_var, iterable.strip())
+        with_node = EtreeElement('{%s}with' % py_namespace,
+                                 attrib={"vars": vars},
+                                 nsmap=self.namespaces)
+
+        # 2) transform a_val to use that temporary variable
+        a_val = "%s in %s" % (target, temp_var)
+
+        # 3) wrap the corresponding cells on the next row(s)
+        #    (those should be covered-table-cell) inside a
+        #    duplicate py:for node (looping on the temporary
+        #    variable).
+        row_node = outer_o_node.getparent()
+        row_node.addprevious(with_node)
+        rows_to_wrap = [row_node]
+        assert row_node.tag == table_row_tag
+        next_rows = row_node.itersiblings(table_row_tag)
+        for row_idx in range(rows_spanned-1):
+            next_row_node = next_rows.next()
+            rows_to_wrap.append(next_row_node)
+            # compute the start and end nodes
+            first = next_row_node[opening_pos]
+            last = next_row_node[closing_pos]
+            assert first.tag == table_cov_cell_tag
+            assert last.tag == table_cov_cell_tag
+            # wrap them
+            tag = '{%s}%s' % (py_namespace, directive)
+            for_node = EtreeElement(tag,
+                                    attrib={attr: a_val},
+                                    nsmap=self.namespaces)
+            wrap_nodes_between(first, last, for_node)
+
+        # 4) wrap all the corresponding rows indide the "with"
+        #    node
+        for node in rows_to_wrap:
+            with_node.append(node)
+        return a_val
+
+    def _handle_images(self, tree):
+        "replaces all draw:frame named 'image: ...' by draw:image nodes"
+        draw_name = '{%s}name' % self.namespaces['draw']
+        draw_image = '{%s}image' % self.namespaces['draw']
+        py_attrs = '{%s}attrs' % self.namespaces['py']
+        xpath_expr = "//draw:frame[starts-with(@draw:name, 'image:')]"
+        for draw in tree.xpath(xpath_expr, namespaces=self.namespaces):
+            d_name = draw.attrib[draw_name]
+            attr_expr = "__relatorio_make_href(%s)" % d_name[7:]
+            image_node = EtreeElement(draw_image,
+                                      attrib={py_attrs: attr_expr},
+                                      nsmap=self.namespaces)
+            draw.replace(draw[0], image_node)
+
+    def _handle_innerdocs(self, tree):
+        "finds inner_docs and adds them to the processing stack."
+        href_attrib = '{%s}href' % self.namespaces['xlink']
+        xpath_expr = "//draw:object[starts-with(@xlink:href, './')" \
+                     "and @xlink:show='embed']"
+        for draw in tree.xpath(xpath_expr, namespaces=self.namespaces):
+            self.inner_docs.append(draw.attrib[href_attrib][2:])
+
+    def generate(self, *args, **kwargs):
+        "creates the RelatorioStream."
+        serializer = OOSerializer(self.filepath)
+        kwargs['__relatorio_make_href'] = ImageHref(serializer.outzip, kwargs)
+        kwargs['__relatorio_guess_type'] = guess_type
+
+        counter = ColumnCounter()
+        kwargs['__relatorio_reset_col_count'] = counter.reset
+        kwargs['__relatorio_inc_col_count'] = counter.inc
+        kwargs['__relatorio_store_col_count'] = counter.store
+
+        stream = super(Template, self).generate(*args, **kwargs)
+        if self.has_col_loop:
+            transformation = DuplicateColumnHeaders(counter)
+            col_filter = Transformer('//repeat[namespace-uri()="%s"]'
+                                     % RELATORIO_URI)
+            col_filter = col_filter.apply(transformation)
+            stream = Stream(list(stream), self.serializer) | col_filter
+        return RelatorioStream(stream, serializer)
+
+
+class DuplicateColumnHeaders(object):
+    def __init__(self, counter):
+        self.counter = counter
+
+    def __call__(self, stream):
+        for mark, (kind, data, pos) in stream:
+            # for each repeat tag found
+            if mark is ENTER:
+                # get the number of columns for that table
+                attrs = data[1]
+                table = attrs.get('table')
+                col_count = self.counter.counters[table]
+
+                # collect events (column header tags) to repeat
+                events = []
+                for submark, event in stream:
+                    if submark is EXIT:
+                        break
+                    events.append(event)
+
+                # repeat them
+                for _ in range(col_count):
+                    for event in events:
+                        yield None, event
+            else:
+                yield mark, (kind, data, pos)
+
+
+class OOSerializer:
+
+    def __init__(self, oo_path):
+        self.inzip = zipfile.ZipFile(oo_path)
+        self.new_oo = StringIO()
+        self.outzip = zipfile.ZipFile(self.new_oo, 'w')
+        self.xml_serializer = genshi.output.XMLSerializer()
+
+    def __call__(self, stream):
+        files = {}
+        for kind, data, pos in stream:
+            if kind == genshi.core.PI and data[0] == 'relatorio':
+                stream_for = data[1]
+                continue
+            files.setdefault(stream_for, []).append((kind, data, pos))
+
+        now = time.localtime()[:6]
+        for f_info in self.inzip.infolist():
+            if f_info.filename.startswith('ObjectReplacements'):
+                continue
+            elif f_info.filename in files:
+                stream = files[f_info.filename]
+                # create a new file descriptor, copying some attributes from
+                # the original file
+                new_info = zipfile.ZipInfo(f_info.filename, now)
+                for attr in ('compress_type', 'flag_bits', 'create_system'):
+                    setattr(new_info, attr, getattr(f_info, attr))
+                serialized_stream = output_encode(self.xml_serializer(stream))
+                self.outzip.writestr(new_info, serialized_stream)
+            else:
+                self.outzip.writestr(f_info, self.inzip.read(f_info.filename))
+        self.inzip.close()
+        self.outzip.close()
+
+        return self.new_oo
+
+MIMETemplateLoader.add_factory('oo.org', Template)
diff --git a/relatorio/templates/pdf.py b/relatorio/templates/pdf.py
new file mode 100644
index 0000000..d515af1
--- /dev/null
+++ b/relatorio/templates/pdf.py
@@ -0,0 +1,69 @@
+###############################################################################
+#
+# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
+# Reserved.
+#
+# This program 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; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program 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.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+###############################################################################
+
+__metaclass__ = type
+
+import os
+import shutil
+import tempfile
+import subprocess
+from cStringIO import StringIO
+
+import genshi
+import genshi.output
+from genshi.template import NewTextTemplate
+
+from relatorio.templates.base import RelatorioStream
+from relatorio.reporting import MIMETemplateLoader
+
+TEXEXEC_PATH = '/usr/bin/texexec'
+_encode = genshi.output.encode
+
+
+class Template(NewTextTemplate):
+
+    def generate(self, *args, **kwargs):
+        generated = super(Template, self).generate(*args, **kwargs)
+        return RelatorioStream(generated, PDFSerializer())
+
+
+class PDFSerializer:
+
+    def __init__(self):
+        self.working_dir = tempfile.mkdtemp(prefix='relatorio')
+        self.tex_file = os.path.join(self.working_dir, 'report.tex')
+        self.pdf_file = os.path.join(self.working_dir, 'report.pdf')
+        self.text_serializer = genshi.output.TextSerializer()
+
+    def __call__(self, stream):
+        tex_file = open(self.tex_file, 'w')
+        tex_file.write(_encode(self.text_serializer(stream)))
+        tex_file.close()
+
+        subprocess.check_call([TEXEXEC_PATH, '--purge', 'report.tex'],
+                              cwd=self.working_dir)
+
+        pdf = StringIO()
+        pdf.write(open(self.pdf_file, 'r').read())
+
+        shutil.rmtree(self.working_dir, ignore_errors=True)
+        return pdf
+
+MIMETemplateLoader.add_factory('pdf', Template)
diff --git a/relatorio/tests/__init__.py b/relatorio/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/relatorio/tests/egg.jpg b/relatorio/tests/egg.jpg
new file mode 100644
index 0000000..2700e16
Binary files /dev/null and b/relatorio/tests/egg.jpg differ
diff --git a/relatorio/tests/one.jpg b/relatorio/tests/one.jpg
new file mode 100644
index 0000000..48723f0
Binary files /dev/null and b/relatorio/tests/one.jpg differ
diff --git a/relatorio/tests/templates/other.tmpl b/relatorio/tests/templates/other.tmpl
new file mode 100644
index 0000000..224a5d0
--- /dev/null
+++ b/relatorio/tests/templates/other.tmpl
@@ -0,0 +1 @@
+Another Hello.
diff --git a/relatorio/tests/templates/test.tmpl b/relatorio/tests/templates/test.tmpl
new file mode 100644
index 0000000..3b06a49
--- /dev/null
+++ b/relatorio/tests/templates/test.tmpl
@@ -0,0 +1 @@
+Hello ${o.name}.
diff --git a/relatorio/tests/templates/time.tmpl b/relatorio/tests/templates/time.tmpl
new file mode 100644
index 0000000..8467d56
--- /dev/null
+++ b/relatorio/tests/templates/time.tmpl
@@ -0,0 +1,2 @@
+Hi ${o.name},
+It's ${time} to ${func(y)} !
diff --git a/relatorio/tests/test.odt b/relatorio/tests/test.odt
new file mode 100644
index 0000000..a077357
Binary files /dev/null and b/relatorio/tests/test.odt differ
diff --git a/relatorio/tests/test_api.py b/relatorio/tests/test_api.py
new file mode 100644
index 0000000..22f4336
--- /dev/null
+++ b/relatorio/tests/test_api.py
@@ -0,0 +1,112 @@
+###############################################################################
+#
+# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
+# Reserved.
+#
+# This program 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; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program 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.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+###############################################################################
+
+
+import os
+from nose.tools import *
+
+from relatorio.reporting import (ReportRepository, Report, MIMETemplateLoader,
+                                 DefaultFactory, _absolute, _guess_type)
+
+
+class StubObject(object):
+
+    def __init__(self, **kwargs):
+        for key, val in kwargs.iteritems():
+            setattr(self, key, val)
+
+
+class TestRepository(object):
+
+    def test_register(self):
+        "Testing the registration"
+        reporting = ReportRepository()
+        reporting.add_report(StubObject, 'text/plain',
+                             os.path.join('templates', 'test.tmpl'))
+
+        assert_true(StubObject in reporting.classes)
+        assert_true('default' in reporting.classes[StubObject].ids)
+        assert_true('text/plain' in reporting.classes[StubObject].mimetypes)
+
+        report, mime = reporting.classes[StubObject].ids['default']
+        eq_(mime, 'text/plain')
+        eq_(report.mimetype, 'text/plain')
+        assert_true(report.fpath.endswith(os.path.join('templates',
+                                                       'test.tmpl')))
+
+        report2, name = reporting.classes[StubObject].mimetypes['text/plain'][0]
+        eq_(name, 'default')
+        eq_(report, report2)
+
+    def test_mimeguesser(self):
+        eq_(_guess_type('application/pdf'), 'pdf')
+        eq_(_guess_type('text/plain'), 'text')
+        eq_(_guess_type('text/xhtml'), 'markup')
+        eq_(_guess_type('application/vnd.oasis.opendocument.text'), 'oo.org')
+
+    def abspath_helper(self, path):
+        return _absolute(path)
+
+    def test_absolute(self):
+        "Test the absolute path calculation"
+        eq_("/home/nicoe/python/mock.py",
+            _absolute("/home/nicoe/python/mock.py"))
+
+        our_dir, _ = os.path.split(__file__)
+        # We use this because me go up by two frames
+        new_path = self.abspath_helper(os.path.join('brol', 'toto'))
+        eq_(os.path.join(our_dir, 'brol', 'toto'), new_path)
+
+
+class TestReport(object):
+
+    def setup(self):
+        self.loader = MIMETemplateLoader()
+        our_dir, _ = os.path.split(__file__)
+        self.report = Report(os.path.join(our_dir, 'templates', 'test.tmpl'),
+                             'text/plain', DefaultFactory(), self.loader)
+
+    def test_report(self):
+        "Testing the report generation"
+        a = StubObject(name='OpenHex')
+        eq_(self.report(o=a).render(), 'Hello OpenHex.\n')
+
+    def test_factory(self):
+        "Testing the data factory"
+        class MyFactory:
+            def __call__(self, o, time, y=1):
+                d = dict()
+                d['o'] = o
+                d['y'] = y
+                d['time'] = time
+                d['func'] = lambda x: x+1
+                return d
+
+        our_dir, _ = os.path.split(__file__)
+        report = Report(os.path.join(our_dir, 'templates', 'time.tmpl'),
+                        'text/plain', MyFactory(), self.loader)
+
+        a = StubObject(name='Foo')
+        eq_(report(o=a, time="One o'clock").render(),
+            "Hi Foo,\nIt's One o'clock to 2 !\n")
+        eq_(report(o=a, time="One o'clock", y=4).render(),
+            "Hi Foo,\nIt's One o'clock to 5 !\n")
+        assert_raises(TypeError, report, a)
+
diff --git a/relatorio/tests/test_odt.py b/relatorio/tests/test_odt.py
new file mode 100644
index 0000000..5351d2a
--- /dev/null
+++ b/relatorio/tests/test_odt.py
@@ -0,0 +1,166 @@
+# -*- encoding: utf-8 -*-
+###############################################################################
+#
+# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
+# Reserved.
+#
+# This program 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; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program 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.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+###############################################################################
+
+
+import os
+import re
+from cStringIO import StringIO
+
+import lxml.etree
+from nose.tools import *
+import genshi
+from genshi.filters import Translator
+from genshi.core import PI
+from genshi.template.eval import UndefinedError
+
+from templates.opendocument import Template, GENSHI_EXPR
+
+def pseudo_gettext(string):
+    catalog = {'Mes collègues sont:': 'My colleagues are:',
+               'Bonjour,': 'Hello,',
+               'Je suis un test de templating en odt.':
+                'I am an odt templating test',
+               'Felix da housecat': unicode('Félix le chat de la maison',
+                                            'utf8'),
+               'We sell stuff': u'On vend des choses',
+              }
+    return catalog.get(string, string)
+
+
+class TestOOTemplating(object):
+
+    def setup(self):
+        thisdir = os.path.dirname(__file__)
+        filepath = os.path.join(thisdir, 'test.odt')
+        self.oot = Template(file(filepath), filepath)
+        self.data = {'first_name': u'Trente',
+                     'last_name': unicode('Møller', 'utf8'),
+                     'ville': unicode('Liège', 'utf8'),
+                     'friends': [{'first_name': u'Camille',
+                                  'last_name': u'Salauhpe'},
+                                 {'first_name': u'Mathias',
+                                  'last_name': u'Lechat'}],
+                     'hobbies': [u'Music', u'Dancing', u'DJing'],
+                     'animals': [u'Felix da housecat', u'Dog eat Dog'],
+                     'images': [(file(os.path.join(thisdir, 'one.jpg')),
+                                 'image/jpeg'),
+                                (file(os.path.join(thisdir, 'two.png')),
+                                 'image/png')],
+                     'oeuf': file(os.path.join(thisdir, 'egg.jpg')),
+                     'footer': u'We sell stuff'}
+
+    def test_init(self):
+        "Testing the correct handling of the styles.xml and content.xml files"
+        ok_(isinstance(self.oot.stream, list))
+        eq_(self.oot.stream[0], (PI, ('relatorio', 'content.xml'), None))
+        ok_((PI, ('relatorio', 'content.xml'), None) in self.oot.stream)
+
+    def test_directives(self):
+        "Testing the directives interpolation"
+        xml = '''<b:a xmlns:b="urn:b" xmlns:text="%s" xmlns:draw="urn:draw"
+        xmlns:table="urn:table" xmlns:office="urn:office"
+        xmlns:xlink="urn:xlink">
+        <text:a xlink:href="relatorio://foo">foo</text:a>
+        </b:a>''' % 'urn:text'
+        interpolated = self.oot.insert_directives(xml)
+        root_interpolated = lxml.etree.parse(interpolated).getroot()
+        root_attrs = root_interpolated[0].attrib
+        eq_(root_attrs['{http://genshi.edgewall.org/}replace'], 'foo')
+
+    def test_styles(self):
+        "Testing that styles get rendered"
+        stream = self.oot.generate(**self.data)
+        rendered = stream.events.render()
+        ok_('We sell stuff' in rendered)
+
+        dico = self.data.copy()
+        del dico['footer']
+        stream = self.oot.generate(**dico)
+        assert_raises(UndefinedError, lambda: stream.events.render())
+
+    def test_generate(self):
+        "Testing that content get rendered"
+        stream = self.oot.generate(**self.data)
+        rendered = stream.events.render()
+        ok_('Bonjour,' in rendered)
+        ok_('Trente' in rendered)
+        ok_('Møller' in rendered)
+        ok_('Dog eat Dog' in rendered)
+        ok_('Felix da housecat' in rendered)
+
+    def test_filters(self):
+        "Testing the filters with the Translator filter"
+        stream = self.oot.generate(**self.data)
+        translated = stream.filter(Translator(pseudo_gettext))
+        translated_xml = translated.events.render()
+        ok_("Hello," in translated_xml)
+        ok_("I am an odt templating test" in translated_xml)
+        ok_('Felix da housecat' not in translated_xml)
+        ok_('Félix le chat de la maison' in translated_xml)
+        ok_('We sell stuff' not in translated_xml)
+        ok_('On vend des choses' in translated_xml)
+
+    def test_images(self):
+        "Testing the image replacement directive"
+        stream = self.oot.generate(**self.data)
+        rendered = stream.events.render()
+        styles_idx = rendered.find('<?relatorio styles.xml?>')
+        tree = lxml.etree.parse(StringIO(rendered[25:styles_idx]))
+        root = tree.getroot()
+        images = root.xpath('//draw:frame', namespaces=self.oot.namespaces)
+        eq_(len(images), 3)
+        eq_(images[0].attrib['{%s}name' % self.oot.namespaces['draw']],
+            "image: (oeuf, 'image/png')")
+        eq_(images[1].attrib['{%s}name' % self.oot.namespaces['draw']],
+            'image: img')
+        eq_(images[1].attrib['{%s}width' % self.oot.namespaces['svg']],
+            '1.732cm')
+        eq_(images[1].attrib['{%s}height' % self.oot.namespaces['svg']],
+            '1.513cm')
+        eq_(images[2].attrib['{%s}width' % self.oot.namespaces['svg']],
+            '1.732cm')
+        eq_(images[2].attrib['{%s}height' % self.oot.namespaces['svg']],
+            '1.513cm')
+
+    def test_regexp(self):
+        "Testing the regexp used to find relatorio tags"
+        # a valid expression
+        group = GENSHI_EXPR.match('for each="foo in bar"').groups()
+        eq_(group, (None, 'for', 'each', 'foo in bar'))
+
+        # invalid expr
+        group = GENSHI_EXPR.match('foreach="foo in bar"').groups()
+        eq_(group, (None, None, None, None))
+
+        # valid closing tags
+        group = GENSHI_EXPR.match('/for').groups()
+        eq_(group, ('/', 'for', None, None))
+        group = GENSHI_EXPR.match('/for ').groups()
+        eq_(group, ('/', 'for', None, None))
+
+        # another non matching expr
+        group = GENSHI_EXPR.match('formatLang("en")').groups()
+        eq_(group, (None, None, None, None))
+
+    def test_str(self):
+        "Testing that a RelatorioStream str returns a bitstream"
+        stream = str(self.oot.generate(**self.data))
+        ok_(isinstance(stream, str))
diff --git a/relatorio/tests/two.png b/relatorio/tests/two.png
new file mode 100644
index 0000000..f7d65d5
Binary files /dev/null and b/relatorio/tests/two.png differ
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 0000000..f22112a
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,2 @@
+[egg_info]
+
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..9252123
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,29 @@
+# -*- encoding: utf-8 -*-
+import relatorio
+from setuptools import setup, find_packages
+
+setup(
+    name="relatorio",
+    url="http://relatorio.openhex.org",
+    author="Nicolas Evrard",
+    author_email="nicoe at openhex.org",
+    description="A templating library able to output odt and pdf files",
+    long_description=relatorio.__doc__,
+    license="GPL License",
+    version=relatorio.__version__,
+    packages=find_packages(exclude=['relatorio.tests', 'examples']),
+    install_requires=[
+        "Genshi >= 0.5",
+        "lxml >= 1.3.6"
+    ],
+    classifiers=[
+        "Development Status :: 4 - Beta",
+        "Intended Audience :: Developers",
+        "License :: OSI Approved :: GNU General Public License (GPL)",
+        "Operating System :: OS Independent",
+        "Programming Language :: Python",
+        "Topic :: Software Development :: Libraries :: Python Modules",
+        "Topic :: Text Processing",
+    ],
+    test_suite="nose.collector",
+    )
-- 
relatorio



More information about the tryton-debian-vcs mailing list