diff --git a/COPYRIGHT b/COPYRIGHT
new file mode 100644
--- /dev/null
+++ b/COPYRIGHT
@@ -0,0 +1,61 @@
+The ChristmasTree package is (c) copyright 2008
+to the original authors and other contributors listed here.  If you add
+or modify code, please add your name here.
+
+Original authors:
+        Marcos Viera
+	Doaitse Swierstra
+	Eelco Lempsink
+
+----
+The GRead package is licensed under the terms of the GNU Lesser General Public
+Licence (LGPL), which can be found in the file called LICENCE-LGPL, with
+the following special exception:
+
+    As a relaxation of clause 6 of the LGPL, the copyright holders of this
+    library give permission to use, copy, link, modify, and distribute,
+    binary-only object-code versions of an executable linked with the
+    original unmodified Library, without requiring the supply of any
+    mechanism to modify or replace the Library and relink (clauses 6a,
+    6b, 6c, 6d, 6e), provided that all the other terms of clause 6 are
+    complied with.
+
+This software 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
+License for more details.
+
+----
+This software depends on library code by Daan Leijen, which
+is distributed under the following license:
+
+                       The Modified BSD License
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions 
+are met:
+
+  * Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+
+  * Redistributions in binary form must reproduce the above
+    copyright notice, this list of conditions and the following
+    disclaimer in the documentation and/or other materials provided
+    with the distribution.
+
+  * Neither the names of the copyright holders, nor the names of its
+    contributors may be used to endorse or promote products derived 
+    from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
diff --git a/ChristmasTree.bib b/ChristmasTree.bib
new file mode 100644
--- /dev/null
+++ b/ChristmasTree.bib
@@ -0,0 +1,13 @@
+@inproceedings{1411296,
+ author = {Marcos Viera and S. Doaitse Swierstra and Eelco Lempsink},
+ title = {Haskell, do you read me?: constructing and composing efficient top-down parsers at runtime},
+ booktitle = {Haskell '08: Proceedings of the first ACM SIGPLAN symposium on Haskell},
+ year = {2008},
+ isbn = {978-1-60558-064-7},
+ pages = {63--74},
+ location = {Victoria, BC, Canada},
+ doi = {http://doi.acm.org/10.1145/1411286.1411296},
+ publisher = {ACM},
+ address = {New York, NY, USA},
+ }
+
diff --git a/ChristmasTree.cabal b/ChristmasTree.cabal
new file mode 100644
--- /dev/null
+++ b/ChristmasTree.cabal
@@ -0,0 +1,26 @@
+cabal-version:      >=1.2
+build-type:         Simple
+name:               ChristmasTree
+version:            0.1
+license:            LGPL
+license-file:       COPYRIGHT
+maintainer:         Marcos Viera <mviera@fing.edu.uy>
+homepage:           http://www.cs.uu.nl/wiki/bin/view/Center/TTTAS
+description:        Alternative approach of 'read' that composes grammars instead of parsers. It reads data in linear time, while the function 'read' has an exponential behavior in some cases of data types with infix operators.
+synopsis:           Changing Haskell's Read Implementation Such That by Mainpulating Abstract Syntax Trees it Reads Expressions Efficiently
+category:           Parsing 
+stability:          Experimental
+copyright:          Universiteit Utrecht
+build-depends:      base, haskell98, template-haskell, containers,
+                    fgl>=5.4, TTTAS, uulib 
+exposed-modules:    Text.GRead, Text.GShow, 
+                    Text.GRead.Derive, Text.GRead.Grammar
+other-modules:      Text.GRead.Derive.BindingGroup,
+                    Text.GRead.Transformations.GramTrafo, 
+                    Text.GRead.Transformations.Group, 
+                    Text.GRead.Transformations.LeftCorner,
+                    Text.GRead.Transformations.LeftFact     
+extensions:         Arrows, GADTs, TemplateHaskell
+hs-source-dirs:     src
+extra-source-files: README, LICENSE-LGPL, ChristmasTree.bib
+ghc-options:        -Wall
diff --git a/LICENSE-LGPL b/LICENSE-LGPL
new file mode 100644
--- /dev/null
+++ b/LICENSE-LGPL
@@ -0,0 +1,507 @@
+                  GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations
+below.
+
+  When we speak of free software, we are referring to freedom of use,
+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 and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it
+becomes a de-facto standard.  To achieve this, non-free programs must
+be allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+
+                  GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, 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 library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+  1. You may copy and distribute verbatim copies of the Library's
+complete 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 distribute a copy of this License along with the
+Library.
+
+  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 Library or any portion
+of it, thus forming a work based on the Library, 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) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+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 Library, 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 Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you 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.
+
+  If distribution of 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 satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at least
+    three years, to give the same user the materials specified in
+    Subsection 6a, above, for a charge no more than the cost of
+    performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be 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.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library 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.
+
+  9. 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 Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+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 with
+this License.
+
+  11. 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 Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library 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 Library.
+
+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.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library 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.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser 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 Library
+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 Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+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
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "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
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. 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 LIBRARY 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
+LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey 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 library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library 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
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
+
diff --git a/README b/README
new file mode 100644
--- /dev/null
+++ b/README
@@ -0,0 +1,43 @@
+Please check the right section in this file for instructions depending on how you obtained the source files.
+
+
+Installing ChristmasTree from a source distribution
+-------------------------------------------
+
+  The source distribution can be unpacked from the
+  .tar.gz files distributed in the following page:
+
+    http://www.cs.uu.nl/wiki/bin/view/Center/TTTAS
+
+  System wide installation (assumming GHC is the
+  Haskell compiler) can be done like this:
+
+    ghc --make Setup.hs -o setup -package Cabal
+    ./setup configure
+    ./setup build
+    ./setup install
+
+
+Installing uulib to a non-standard location
+-------------------------------------------
+
+  This is useful if you don't want (or can't)
+  modify system wide settings.
+
+    ghc --make Setup.hs -o setup -package Cabal
+    ./setup configure --prefix=/foo
+    ./setup build
+    ./setup install --user
+
+  The last command registers the package only for
+  the user.
+
+
+
+Optionally generating Haddock Documentation
+-------------------------------------------
+
+  Output generated in dist/doc/html
+
+    ./setup haddock
+
diff --git a/Setup.hs b/Setup.hs
new file mode 100644
--- /dev/null
+++ b/Setup.hs
@@ -0,0 +1,3 @@
+
+import Distribution.Simple
+main = defaultMain
diff --git a/examples/Test.hs b/examples/Test.hs
new file mode 100644
--- /dev/null
+++ b/examples/Test.hs
@@ -0,0 +1,127 @@
+module Test where
+
+import Text.GRead
+import Language.TTTAS
+
+infixl 5 :<:, :+:
+infixr 6 :>:, :*:
+
+data T1  =  T1 :<: T1
+         |  T1 :>: T1
+         |  C1
+         deriving (Read, Show)
+
+data T2 a  =  T2 a  :+: T2 a
+           |  a     :*: T2 a
+           |  C2
+         deriving (Read, Show)
+
+data T3 = T3 T4 | C3
+         deriving (Read, Show)
+data T4 = T4 T3 | C4
+         deriving (Read, Show)
+
+
+_0 = Zero
+_1 = Suc _0
+_2 = Suc _1
+
+
+instance Gram T1 where
+ grammar = DGrammar _0 envT1
+
+envT1 :: Env DGram ((),T1) ((),T1) 
+envT1 =  consD (nonts _0) Empty 
+     where
+      nonts _T1 = DLNontDefs
+       [  (  DRef (_T1, 5) 
+          ,  DPS  [  dNont (_T1, 5) .#. dTerm ":<:" .#.
+                     dNont (_T1, 6) .#. dEnd infixL ]
+          )
+       ,  (  DRef (_T1, 6) 
+          ,  DPS  [  dNont (_T1, 7) .#. dTerm ":>:" .#.
+                     dNont (_T1, 6) .#. dEnd infixR ] 
+          ) 
+       ,  (  DRef (_T1,10) 
+          ,  DPS  [  dTerm "C1"   .#. dEnd (const C1)
+                  ,  dTerm "(" .#. dNont (_T1,0) .#. 
+                     dTerm ")" .#. dEnd parenT ] 
+          )
+       ]
+      infixL e1 _ e2   = e2 :<: e1
+      infixR e1 _ e2   = e2 :>: e1 
+
+
+instance Gram a => Gram (T2 a) where
+ grammar = DGrammar   _0  envT2 
+
+envT2 :: (Gram a) => Env DGram  (((),a),T2 a)
+                                (((),a),T2 a)
+envT2 =  consD (nonts  _0 _1) $ 
+         consG grammar Empty
+     where
+      nonts _T2 _A = DLNontDefs
+       [  (  DRef (_T2, 5) 
+          ,  DPS  [  dNont (_T2,  6)  .#. dTerm ":+:" .#.
+                     dNont (_T2,  6)  .#. dEnd infixP ] 
+          )
+       ,  (  DRef (_T2, 6)
+          ,  DPS  [  dNont (_A,   7)  .#. dTerm ":*:" .#. 
+                     dNont (_T2,  7)  .#. dEnd infixT ] 
+          )
+       ,  (  DRef (_T2,10) 
+          ,  DPS  [  dTerm "C2"   .#. dEnd (const C2)
+                  ,  dTerm "("    .#. dNont (_T2,0) .#. 
+                     dTerm ")"    .#. dEnd parenT ] 
+          )
+       ]
+      infixP   e1 _ e2  = e2 :+: e1
+      infixT   e1 _ e2  = e2 :*: e1 
+
+envT3T4 :: Env DGram (((), T4), T3) (((), T4), T3)
+envT3T4 =  consD (nonts3 _0 _1) $
+           consD (nonts4 _1 _0) Empty  
+     where
+      nonts3 _T3 _T4 = DLNontDefs
+       [  (  DRef (_T3,10) 
+          ,  DPS  [  dTerm "T3" .#. dNont (_T4,0) .#. 
+                     dEnd consT3 
+                  ,  dTerm "C3" .#. dEnd (const C3) 
+                  ,  dTerm "(" .#. dNont (_T3,0) .#. 
+                     dTerm ")" .#. dEnd parenT  
+                  ]
+          )
+       ]
+      nonts4 _T4 _T3 = DLNontDefs
+       [  (  DRef (_T4,10) 
+          ,  DPS  [  dTerm "T4" .#. dNont (_T3,0) .#. 
+                     dEnd consT4 
+                  ,  dTerm "C4" .#. dEnd (const C4) 
+                  ,  dTerm "(" .#. dNont (_T4,0) .#. 
+                     dTerm ")" .#. dEnd parenT  
+                  ]
+          )
+       ]
+      consT3 a  = const (T3 a) 
+      consT4 a  = const (T4 a) 
+
+instance Gram T3 where
+ grammar = DGrammar _0 envT3T4
+
+instance Gram T4 where
+ grammar = DGrammar _1 envT3T4
+
+read' :: (Gram a) => String -> a
+read' input = case gread input of
+                 Ok  a       -> a
+                 Rep _ (m:_) -> error $ show m
+
+v1 = read' "C1 :>: C1 :>: C1" :: T1
+v2 = read' "C1 :<: C1 :<: C1" :: T1
+v3 = read' "C1 :>: C1 :<: C1 :>: C1" :: T1
+v4 = read' "(((((((((((((C1)))))))))))))" :: T1
+v5 = read' "(C1 :>: C1) :*: C2 :+: C2" :: T2 T1
+v6 = read' "T3 T4 T3 T4 C3" :: T3
+v7 = read' "T4 T3 T4 T3 T4 C3" :: T4
+v8 = read' "bla" :: T1 -- error
+
diff --git a/examples/Test2.hs b/examples/Test2.hs
new file mode 100644
--- /dev/null
+++ b/examples/Test2.hs
@@ -0,0 +1,45 @@
+{-# OPTIONS  -XScopedTypeVariables -XRankNTypes #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Test2 where
+
+import Text.GRead
+import Text.GRead.Derive
+
+infixl 5 :<:, :+:
+infixr 6 :>:, :*:
+
+data T1  =  T1 :<: T1
+         |  T1 :>: T1
+         |  C1
+         deriving (Read, Show)
+
+data T2 a  =  T2 a  :+: T2 a
+           |  a     :*: T2 a
+           |  C2
+         deriving (Read, Show)
+
+data T3 = T3 T4 | C3
+         deriving (Read, Show)
+data T4 = T4 T3 | C4
+         deriving (Read, Show)
+
+$(deriveGrammar ''T1)
+$(deriveGrammar ''T2)
+$(deriveGrammar ''T3)
+$(deriveGrammar ''T4)
+
+read' :: (Gram a) => String -> a
+read' input = case gread input of
+                 Ok  a       -> a
+                 Rep _ (m:_) -> error $ show m
+
+v1 = read' "C1 :>: C1 :>: C1" :: T1
+v2 = read' "C1 :<: C1 :<: C1" :: T1
+v3 = read' "C1 :>: C1 :<: C1 :>: C1" :: T1
+v4 = read' "(((((((((((((C1)))))))))))))" :: T1
+v5 = read' "(C1 :>: C1) :*: C2 :+: C2" :: T2 T1
+v6 = read' "T3 T4 T3 T4 C3" :: T3
+v7 = read' "T4 T3 T4 T3 T4 C3" :: T4
+v8 = read' "bla" :: T1 -- error
+
diff --git a/examples/TestDerive.hs b/examples/TestDerive.hs
new file mode 100644
--- /dev/null
+++ b/examples/TestDerive.hs
@@ -0,0 +1,128 @@
+{-# OPTIONS  -XScopedTypeVariables -XRank2Types #-}
+{-# LANGUAGE TemplateHaskell #-}
+module TestDerive where
+
+import Text.GRead
+import Text.GRead.Derive
+
+
+data T1  =  T1 :<: T1
+         |  T1 :>: T1
+         |  C1
+  deriving Show
+
+data T2 a  =  T2 a  :+: T2 a
+           |  a     :*: T2 a
+           |  C2
+  deriving Show
+
+data T3 = T3 T4 | C3
+  deriving Show
+
+data T4 = T4 T3 | C4
+  deriving Show
+
+data T5 = T5 T6 | C5
+  deriving Show
+
+data T6 = T6 T7
+  deriving Show
+
+data T7 = T7 T5
+  deriving Show
+
+data T8  =  T8 (T2 T8) 
+         |  C8
+  deriving Show
+
+data T9   =  T9 (T2 T10) 
+          |  C9
+  deriving Show
+
+data T10  =  T10 T9
+  deriving Show
+
+data T11  =  T11  (T2 T11) 
+                  (T2 T12) 
+  deriving Show
+
+data T12  =  T12  T11
+  deriving Show
+
+data T13     = T13
+  deriving Show
+
+data T14 a b = T14 a b
+  deriving Show
+
+data T15  =  T15 :-: T1
+          |  C15
+
+data T16  =  T1 :.: T16
+          |  C16
+
+
+
+$(deriveGrammar ''T1)
+$(deriveGrammar ''T2)
+$(deriveGrammar ''T3)
+$(deriveGrammar ''T4)
+$(deriveGrammar ''T5)
+$(deriveGrammar ''T6)
+$(deriveGrammar ''T7)
+$(deriveGrammar ''T8)
+$(deriveGrammar ''T9)
+$(deriveGrammar ''T10)
+$(deriveGrammar ''T11)
+$(deriveGrammar ''T12)
+$(deriveGrammar ''T13)
+$(deriveGrammar ''T14)
+-- $(deriveGrammar ''T15) -- doesn't work
+-- $(deriveGrammar ''T16) -- doesn't work
+
+
+data BT a b c d e 
+  = BT (BT a b c d e) (BT a b c d e) 
+  | O_A a | O_B b | O_C c | O_D d | O_E e  
+  | O_movl | O_movw | O_movb  | O_movzbw | O_movzbl | O_movzwl 
+  | O_movsbw | O_movsbl | O_movswl   | O_pushl | O_popl 
+  | O_pushfl | O_popfl  | O_notl | O_notw | O_notb  | O_sall | O_salw | O_salb
+  | O_sarl | O_sarw | O_sarb  | O_shrl | O_shrw | O_shrb
+  | O_roll | O_rolw | O_rolb  | O_rorl | O_rorw | O_rorb
+  | O_shldl | O_shrdl  | O_addl | O_addw | O_addb
+  | O_adcl  | O_subl | O_subw | O_subb   | O_sbbl
+  | O_imull | O_imulw | O_imulb | O_mull | O_divl | O_divw | O_divb
+  | O_idivl | O_xorl | O_xorw | O_xorb  | O_andl | O_andw | O_andb
+  | O_orl  | O_orw  | O_orb | O_incl | O_incw | O_incb
+  | O_decl | O_decw | O_decb  | O_negl | O_negw | O_negb
+  | O_testl | O_testw | O_testb | O_leal | O_cmpl | O_cmpw | O_cmpb
+  | O_cmpsb | O_scasb | O_movsl | O_movsw | O_movsb
+  | O_stosl | O_stosw | O_stosb | O_leave | O_ret | O_call | O_jmp
+  | O_je | O_jne  | O_jl | O_jle | O_jg | O_jge | O_js | O_jns
+  | O_jz | O_jnz  | O_jc | O_jnc | O_jo | O_jno | O_ja | O_jae
+  | O_jb | O_jbe  | O_jp | O_seta | O_setae | O_setb | O_setbe
+  | O_sete | O_setne | O_setl | O_setle | O_setg | O_setge
+  | O_setc | O_setcb  | O_btl | O_btsl | O_btrl | O_btcl
+  | O_cld  | O_cltd  | O_cwtl  | O_cbtw  | O_rep | O_repz | O_repnz
+  | O_fild | O_fildl | O_fildll  | O_fsubp | O_fsubr | O_fsubrp 
+  | O_fsubrl | O_fsubrs | O_fsubs | O_fsubl | O_fsub
+  | O_faddp | O_fadds | O_faddl | O_fadd | O_fiaddl
+  | O_fmul | O_fmuls | O_fmull | O_fmulp
+  | O_fimull | O_fdiv | O_fdivp | O_fdivr | O_fdivrs | O_fdivrl | O_fdivrp
+  | O_fidivl | O_fidivrl | O_fdivl | O_fdivs
+  | O_fprem  | O_fstp | O_fsts | O_fstps | O_fstl | O_fstpl | O_fstpt | O_fst
+  | O_fistl | O_fistpl | O_fistpll
+  | O_fld | O_flds | O_fldl | O_fldt | O_fldz | O_fld1 | O_fldl2e | O_fldln2
+  | O_fchs  | O_fsin | O_fcos | O_fptan | O_fsqrt | O_fpatan | O_fabs
+  | O_f2xm1 | O_fscale | O_fyl2x
+  | O_fucom | O_fucomp | O_fucompp
+  | O_fcomp | O_fcompp | O_fcoml | O_fcompl | O_ficompl
+  | O_fcoms | O_fcom | O_fcomps  | O_fnstsw | O_fnstcw            
+  | O_fldcw | O_frndint | O_fxch | O_sahf  | O_nop
+    deriving (Show, Eq, Read)
+
+$(deriveGrammar ''BT)
+
+
+res = gread "BT O_nop BT (O_B T10 C9) (O_E T14 C1 C3)" :: GReadResult (BT T1 T10 T11 T12 (T14 T1 T3))
+
diff --git a/examples/TestShow.hs b/examples/TestShow.hs
new file mode 100644
--- /dev/null
+++ b/examples/TestShow.hs
@@ -0,0 +1,62 @@
+{-# OPTIONS -XScopedTypeVariables -XRank2Types #-}
+{-# LANGUAGE TemplateHaskell  #-}
+
+module TestShow where
+
+import Text.GRead
+import Text.GRead.Derive
+
+import Text.GShow
+
+import Language.Haskell.TH
+import Language.Haskell.TH.Syntax
+
+
+data T1 = T1
+ deriving Show
+$(deriveShow ''T1)
+
+s1 = gshow T1
+
+data T2 a = T2
+
+$(deriveShow ''T2)
+
+s2 = gshow (T2 :: (T2 T1))
+
+data T3 a = T3 a
+  deriving Show
+
+$(deriveShow ''T3)
+
+s3 = gshow $ T3 T1
+
+infixl 5 :<:
+infixr 6 :>:
+
+data T4 a =  T4 a :<: a
+          |  T4 a :>: T4 a
+          |  C4
+ deriving Show
+
+data T5 = T5
+ deriving Show
+
+$(deriveShow ''T4)
+$(deriveShow ''T5)
+
+s41 = gshow (C4 :>: C4 :>: C4 :>: C4 :: T4 T5)
+s42 = gshow ((C4 :>: C4) :>: C4 :: T4 T5)
+s43 = gshow (C4 :>: (C4 :>: C4) :: T4 T5)
+s44 = gshow (C4 :>: C4 :>: C4 :<: T5 :: T4 T5)
+s45 = gshow (C4 :>: C4 :>: C4 :<: T5 :<: T5 :: T4 T5)
+
+$(deriveGrammar ''T4)
+$(deriveGrammar ''T5)
+
+v41 = gread s41 :: GReadResult (T4 T5)
+v42 = gread s42 :: GReadResult (T4 T5)
+v43 = gread s43 :: GReadResult (T4 T5)
+v44 = gread s44 :: GReadResult (T4 T5)
+v45 = gread s45 :: GReadResult (T4 T5)
+
diff --git a/src/Text/GRead.hs b/src/Text/GRead.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/GRead.hs
@@ -0,0 +1,145 @@
+{-# OPTIONS  -fglasgow-exts #-}
+
+{-| 
+    Alternative approach of 'read' that composes grammars instead 
+    of parsers. Grammars describing the data types are composed
+    dynamically, removing possible left-recursion and combining
+    common prefixes of alternatives.   
+
+    The function 'gread' defined here is able to handle the 
+    associativities defined for infix operators.
+
+    The function 'gread' reads data in linear time, while the 
+    function 'read' has an exponential behavior in some cases 
+    of data types with infix operators.
+
+    Non uniform data types are not supported, because they
+    generate infinite grammars.
+
+    The library is documented in the paper: /Haskell, do you read me?: constructing and composing efficient top-down parsers at runtime/
+
+    Bibtex entry: <http://www.cs.uu.nl/wiki/bin/viewfile/Center/TTTAS?rev=1;filename=GRead.bib>
+
+    For more documentation see the TTTAS webpage: <http://www.cs.uu.nl/wiki/bin/view/Center/TTTAS> .
+ -}
+
+module Text.GRead ( 
+               -- * Grammar Description 
+               module Text.GRead.Grammar, 
+
+               -- * Reading Functions
+               gread, 
+
+               -- * Types
+               GReadMsg, GReadResult(..) 
+
+             ) where
+
+import Language.TTTAS
+import Text.GRead.Grammar
+import Text.GRead.Transformations.LeftFact
+import Text.GRead.Transformations.LeftCorner
+import Text.GRead.Transformations.Group
+import UU.Parsing hiding (Symbol,parse,Ok)
+import qualified UU.Parsing as UU
+import List (findIndex)
+
+
+-- | Type of error repair messages.
+type GReadMsg = Message Token (Maybe Token)
+
+
+-- | Type of 'gread' results.
+data GReadResult a = Ok  a
+                   | Rep a [GReadMsg] 
+      deriving Show
+
+
+-- | The 'gread' reads input from a string, which must be 
+--   completely consumed by the input process.
+--   Returns @Ok value@ on a successful parse.
+--   Otherwise returns @Rep value msgs@, where the @value@
+--   results of parsing a repaired input. The list @msgs@ 
+--   contains the \"corrections\" done to the input.
+--
+--   For example, a 'read'-like implementation can be:
+--
+-- > read :: (Gram a) => String -> a
+-- > read input = case gread input of
+-- >                  Ok  a       -> a
+-- >                  Rep _ (m:_) -> error $ show m
+
+
+gread ::  (Gram a) => String -> GReadResult a
+gread =   (  parse . compile 
+          .  leftfactoring . leftcorner 
+          .  group ) grammar
+
+
+
+-- COMPILE --------------------------------------------------------------------
+
+newtype Const f a s = C {unC :: f a}
+
+compile :: forall a . Grammar a -> Parser Token a
+compile (Grammar (start :: Ref a env) rules) 
+                       = unC (lookupEnv start result)
+  where  result  =  
+          mapEnv 
+          (\ (PS ps) -> C (foldr1 (<|>) [ comp p | p <- ps]))
+          rules
+         comp :: forall t . Prod t env -> Parser Token t
+         comp (End x)   = pLow x 
+         comp (Seq (Term t) ss) 
+                       = (flip ($))  <$> pSym t <*> comp ss 
+         comp (Seq (Nont n) ss) 
+                       = (flip ($))  <$> unC (lookupEnv n result)
+                                     <*> comp ss
+
+mapEnv  ::  (forall a . f a s -> g a s)  
+        ->  Env f s env -> Env g s env
+mapEnv  _ Empty       = Empty
+mapEnv  f (Ext r v)   = Ext (mapEnv f r) (f v)
+
+
+instance Show Token where
+    show (Keyw s) = s
+    show Open     = "("
+    show Close    = ")"
+
+instance UU.Symbol Token where
+  deleteCost _ = 5
+
+
+-- PARSE ----------------------------------------------------------------------
+
+parse :: Parser Token a -> String -> GReadResult a
+parse p input = case rparse p input of
+                  (a,[]  ) -> Ok a
+                  (a,msgs) -> Rep a msgs
+
+
+rparse :: Parser Token a -> String -> (a, [GReadMsg])
+rparse p input = let ((Pair a _),msgs) =  eval (UU.parse p (tokenize input))
+                 in (a,msgs)
+ where eval :: Steps a Token (Maybe Token) -> (a, [GReadMsg])
+       eval (OkVal v        r) = let (a,msgs) = v `seq` (eval r) 
+                                 in  (v a,msgs)
+       eval (UU.Ok          r) = eval r
+       eval (Cost  _        r) = eval  r
+       eval (StRepair _ msg r) = let (v,msgs) = eval r 
+                                 in  (v,msg:msgs)
+       eval (Best _   r     _) = eval  r
+       eval (NoMoreSteps v   ) = (v,[]) 
+
+       tokenize []       = []
+       tokenize ('(':xs) = Open  : (tokenize xs)
+       tokenize (')':xs) = Close : (tokenize xs) 
+       tokenize (' ':xs) = tokenize xs
+       tokenize l        = case findIndex endTok l of
+                            Just i -> let (ky,rs) = splitAt i l
+                                      in  Keyw ky : (tokenize rs) 
+                            Nothing -> [Keyw l] 
+       
+       endTok t = t == ')' || t == ' ' || t == '(' 
+
diff --git a/src/Text/GRead/Derive.hs b/src/Text/GRead/Derive.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/GRead/Derive.hs
@@ -0,0 +1,355 @@
+{-# LANGUAGE TemplateHaskell #-}
+
+{-| 
+    Automatically derive 'Text.GRead.Gram' instances for data types.
+
+    /Note!/ This is not a complete implementation and will not work for all datatypes.
+
+    Unsupported are
+
+      * Multiple type arguments
+
+      * Tuple, Function, List types
+
+      * All primitive types (also when used in user defined types!)
+    
+    Use with care.
+ -}
+module Text.GRead.Derive (deriveGrammar, deriveSimpleGrammar) where
+
+import Text.GRead.Grammar
+import Language.TTTAS
+
+import Text.GRead.Derive.BindingGroup
+
+import Data.List (nub, foldl', foldl1')
+import Data.Foldable (foldr')
+import Data.Map (Map)
+import qualified Data.Map as Map (insertWith, empty, toList)
+import Control.Monad (foldM)
+
+import Language.Haskell.TH
+import Language.Haskell.TH.Syntax
+
+{-|
+    Derive a 'Text.GRead.Gram' instance.  This is a Template Haskell function.  Usage example:
+    
+@
+data T1 = C1 | C2 | C3
+
+$(deriveGrammar ''T1)
+@
+-}
+deriveGrammar :: Name -> Q [Dec]
+deriveGrammar name = do
+    bindingGroup <- getBindingGroup name
+    deriveGrammar' name bindingGroup
+
+
+{-|
+    Simpler version of 'deriveGrammar' that doesn't do binding group
+    calculations.  Use this for large types without cyclic references to other
+    types.
+
+    For example, if you want to derive the 'HDYRM.Gram' for 'T3' and 'T4'
+    below, you will need the normal 'deriveGrammar'.
+
+@
+data T3 = T3 T4 | C3
+data T4 = T4 T3 | C4
+@
+-}
+deriveSimpleGrammar :: Name -> Q [Dec]
+deriveSimpleGrammar name = deriveGrammar' name []
+
+deriveGrammar' :: Name -> BindingGroup -> Q [Dec]
+deriveGrammar' name bindingGroup = do
+    (UserD _ args cs) <- getUserType name
+    body              <- mkBody name cs bindingGroup
+    return [InstanceD (mkContext cs) (mkInstanceType name args) body]
+
+mkContext :: [Con] -> Cxt
+mkContext = map (AppT (ConT ''Gram)) . uniqueVars . consArgsTypes
+
+mkInstanceType :: Name -> [Name] -> Type
+mkInstanceType name = AppT (ConT ''Gram) . foldl1' AppT . (:) (ConT name) . map VarT
+
+consArgsTypes :: [Con] -> [Type]
+consArgsTypes = concatMap consArgs
+    where
+        consArgs :: Con -> [Type]
+        consArgs (NormalC _ args)      = map snd args
+        consArgs (InfixC  argl _ argr) = [snd argl, snd argr]
+
+uniqueVars :: [Type] -> [Type]
+uniqueVars = nub . filter isVarT . unrollApps
+    where
+        unrollApps :: [Type] -> [Type]
+        unrollApps [] = [] 
+        unrollApps (a@(AppT _ _):ts) = unrollApp a ++ unrollApps ts
+        unrollApps (other:ts)        = other : unrollApps ts
+
+isVarT :: Type -> Bool
+isVarT (VarT _) = True
+isVarT _        = False
+
+
+mkBody :: Name -> [Con] -> BindingGroup -> Q [Dec]
+mkBody top cs bindingGroup = do
+    let bindingGroup' | bindingGroup == [] = [(top, [])]
+                      | otherwise          = bindingGroup
+        neededInstances = concatMap snd bindingGroup'
+    strongEdges      <- mapM (calculateStrongEdges neededInstances) bindingGroup'
+    instances        <- mapM (createInstances neededInstances strongEdges) bindingGroup'
+    let instances'      = concat instances
+        nontsInstance   = mkNontsInstance strongEdges bindingGroup' (instanceExps instances')
+        topPat          = map varP (instanceNames instances')
+        env             = appsE $ (lamE topPat nontsInstance) : (linkRefs (length instances'))
+    [d| grammar = DGrammar Zero $(sigE env (envSignature cs (instanceTypes instances'))) |]
+    where
+        instanceNames = map (fst . fst)
+        instanceTypes = map (snd . fst)
+        instanceExps  = map snd
+
+
+-- Only edges that are not in the binding group
+calculateStrongEdges :: [(Name, [[Type]])] -> (Name, [(Name, [[Type]])]) -> Q (Name, [Type])
+calculateStrongEdges needed (typeName, edges) = do
+    (UserD _ _ cs) <- getUserType typeName
+    return $ (typeName, mkNonBGEdges typeName (map fst needed) (bindingGroupEdges typeName needed) cs)
+    where
+        bindingGroupEdges typeName needed = maybe [] concat $ Prelude.lookup typeName needed
+        
+        mkNonBGEdges self done before = filter (not . already done before self) . consArgsTypes
+
+        already :: [Name] -> [Type] -> Name -> Type -> Bool
+        already done before self (VarT _)      = True
+        already done before self c@(ConT name) =  elem c before 
+                                               || elem name done
+                                               || name == self
+        already done before self a@(AppT _ _)  = elem a before 
+                                               || elem (conName a) done
+                                               || (conName a) == self
+            where conName = (\(ConT name) -> name) . head . unrollApp
+        -- TODO Incomplete: TupleT, ListT, etc...
+   
+getEdges :: Name -> [(Name, [Type])] -> [Type]
+getEdges name = maybe [] id . Prelude.lookup name
+
+
+-- The non-terminal rules, wrapped in lambda expression to select the grammars from this closed group
+mkNontsInstance :: [(Name, [Type])] -> BindingGroup -> [ExpQ] -> Q Exp
+mkNontsInstance strongEdges bindingGroup instances = do
+        nontsTypes <- mapM (mkNontsType strongEdges) bindingGroup
+        appsE $ (lamE (mkNontsPat nontsTypes bindingGroup) (foldr' appE [|Empty|] instances)) 
+              : (mkNonts strongEdges bindingGroup)
+        where
+            mkNonts edges    = map (mkGrammarPart edges)
+            mkNontsPat types = map (\(t, v) -> sigP v (do return t)) . zip types . nontsPatVars
+            nontsPatVars     = map (varP . type2Nonts . fst)
+
+envSignature :: [Con] -> [Type] -> Q Type
+envSignature cs types = if null (consVars cs) 
+                            then envSignature' 
+                            else forallT (consVars cs) (return $ mkContext cs) envSignature'
+    where
+        consVars      :: [Con] -> [Name]
+        consVars      = map (\(VarT n) -> n) . uniqueVars . consArgsTypes
+
+        envSignature' :: Q Type
+        envSignature' = foldl1' appT [conT ''Env, conT ''DGram, tupleTypes types, tupleTypes types]
+
+        -- Make a nested tuple of the types 
+        tupleTypes    :: [Type] -> Q Type
+        tupleTypes    = foldr' ((\x xs -> appT (appT (tupleT 2) xs) x)) (conT ''()) . map return
+
+
+--  If there are args, see if we need instances (from needed)
+--  Create all needed instances
+--  Also, if there's still a var, create a consG for that
+--  Return a list of tuples of the name of an instance and the instance itself
+createInstances :: [(Name, [[Type]])] -> [(Name, [Type])] -> (Name, [(Name, [[Type]])]) -> Q [((Name, Type), ExpQ)]
+createInstances needed strongEdges (typeName, edges) = do
+    (UserD _ args cs) <- getUserType typeName
+    let instancesNeeded   = maybe [map VarT args] id $ Prelude.lookup typeName needed
+    return $  mkInstances      instancesNeeded
+           ++ mkArgInstances   instancesNeeded
+           ++ mkNonBGInstances typeName strongEdges
+    where
+        mkConsG :: Type -> ((Name, Type), ExpQ)
+        mkConsG typ = ((instName typeName typ, typ), [|consG grammar|])
+
+        mkInstances    = map (createInstance (typeName, edges) (getEdges typeName strongEdges))
+        mkArgInstances = map mkConsG . filter isVarT . concat
+
+        mkNonBGInstances typeName = map mkConsG . getEdges typeName
+
+
+createInstance :: (Name, [(Name, [[Type]])]) -> [Type] -> [Type] -> ((Name, Type), ExpQ)
+createInstance (typeName, edges) strongEdges inst = ((iName, iType), [|consD $(appsE $ (varE $ type2Nonts typeName) : (selfArgs ++ strongEdgeArgs ++ nonBGStrongEdges)) |])
+    where iName            = nameArgs (type2TopRef typeName) inst
+          iType            = foldl1' AppT (ConT typeName : inst)
+          selfArgs         = (varE iName) : (map (varE . instName typeName) inst)
+          strongEdgeArgs   = concatMap refEdge edges
+          nonBGStrongEdges = map (varE . instName typeName) strongEdges
+
+instName :: Name -> Type -> Name
+instName top (VarT n)     = var2TopRef top n 
+instName _ (ConT n)       = type2TopRef n
+instName _ app@(AppT _ _) = app2TopRef $ unrollApp app
+
+
+mkNontsType :: [(Name, [Type])] -> (Name, [(Name, [[Type]])]) -> Q Type
+mkNontsType strongEdges (typeName, edges) = do
+    (UserD _ args _) <- getUserType typeName
+    let envName    = mkName "env"
+        env        = VarT envName
+        ref        = ConT ''Ref
+        argsType   = map VarT args
+        topType    = foldl' AppT (ConT typeName) argsType
+        resultType = AppT (AppT (ConT ''DLNontDefs) topType) env
+        refTo      = (topType : argsType) ++ concatMap edgeType edges ++ getEdges typeName strongEdges
+        refs       = map (\r -> AppT (AppT ref r) env) refTo
+        nontsType  = foldr' (\r rs -> AppT (AppT ArrowT r) rs) resultType refs
+    return $ ForallT (envName:args) [] nontsType
+
+edgeType :: (Name, [[Type]]) -> [Type]
+edgeType (con, argss) = map (foldl' AppT (ConT con)) argss
+
+mkGrammarPart :: [(Name, [Type])] -> (Name, [(Name, [[Type]])]) -> Q Exp
+mkGrammarPart strongEdges (typeName, edges) = do
+    (UserD _ args cons) <- getUserType typeName
+    let selfArgsNames         = (type2Ref typeName) : (map (var2Ref typeName) args) 
+        strongEdgeNames       = concatMap nameEdge edges
+        -- Strong edges that are not part of the binding group
+        nonBGStrongEdgeNames  = map getTypeName $ getEdges typeName strongEdges
+    lamE (map varP (selfArgsNames ++ strongEdgeNames ++ nonBGStrongEdgeNames)) (conProds cons typeName)
+    where
+        getTypeName (ConT name)  = type2Ref name
+        getTypeName a@(AppT _ _) = app2Ref (unrollApp a) 
+        -- TODO Incomplete: TupleT, ListT, etc...
+
+
+refEdge :: (Name, [[Type]]) -> [ExpQ]
+refEdge (con, argss) = map (varE . nameArgs baseName) argss
+    where baseName = type2TopRef con
+
+nameEdge :: (Name, [[Type]]) -> [Name]
+nameEdge (con, argss) = map (nameArgs baseName) argss
+    where baseName = type2Ref con
+
+--  TODO: Extend this for 'AppT' and clean up
+nameArgs :: Name -> [Type] -> Name
+nameArgs baseName []        = baseName
+nameArgs baseName ((ConT name):types) = nameArgs (mkName $ nameBase baseName ++ "'" ++ nameBase name) types
+nameArgs baseName ((VarT name):types) = nameArgs (mkName $ nameBase baseName ++ "'" ++ nameBase name) types
+
+--  TODO: Simplification, not finished, doesn't support AppT at the moment
+getNeededInstances :: (Name, [[Type]]) -> [(Name, [Type])] 
+getNeededInstances (top, argss) = concatMap (\args -> (top,args): map (\arg -> (typeName arg, [])) args) argss
+    where typeName (ConT n) = n --  Break with a pattern match failure
+
+linkRefs :: Int -> [ExpQ]
+linkRefs x = linkRefs' (x-1) [[|Zero|]] --  Minus one is for the top type, works always
+    where linkRefs' 0  done       = reverse done
+          linkRefs' x' l@(last:_) = linkRefs' (x' - 1) ((appE [|Suc|] last):l)
+
+type PrecProd = Map Int [ExpQ]
+
+conProds :: [Con] -> Name -> Q Exp
+conProds cs top = do
+    prods    <- foldM (insertCon top) Map.empty cs
+    --  Add the parenthesis production
+    prods'   <- insertCon' 10 (parensProd top) prods 
+    let prodList = map (\(prec, nonts) -> 
+                        tupE [ [|DRef ($(varE $ type2Ref top), prec)|]
+                             , appE [|DPS|] (listE nonts)
+                             ]
+                       )
+                   (Map.toList prods')
+    appE [|DLNontDefs|] $ listE prodList
+
+parensProd :: Name -> Q Exp
+parensProd top = [| dTerm "(" .#. (dNont ($(varE $ type2Ref top), 0)) .#. dTerm ")" .#. dEnd parenT |]
+
+getTypeRef :: Name -> Int -> StrictType -> Q Exp
+getTypeRef top p (_,t) = [| dNont ($(varE (refTo top t)), p) |]
+    where  refTo top' (VarT n)           = var2Ref top' n
+           refTo _    (ConT n)           = type2Ref n
+           refTo top' app@(AppT _ _)     = appOrType2Ref top' $ unrollApp app 
+           appOrType2Ref cur app@((ConT con):_) | cur == con   = type2Ref cur --  TODO: Is this always true?
+                                                | otherwise    = app2Ref app
+           --  TODO Incomplete?
+
+--  TODO: first argument doesn't have to be a con!
+app2Ref :: [Type] -> Name
+app2Ref ((ConT con):args) = nameArgs (type2Ref con) args 
+
+app2TopRef :: [Type] -> Name
+app2TopRef ((ConT con):args) = nameArgs (type2TopRef con) args 
+
+--  TODO: Nice for readability, but should be cleaned up
+type2Ref :: Name -> Name
+type2Ref = type2Ref' "_r_"
+
+type2Ref' :: String -> Name -> Name
+type2Ref' prefix t = mkName $ prefix ++ nameBase t
+
+var2Ref :: Name -> Name -> Name
+var2Ref = var2Ref' "_r_"
+
+var2Ref' :: String -> Name -> Name -> Name
+var2Ref' prefix t v = mkName $ prefix ++ nameBase t ++ "_" ++ nameBase v
+
+type2Nonts :: Name -> Name
+type2Nonts = type2Ref' "_nonts_"
+
+var2TopRef :: Name -> Name -> Name
+var2TopRef = var2Ref' "_t_"
+
+type2TopRef :: Name -> Name
+type2TopRef = type2Ref' "_t_"
+
+nameStringE :: Name -> Q Exp
+nameStringE = stringE . nameBase
+
+insertCon :: Name -> PrecProd -> Con -> Q PrecProd
+insertCon top pp (NormalC name args) = do
+    insertCon' 10 (foldr1 appE (
+        [ [| (.#.) $ dTerm $(nameStringE name) |] ]     ++
+        ( map (appE [|(.#.)|] . (getTypeRef top 0)) args )  ++
+        [ [| dEnd $(consExp name (length args)) |] ]
+        )) pp 
+
+insertCon top pp (InfixC argl name argr)  = do
+    (prec, precl, precr) <- getPrec name
+    let  refl  = getTypeRef top precl argl
+         refr  = getTypeRef top precr argr
+    insertCon' prec (infixProd refl (nameBase name) refr (conE name)) pp
+
+insertCon _ _ _ = undefined --  TODO
+
+
+infixProd :: ExpQ -> String -> ExpQ -> ExpQ -> Q Exp
+infixProd argl term argr op = 
+    [|  $argl .#. dTerm term .#. $argr .#. 
+        dEnd (\e1 _ e2 -> $(appsE [op, [|e2|], [|e1|]])) 
+    |]
+
+getPrec :: Name -> Q (Int, Int, Int)
+getPrec name = do
+    (DataConI _ _ _ (Fixity f fd)) <- reify name
+    return (f, (f + fLeft fd), (f + fRight fd))
+    where
+        fLeft   InfixL  = 0
+        fLeft   InfixR  = 1
+        fRight  InfixR  = 0
+        fRight  InfixL  = 1
+
+insertCon' :: Int -> ExpQ -> PrecProd -> Q PrecProd
+insertCon' i e pp = return $ Map.insertWith (flip (++)) i [e] pp
+
+consExp :: Name -> Int -> Q Exp
+consExp name times = do 
+    let names = map (\x -> mkName $ "arg" ++ show x) [1..times]
+    lamE (map varP names ++ [wildP]) (appsE $ (conE name):(map varE (reverse names)))
diff --git a/src/Text/GRead/Derive/BindingGroup.hs b/src/Text/GRead/Derive/BindingGroup.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/GRead/Derive/BindingGroup.hs
@@ -0,0 +1,242 @@
+{-# LANGUAGE TemplateHaskell #-}
+
+{-|
+    Module used internally by the "Derive" module for binding group calculation.
+ -}
+
+module Text.GRead.Derive.BindingGroup (
+    -- * Binding group
+      BindingGroup
+    , getBindingGroup
+    , showBindingGroup
+    -- * Template Haskell helpers
+    , UserType(..)
+    , getUserType
+    , unrollApp
+    ) where
+
+import Language.Haskell.TH.Syntax
+
+import           Data.List (nub, intersect)
+import           Data.Maybe (fromJust)
+import qualified Data.Map as M
+
+import qualified Data.Graph.Inductive.Graph as G
+import qualified Data.Graph.Inductive.Tree as G
+import qualified Data.Graph.Inductive.Query.BFS as G
+import qualified Data.Graph.Inductive.NodeMap as G
+
+import Control.Monad (foldM)
+
+-- | Uniform representation of 'data' and 'newtype'
+data UserType  = UserD Name [Name] [Con]
+
+-- | Edges can be Strong (direct) or Weak (through variable)
+data EdgeType  = Strong [Type] | Weak [Type] deriving (Show, Eq)
+
+-- | Graph of our type dependencies
+type TypeGraph   = G.Gr      Name EdgeType
+type TypeContext = G.Context Name EdgeType
+
+-- | The next edge, parent and type
+type NextEdge  = (EdgeType, G.Node)
+
+-- | Map for looking up vars
+type VarMap    = M.Map Name Type
+
+-- This will be our 'inherited' attributes, as we walk the tree of types
+-- type InheritState = (NextEdge, VarMap, TypeGraph)
+data InheritState = IS { nextEdge  :: NextEdge
+                       , varMap    :: VarMap
+                       , typeGraph :: TypeGraph
+                       , bindings  :: M.Map Name VarMap -- Also used as a loop-check
+                       -- Actually synthesized, but here to enable tail recursion
+                       , nodeMap   :: G.NodeMap Name
+                       , contexts  :: [TypeContext] 
+                       }
+
+type SynthesizedState = (G.NodeMap Name, [TypeContext])
+
+-- | Mapping from types to the list of types (with specific constructor instantiations, the '[[Type]]') in the same binding group.
+type BindingGroup = [(Name, [(Name, [[Type]])])]
+
+startState :: Name -> InheritState
+startState firstType = 
+    let (firstNode, firstNodemap) = G.mkNode G.new firstType
+        firstContext              = ([], fst firstNode, snd firstNode, []) 
+    in IS { nextEdge  = (Strong [], fst firstNode)
+          , varMap    = M.empty
+          , bindings  = M.singleton firstType M.empty
+          , typeGraph = firstContext G.& G.empty
+          , nodeMap   = firstNodemap
+          , contexts  = [firstContext]
+          }
+
+returnState :: InheritState -> Q SynthesizedState
+returnState state = return (nodeMap state, contexts state)
+
+-- Show functions for console debugging
+showBindingGroup :: Name -> Q Exp
+showBindingGroup name = do
+    bgroup <- getBindingGroup name
+    let bgroup' = map show bgroup
+    [|bgroup'|]
+
+showTypeGraph :: Name -> Q Exp
+showTypeGraph name = do
+    tgraph <- getTypeGraph name
+    let tgraph' = show tgraph
+    [|tgraph'|]
+
+-- | Find cyclic type dependencies (binding groups)
+getBindingGroup :: Name -> Q BindingGroup
+getBindingGroup name = do
+    typegr <- getTypeGraph name
+    -- Broken in 'labeled' pieces to make it better readable
+    let loopClosers  = G.pre typegr 0
+        loops        = map (\x -> G.esp 0 x typegr) loopClosers
+        bindingGroup = nub $ concat loops
+        -- Create the bindings first, we'll look them up when constructing the final binding group.
+        bindings     = typeBindings typegr bindingGroup
+    return $ map (\x -> (typeName typegr x, outgoingBindings typegr x bindings)) bindingGroup
+    -- TODO Do we need to take into account the case that the 'top' type takes arguments and add a variable binding?
+
+typeName :: TypeGraph -> G.Node -> Name
+typeName typegr node = fromJust $ G.lab typegr node
+
+typeBindings :: TypeGraph -> [G.Node] -> M.Map G.Node [[Type]]
+typeBindings typegr bindingGroup = M.fromList $ map (\x -> (x, bindings x)) bindingGroup
+    where bindings x = nub $ map (getBindings . thd) $ G.inn typegr x
+
+-- Only strong edges
+outgoingBindings :: TypeGraph -> G.Node -> M.Map G.Node [[Type]] -> [(Name, [[Type]])]
+outgoingBindings typegr node bindings = map (\x -> (typeName typegr x, maybe (error $ show x) id $ M.lookup x bindings)) edgesOut
+    where edgesOut = filter ((/=) node) $ intersect (M.keys bindings) $ map getTargetNode $ filter strongEdge $ nub $ G.out typegr node
+          strongEdge (_, _, Strong _) = True
+          strongEdge _                = False
+          getTargetNode (_, n, _)     = n
+
+-- TODO This suggests a better (wrapping) type
+getBindings :: EdgeType -> [Type]
+getBindings (Strong types) = types
+getBindings (Weak   types) = types
+
+-- Build the typegraph
+getTypeGraph :: Name -> Q TypeGraph
+getTypeGraph name = do
+    utype@(UserD uname _ _) <- getUserType name
+    (_, contexts')          <- extendGraphType (startState uname) utype
+    return $ mkGraph' contexts'
+
+mkGraph' :: (Eq a, Eq b) => [G.Context a b] -> G.Gr a b
+mkGraph' contexts = 
+    let nodes = nub $ map G.labNode' contexts
+        edges = concatMap (\x -> (G.inn' x) ++ (G.out' x)) contexts -- Don't nub, do that where it's really needed
+    in G.mkGraph nodes edges
+
+-- | Get a unified type for 'data' and 'newtype'
+getUserType :: Name -> Q UserType
+getUserType name = do
+    info <- reify name
+    case info of
+        TyConI d -> case d of
+            (DataD     _ uname args cs  _)  -> return $ UserD uname args cs 
+            (NewtypeD  _ uname args c   _)  -> return $ UserD uname args [c]
+            _                               -> scopeError
+        _ -> scopeError
+    where scopeError = error $ "Can only be used on algebraic datatypes (which " ++ (show name) ++ " isn't)" 
+
+extendGraphType :: InheritState -> UserType -> Q SynthesizedState
+extendGraphType state (UserD _ _ cons) = do
+    startState <- returnState state
+    foldM (\(nodeMap', contexts') utype -> 
+              extendGraph (state { contexts = contexts', nodeMap = nodeMap' }) utype) 
+          startState
+          (getCtx cons) 
+
+-- Context of a data type, based on the arguments in it's constructors.  Not the context of a graph.
+getCtx :: [Con] -> [Type] 
+getCtx []                            = []
+getCtx ((NormalC        _ args) :cs) = (map snd args) ++ (getCtx cs)
+getCtx ((InfixC   argl  _ argr) :cs) = (snd argl) : ((snd argr) : (getCtx cs))
+getCtx ((RecC           _ args) :cs) = (map thd args) ++ (getCtx cs) 
+-- Not exhaustive: missing ForallC
+
+thd :: (a, b, c) -> c
+thd (_, _, c) = c
+
+extendGraph :: InheritState -> Type -> Q SynthesizedState
+extendGraph state nextType = case nextType of
+    VarT varname             -> extendGraphVar state varname
+    ConT conname             -> extendGraphCon state conname
+    app@(AppT _ _)           -> extendGraphApp state app 
+    _                        -> error $ "Couldn't match: " ++ (show nextType)
+
+extendGraphVar :: InheritState -> Name -> Q SynthesizedState
+extendGraphVar state name = do
+    case M.lookup name (varMap state) of
+        Just (VarT _) -> returnState state
+        Nothing       -> returnState state -- From toplevel
+        -- Follow the var, but make the link weak
+        Just vartype  -> extendGraph (state { nextEdge = (Weak [], snd $ nextEdge state) }) vartype
+
+extendGraphCon :: InheritState -> Name -> Q SynthesizedState
+extendGraphCon state name = do
+    newState               <- insNode state name
+    utype@(UserD _ args _) <- getUserType name
+    case M.lookup name (bindings state) of
+        Just oldVarMap | oldVarMap == varMap state || args == [] -> returnState newState
+        _                                                        -> do
+            extendGraphType newState { bindings = M.insert name (varMap state) (bindings state) } utype
+
+insNode :: InheritState -> Name -> Q InheritState
+insNode state name = do
+    (UserD _ args _) <- getUserType name
+    let ((nodeNr, _), newNodeMap) = G.mkNode (nodeMap state) name
+        (edgeType, parent)        = nextEdge state    
+        nextEdge'                 = (mkNextEdgeType edgeType args (varMap state), parent)
+        newContexts               = ([nextEdge'], nodeNr, name, []) : (contexts state)
+    return $ state { nextEdge    = (Strong [], nodeNr)
+                   , typeGraph   = mkGraph' newContexts
+                   , contexts    = newContexts
+                   , nodeMap     = newNodeMap
+                   }
+
+mkNextEdgeType :: EdgeType -> [Name] -> VarMap -> EdgeType
+mkNextEdgeType (Strong _) args vm = Strong $ mkNextEdgeType' args vm []
+mkNextEdgeType (Weak   _) args vm = Weak   $ mkNextEdgeType' args vm []
+
+mkNextEdgeType' :: [Name] -> VarMap -> [Type] -> [Type]
+mkNextEdgeType' []       _  types = types
+mkNextEdgeType' (a:args) vm types = case M.lookup a vm of
+    Nothing -> mkNextEdgeType' args vm ((VarT a):types)
+    Just t  -> mkNextEdgeType' args vm (t       :types)
+
+extendGraphApp :: InheritState -> Type -> Q SynthesizedState
+extendGraphApp state app = do
+    let (app':appargs) = replaceVars (unrollApp app) (varMap state)
+    varmap' <- extendVarMap app' appargs (varMap state)
+    extendGraph (state { varMap = varmap' }) app'
+
+extendVarMap :: Type -> [Type] -> VarMap -> Q VarMap
+extendVarMap utype appargs varmap =
+    case utype of
+        ConT uname -> do
+            (UserD _ args _) <- getUserType uname
+            return $ M.union (M.fromList $ zip args appargs) varmap
+        _ -> return varmap
+
+-- | Get the types of a type application
+unrollApp :: Type -> [Type]
+unrollApp app = unrollApp' app []
+    where unrollApp' :: Type -> [Type] -> [Type]
+          unrollApp' (AppT sub@(AppT _ _) arg) args = unrollApp' sub (arg:args)
+          unrollApp' (AppT top arg)            args = top:(arg:args)
+          -- Not exhaustive: missing ArrowT, ContT, ForallT, ListT, ...
+
+replaceVars :: [Type] -> VarMap -> [Type]
+replaceVars []              _  = []
+replaceVars (t@(VarT v):ts) vm = case M.lookup v vm of
+                                    Nothing -> t  : replaceVars ts vm
+                                    Just t' -> t' : replaceVars ts vm
+replaceVars (t:ts)          vm = t : replaceVars ts vm
diff --git a/src/Text/GRead/Grammar.hs b/src/Text/GRead/Grammar.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/GRead/Grammar.hs
@@ -0,0 +1,212 @@
+{-# OPTIONS -fglasgow-exts #-}
+
+{- | 
+
+    Representation of Data Type Grammars.
+
+-}
+module Text.GRead.Grammar (
+                       -- * Class Gram
+                       Gram(..),
+ 
+                       -- * Typed Grammar Representations for Data Types
+
+                       -- ** Types
+                       DGrammar(..), DGram(..), DRef(..), DLNontDefs(..),
+                       DProductions(..), DProd(..), DSymbol(..), 
+ 
+                       -- ** Smart Constructors
+                       ( .#. ), consG, consD, dNont, dTerm, dEnd, parenT,
+
+                       -- * Typed Grammar Representations
+
+                       -- ** Types
+                       Grammar(..), Productions(..), Prod(..), 
+                       Symbol(..), Token(..),
+
+                       -- ** Smart Constructors
+                       ext, ( .*. ),
+
+                       -- ** Utils
+                       matchSym, append
+                     ) where
+
+import Language.TTTAS (Env(..), Ref(..), Equal(..), match)
+
+-- |
+--
+-- Class of data types with typed grammar representation. It has to be
+-- instantiated in order to use the function 'Text.GRead.gread'.  
+--
+-- Instances can be derived automatically using the functions defined
+-- in the module "Text.GRead.Derive".
+-- 
+-- For example, given the declarations
+--
+-- > infixl 5 :<:
+-- > infixr 6 :>:, :*:
+-- > 
+-- > data T1  =  T1 :<: T1
+-- >          |  T1 :>: T1
+-- >          |  C1
+-- > 
+-- > data T2 a  =  a :*: T2 a
+-- >            |  C2
+--
+-- the instances of 'Gram' can be
+--
+-- > _0 = Zero
+-- > _1 = Suc _0
+-- > 
+-- > instance Gram T1 where
+-- >  grammar = DGrammar   _0 envT1
+-- > 
+-- > envT1 :: Env DGram ((),T1) ((),T1) 
+-- > envT1 =  consD (nonts _0) Empty 
+-- >      where
+-- >       nonts _T1 = DLNontDefs
+-- >        [  (  DRef (_T1, 5) 
+-- >           ,  DPS  [  dNont (_T1, 5) .#. dTerm ":<:" .#.
+-- >                      dNont (_T1, 6) .#. dEnd infixL ]
+-- >           )
+-- >        ,  (  DRef (_T1, 6) 
+-- >           ,  DPS  [  dNont (_T1, 7) .#. dTerm ":>:" .#.
+-- >                      dNont (_T1, 6) .#. dEnd infixR ] 
+-- >           ) 
+-- >        ,  (  DRef (_T1,10) 
+-- >           ,  DPS  [  dTerm "C1"   .#. dEnd (const C1)
+-- >                   ,  dTerm "(" .#. dNont (_T1,0) .#. 
+-- >                      dTerm ")" .#. dEnd parenT ] 
+-- >           )
+-- >        ]
+-- >       infixL e1 _ e2   = e2 :<: e1
+-- >       infixR e1 _ e2   = e2 :>: e1 
+-- > 
+-- > instance Gram a => Gram (T2 a) where
+-- >  grammar = DGrammar   _0  envT2 
+-- > 
+-- > envT2 :: (Gram a) => Env DGram  (((),a),T2 a)
+-- >                                 (((),a),T2 a)
+-- > envT2 =  consD (nonts  _0 _1) $ 
+-- >          consG grammar Empty
+-- >      where
+-- >       nonts _T2 _A = DLNontDefs
+-- >        [  (  DRef (_T2, 6)
+-- >           ,  DPS  [  dNont (_A,   7)  .#. dTerm ":*:" .#. 
+-- >                      dNont (_T2,  7)  .#. dEnd infixT ] 
+-- >           )
+-- >        ,  (  DRef (_T2,10) 
+-- >           ,  DPS  [  dTerm "C2"   .#. dEnd (const C2)
+-- >                   ,  dTerm "("    .#. dNont (_T2,0) .#. 
+-- >                      dTerm ")"    .#. dEnd parenT ] 
+-- >           )
+-- >        ]
+-- >       infixP   e1 _ e2  = e2 :+: e1
+-- >       infixT   e1 _ e2  = e2 :*: e1 
+--
+-- In case of mutually recursive datatypes, their definitions have
+-- to be tupled together into a single environment.
+
+class Gram a where
+ -- | The function 'grammar' returns the grammar representation of
+ --   the data type.
+ grammar :: DGrammar a
+
+-- | Data type describing grammatical structures of data types,
+--   including information about precedences. The type @DGrammar a@
+--   describes the grammar of the data type @a@.
+data DGrammar a 
+        -- | A grammar consists of an environment ('Env') with the
+        --   defined non-terminals and a reference ('Ref') to the
+        --   /main non-terminal/ in the environment.
+        = forall env. DGrammar  (Ref a env) 
+                                (Env DGram env env)
+ 
+data DGram a env  =  DGD (DLNontDefs a env) 
+                  |  DGG (DGrammar a)
+newtype DRef a env = DRef (Ref a env, Int)
+newtype DLNontDefs a env 
+            = DLNontDefs [(DRef a env, DProductions a env)]
+newtype DProductions a env 
+            = DPS { unDPS :: [DProd a env] }
+ 
+data DProd a env where
+  DSeq    :: DSymbol b env  -> DProd (b->a) env 
+                            -> DProd a env
+  DEnd    :: a              -> DProd a env
+ 
+data DSymbol a env where
+  DNont  :: DRef a env  -> DSymbol a env
+  DTerm  :: Token       -> DSymbol Token env
+
+infixr 5 .#.
+
+( .#. ) ::  DSymbol b env -> DProd (b -> a) env -> DProd a env
+( .#. )                  = DSeq
+
+consG :: DGrammar a -> Env DGram use def' -> Env DGram use (def', a)
+consG   g es             = Ext    es (DGG g)
+
+consD :: DLNontDefs a env -> Env DGram env def' -> Env DGram env (def', a)
+consD   g es             = Ext    es (DGD g)
+
+dNont ::  (Ref a env, Int) -> DSymbol a env
+dNont   nt               = DNont  (DRef nt)
+
+dTerm ::  [Char] -> DSymbol Token env
+dTerm   t  | t == "("    = DTerm  Open
+           | t == ")"    = DTerm  Close
+           | otherwise   = DTerm  (Keyw t)
+
+dEnd ::  a -> DProd a env
+dEnd    f                = DEnd   f
+
+parenT ::  t -> t1 -> t2 -> t1
+parenT  _ e _            = e
+
+
+
+data Grammar a  
+  = forall env . Grammar  (Ref a env)  
+                          (Env Productions env env)
+
+newtype Productions a env 
+  = PS {unPS :: [Prod a env]}
+
+data Prod a env where
+      Seq   ::  Symbol    b        env  ->  Prod   (  b -> a)  env  
+                                        ->  Prod      a        env
+      End   ::  a                       ->  Prod      a        env
+
+data Symbol a env where
+  Nont :: Ref a env ->  Symbol  a       env
+  Term :: Token     ->  Symbol  Token   env
+
+data Token = Keyw String
+           | Open
+           | Close
+         deriving (Ord, Eq)
+
+
+infixr 5 `ext` , .*.
+
+ext :: Env Productions env def' -> [Prod a env]
+    -> Env Productions env (def', a)
+ext g prods  = Ext g (PS prods)
+
+( .*. ) ::  Symbol b env -> Prod (b -> a) env -> Prod a env
+( .*. )      = Seq
+
+matchSym  ::  Symbol a env -> Symbol b env 
+          ->  Maybe (Equal a b)
+matchSym (Nont x)  (Nont y)             = match x y
+matchSym (Term x)  (Term y) | x == y    = Just Eq
+matchSym _         _                    = Nothing
+
+
+append  :: (a -> b -> c) -> Prod a env -> Symbol b env 
+        -> Prod c env
+append g (End f     )  s  =  Seq s  (End (g f))
+append g (Seq t ts  )  s  
+  =  Seq t (append  (\b c d -> g (b d) c) ts s)
+
diff --git a/src/Text/GRead/Transformations/GramTrafo.hs b/src/Text/GRead/Transformations/GramTrafo.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/GRead/Transformations/GramTrafo.hs
@@ -0,0 +1,52 @@
+{-# OPTIONS -fglasgow-exts #-}
+
+module Text.GRead.Transformations.GramTrafo where
+
+import Language.TTTAS
+import Text.GRead.Grammar
+
+newtype MapA_X env a env'
+  = MapA_X (forall x. Symbol x env -> Maybe (Ref (x -> a) env'))
+
+emptyMap :: MapA_X env a env'
+emptyMap  = MapA_X (const Nothing)
+
+extendMap :: Symbol x env -> MapA_X env a env'
+          -> MapA_X env a (env',x->a)
+extendMap  x (MapA_X m) 
+       = MapA_X  (\s -> case matchSym s x of
+                                     Just Eq -> Just Zero
+                                     Nothing -> fmap Suc (m s)
+                      )
+
+
+type GramTrafo env a = Trafo (MapA_X env a) Productions
+
+
+initMap :: GramTrafo env a s c d
+        -> Trafo Unit Productions s c d
+initMap (Trafo st) 
+        = Trafo (\_ -> case st emptyMap of
+                            TrafoE _ f -> TrafoE Unit f
+                )
+
+newNontR ::  forall x env s a 
+         .   Symbol x env 
+         ->  GramTrafo env a s (Productions (x->a) s) (Ref (x->a) s)
+newNontR x = Trafo $ \m -> extEnv (extendMap x m)
+
+
+newtype Mapping old new 
+           = Mapping (Env Ref new old) 
+
+map2trans :: Mapping env s -> T env s
+map2trans (Mapping env) 
+     = T (\r -> (lookupEnv r env))
+
+mapProd  :: T env1 env2 -> Prod a env1 -> Prod a env2
+mapProd _ (End x)           = End x
+mapProd t (Seq (Nont x) r)  = Seq (Nont (unT t x)) 
+                                  (mapProd t r)
+mapProd t (Seq (Term x) r)  = Seq (Term x) 
+                                  (mapProd t r)
+
diff --git a/src/Text/GRead/Transformations/Group.hs b/src/Text/GRead/Transformations/Group.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/GRead/Transformations/Group.hs
@@ -0,0 +1,96 @@
+{-# OPTIONS -fglasgow-exts -XArrows #-}
+
+module Text.GRead.Transformations.Group where
+
+import Language.TTTAS
+import Text.GRead.Grammar
+import Control.Arrow
+
+
+newtype DT env1 env2  
+ = DT { unDT :: forall a . DRef a env1 -> Ref a env2 }
+
+mapDP2Prod  :: DT env1 env2 -> DProd a env1 
+            -> Prod a env2
+
+mapDP2Prod _ (DEnd x)    = End x
+mapDP2Prod t (DSeq (DNont x) r)  
+                         = Seq  (Nont (unDT t x)) 
+                                (mapDP2Prod t r)
+mapDP2Prod t (DSeq (DTerm x) r)  
+                         = Seq  (Term x) 
+                                (mapDP2Prod t r)
+
+
+type GTrafo = Trafo Unit Productions
+
+dp2prod  :: DProd a env -> GTrafo s (DT env s) (Prod a s)
+dp2prod p = arr ( \env2s -> mapDP2Prod env2s p )
+
+ld2nt  :: (DRef a env, DProductions a env)
+       -> GTrafo s (DT env s) (DRef a s) 
+ 
+ld2nt (DRef (rnt,i),DPS lp) 
+        =  proc env2s ->
+            do  ps <- sequenceA (map dp2prod lp) -< env2s
+                (PS nl) <- mkNxtLev -< env2s
+                r  <- newSRef -< PS $ nl++ps
+                returnA -< DRef (r,i)
+    where
+        mkNxtLev  = arr $ \t -> PS $  
+              (if (i<10) 
+               then  [Seq  (Nont $ unDT  t $ 
+                                         DRef (rnt,i+1)) 
+                           (End id)]
+               else  []) 
+
+newtype ListDR a s    = ListDR { unListDR :: [DRef a s] }
+
+newtype DMapping o n  = DMapping { unDMapping :: Env ListDR n o }
+
+dmap2trans :: DMapping env s -> DT env s
+dmap2trans (DMapping env) 
+  = DT (\  (DRef (r,i)) 
+           -> case  (lookupEnv r env) of
+                    ListDR rs -> (plookup i rs))
+
+plookup :: Int -> [DRef a s] -> Ref a s
+plookup _ []            = error "Wrong Grammar!!"
+plookup i ((DRef (r,p)):drs)
+           | i <= p     = r
+           | otherwise  = plookup i drs   
+
+
+
+group :: DGrammar a -> Grammar a
+group gram 
+    = let trafo =  proc x -> 
+                    do (ListDR rs) <- (gGrammar gram) -< x
+                       returnA -< plookup 0 rs 
+      in  case runTrafo trafo Unit undefined of 
+               Result _ r grm -> Grammar r grm
+
+gGrammar  :: DGrammar a 
+          -> GTrafo s t (ListDR a s)
+gGrammar (DGrammar r gram) = proc _ ->
+        mdo let env_s = dmap2trans menv_s
+            menv_s <- gDGrams gram -< env_s
+            returnA -< lookupEnv r (unDMapping menv_s)
+
+
+gDGrams  :: Env DGram env env' 
+         -> GTrafo  s (DT env s)  (DMapping env' s)
+  
+gDGrams Empty = arr (const (DMapping Empty)) 
+  
+gDGrams (Ext ps (DGG gram)) 
+    = proc env_s ->
+        do refs <- gGrammar gram -< env_s
+           ms   <- gDGrams ps -< env_s
+           returnA -< DMapping $ Ext (unDMapping ms) refs 
+gDGrams (Ext ps (DGD (DLNontDefs nonts))) 
+    = proc env_s ->
+        do r  <- sequenceA (map ld2nt nonts) -< env_s
+           ms <- gDGrams ps -< env_s
+           returnA -< DMapping $ Ext (unDMapping ms) (ListDR r)
+
diff --git a/src/Text/GRead/Transformations/LeftCorner.hs b/src/Text/GRead/Transformations/LeftCorner.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/GRead/Transformations/LeftCorner.hs
@@ -0,0 +1,109 @@
+{-# OPTIONS -fglasgow-exts -XArrows #-}
+
+module Text.GRead.Transformations.LeftCorner (leftcorner) where
+
+import Language.TTTAS
+import Text.GRead.Grammar
+import Text.GRead.Transformations.GramTrafo
+import Control.Arrow
+
+
+leftcorner :: forall a . Grammar a -> Grammar a
+leftcorner (Grammar start productions)
+      = case runTrafo (lctrafo productions) Unit () of
+            Result _ (T tt) gram -> 
+                 Grammar (tt start) gram
+
+lctrafo :: Env Productions env env 
+        -> Trafo Unit Productions s () (T env s)
+lctrafo productions = proc _ ->
+            mdo  let tenv_s = map2trans menv_s
+                 menv_s <- (rules1 productions productions) -< tenv_s
+                 returnA -< tenv_s
+
+
+rules1  ::  Env Productions env env
+        ->  Env Productions env env' 
+        ->  Trafo  Unit Productions s (T env s) 
+                                      (Mapping env' s)
+rules1 _ Empty          
+     = proc _ ->
+        returnA -< Mapping Empty  
+
+rules1 productions (Ext ps (PS prods)) 
+     = proc tenv_s ->
+        do  p <- app_rule1 productions prods -< tenv_s
+            r <- newSRef -< p   
+            Mapping e <- rules1 productions ps -< tenv_s
+            returnA -< Mapping (Ext e r)
+ 
+app_rule1 :: forall env a s. Env Productions env env
+          -> [Prod a env]
+          -> Trafo Unit Productions s (T env s) (Productions a s)
+app_rule1 productions prods =  initMap 
+          ( proc tenv_s -> 
+                do pss <- sequenceA  (map  (rule1 productions) prods) -< tenv_s 
+                   returnA -< PS (concatMap unPS pss)
+          )
+
+rule1  :: Env Productions env env -> Prod a env 
+       -> GramTrafo env a s (T env s) (Productions a s)
+rule1 gram (Seq x beta) 
+     = proc tenv_s ->
+        do  insert gram x -< (tenv_s, mapProd tenv_s beta)
+                      
+
+rule2  :: Env Productions env env 
+       -> Symbol x env 
+       -> GramTrafo env a s (T env s, Ref (x -> a) s) 
+                            (Productions a s)
+rule2 _    (Term a) 
+     = proc (_, a_x) ->
+        do  returnA -< PS [rule2a a a_x]
+rule2 gram (Nont b) 
+     = case lookupEnv b gram of
+          PS ps ->  proc (tenv_s, a_x) ->
+                      do pss <- sequenceA  
+                                (map  (rule2b gram) ps) -< (tenv_s, a_x)
+                         returnA -< PS (concatMap unPS pss)
+
+
+rule2a :: Token -> Ref (Token -> a) s -> Prod a s
+rule2a a refA_a
+     =  Term a .*. Nont refA_a .*. End ($) 
+
+rule2b  :: Env Productions env env 
+        -> Prod b env 
+        -> GramTrafo env a s (T env s, Ref (b -> a) s) 
+                             (Productions a s)
+rule2b gram (Seq x beta) 
+     = proc (tenv_s, a_b) ->
+         do insert gram x -< (tenv_s, append  (flip (.)) 
+                                              (mapProd tenv_s beta) 
+                                              (Nont a_b))
+
+insert ::  forall env s a x
+       .   Env Productions env env 
+       ->  Symbol x env
+       ->  GramTrafo env a s  (T env s, Prod (x->a) s)
+                              (Productions a s)
+insert gram x = 
+     Trafo (
+           \(MapA_X m) -> case m x of
+                       Just r   -> extendA_X (MapA_X m) r
+                       Nothing  -> let  Trafo step = insertNewA_X 
+                                   in   step (MapA_X m)
+           )
+     where
+       insertNewA_X = proc (tenv_s,p) ->
+                     do  r <- newNontR x -< PS [p]
+                         rule2 gram x    -< (tenv_s,r)
+
+
+extendA_X :: m env2-> Ref (x->a) env2-> TrafoE m Productions s env2 (t, Prod (x->a) s) (Productions a env)
+extendA_X m r = fmap  (const $ PS []) $ 
+                      updateSRef m r (\(_,p) (PS ps) -> PS (p:ps))
+
+
+
+
diff --git a/src/Text/GRead/Transformations/LeftFact.hs b/src/Text/GRead/Transformations/LeftFact.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/GRead/Transformations/LeftFact.hs
@@ -0,0 +1,148 @@
+{-# OPTIONS -fglasgow-exts -XArrows #-}
+
+module Text.GRead.Transformations.LeftFact (leftfactoring) where
+
+import Language.TTTAS
+import Text.GRead.Grammar
+import Text.GRead.Transformations.GramTrafo
+import Control.Arrow
+import Data.Maybe
+
+
+
+--list of repeated symbols (with hidden type)
+data AnySym env = forall x. AnySym (Symbol x env)
+
+newtype BT env s = BT (Bool, T env s)
+
+-- The 'leftfactoring' function makes a feed-back loop to apply the 
+-- transformation to the Grammar.
+-- If the transformation has produced new nonterminals (repeated initial
+-- symbols have been found) the 'leftfactoring' function is called again.
+leftfactoring :: forall a. Grammar a -> Grammar a
+leftfactoring (Grammar start productions)
+      = case runTrafo (lftrafo productions) Unit () of
+            Result _ (BT (b,T tt)) gram -> 
+                 let g = Grammar (tt start) gram
+                 in  if b then leftfactoring g
+                          else g 
+
+lftrafo :: Env Productions env env 
+        -> Trafo Unit Productions s () (BT env s)
+lftrafo productions = proc _ ->
+            mdo  let tenv_s = map2trans menv_s
+                 (b,menv_s) <- (rules productions) -< tenv_s
+                 returnA -< BT (b,tenv_s)
+
+
+-- The function 'rules' is defined by induction over the original Grammar. 
+-- Applies the "transformation rule" for each nonterminal (and
+-- its corresponding productions) of the Grammar.
+-- First of all, the list of "repeated initial symbols" in the productions
+-- of a nonterminal is found.
+-- Having this list, the rule is applied to the productions.
+-- The nonterminal is added to the new Grammar, with the productions
+-- generated by the rule.
+-- The output of the Trafo is compound by a boolean indicating if repeated
+-- symbols were found, and the Mapping from the positions in the new Grammar
+-- for each nonterminal of the old Grammar.
+rules  ::  Env Productions env env' 
+        -> Trafo Unit Productions s (T env s) (Bool,(Mapping env' s))
+rules Empty           
+       = proc _ ->
+          returnA -< (False, Mapping Empty)
+
+rules (Ext ps (PS prods)) = 
+    let rep = getrepeated prods
+    in proc tenv_s ->
+         do p <- app_rule rep prods -< tenv_s
+            r <- newSRef -< p   
+            (bs,Mapping e) <- rules ps -< tenv_s
+            returnA -< ((length rep > 0) || bs, Mapping (Ext e r))
+ 
+app_rule :: forall env a s. [AnySym env]
+         -> [Prod a env]
+         -> Trafo Unit Productions s (T env s) (Productions a s)
+app_rule rep prods =  initMap 
+          ( proc tenv_s -> 
+                do pss <- sequenceA  (map  (rule rep) prods) -< tenv_s 
+                   returnA -< PS (concatMap unPS pss)
+          )
+
+-- If the first symbol of the production is in the list of "repeated
+-- initial symbols", the transformation generated by 'rinstert'
+-- is called with input the rest of the production. So, a new nonterminal
+-- A_Rest_X is generated (if necessary) and the rest (beta) of the production
+-- is stored as a production of it.
+-- In other case the production (with its references mapped to the
+-- to the new Grammar) is returned. 
+rule :: [AnySym env] -> Prod a env
+     -> GramTrafo env a s (T env s) (Productions a s)
+rule _   (End a) = proc env2s ->
+                    do returnA -< PS [ mapProd env2s (End a) ]
+                        
+rule rep (Seq x beta) 
+      | x `iselem` rep = proc env2s ->
+                        do  rinsert x -< (env2s, mapProd env2s beta)
+      | otherwise    = proc env2s ->
+                        do returnA -< PS [ mapProd env2s (Seq x beta) ]
+
+
+-- Insertion of a new production into one "rest" nonterminal.
+-- If the symbol 'x' is in the MapA_X the nonterminal was already
+-- added, so we obtain the reference of the nonterminal and add the new
+-- production.
+-- Otherwise, we have to create the new nonterminal (newNontR x).
+rinsert :: forall env s a x. Symbol x env
+        -> GramTrafo env a s (T env s, Prod (x->a) s) (Productions a s)
+rinsert x = 
+     Trafo (
+           \(MapA_X m) -> case m x of
+                       Nothing -> case proc (env2s,p) ->
+                                          do r <- newNontR x -< PS [p]
+                                             addprod x -< (env2s,r) 
+                                  of Trafo step -> step (MapA_X m)
+                       Just r  -> TrafoE (MapA_X m)
+                                         (\(_,p) t e ->
+                                              ( PS []
+                                              , t
+                                              , updateEnv (\(PS ps) 
+                                                             -> PS (p:ps))
+                                                          r e
+                                              )
+                                         )
+           )
+
+
+addprod :: Symbol x env -> GramTrafo env a s (T env s, Ref (x -> a) s) 
+                                           (Productions a s)     
+addprod (Term x) = proc (_,    a__x) -> 
+                      do returnA -< PS [ Term x .*. Nont a__x .*. End ($)]
+addprod (Nont r) = proc (env2s,a__x) -> 
+                      do returnA -< PS [ Nont (unT env2s r) .*. Nont a__x 
+                                         .*. End ($)]
+
+
+-- Get the list of symbols that are repeated as "first symbol" in the list
+-- of productions.
+getrepeated :: [Prod a env] -> [AnySym env]
+getrepeated prods = repeated $ mapMaybe head' prods
+      where head' (End _  ) = Nothing
+            head' (Seq x _) = Just (AnySym x)
+            repeated [] = []
+            repeated (ax@(AnySym x):xs) 
+              | x `iselem` xs = ax : repeated (filter (noteqAny ax) xs)
+              | otherwise     = repeated xs
+
+            noteqAny (AnySym x) (AnySym y) = (aux $ matchSym x y)
+                                               
+aux :: Maybe (Equal a b) -> Bool
+aux (Just Eq) = False
+aux Nothing   = True  
+
+iselem :: Symbol t env -> [AnySym env] -> Bool
+iselem _ []              = False
+iselem x ((AnySym y):ys) = case (matchSym x y) of
+                                  (Just Eq) -> True
+                                  Nothing   -> iselem x ys 
+
diff --git a/src/Text/GShow.hs b/src/Text/GShow.hs
new file mode 100644
--- /dev/null
+++ b/src/Text/GShow.hs
@@ -0,0 +1,122 @@
+{-# LANGUAGE TemplateHaskell #-}
+
+module Text.GShow ( GShow(..), deriveShow, app_prec ) where
+
+import Text.GRead
+import Language.TTTAS
+
+import Language.Haskell.TH
+import Language.Haskell.TH.Syntax
+
+import Data.List (nub, foldl1')
+
+class GShow a where
+  gshow :: a -> String
+  gshowsPrec :: Int -> a -> ShowS
+
+app_prec = 10 :: Int
+
+
+data ADInfo = ADInfo [Name] [Con]
+
+deriveShow :: Name -> Q [Dec]
+deriveShow name = do
+                   (ADInfo args cons) <- getInfo name
+                   let targs = map VarT args
+                       ctx   = map (AppT (ConT ''GShow)) (nub $ filterVars $ unrollApps $ mkContext cons)
+                       typ   = AppT (ConT ''GShow) (foldl1' AppT $ (ConT name):targs)
+                   
+                   gs <- [d| gshow a =  gshowsPrec 0 a "" |]
+                   let clcons = map deriveShowCon cons
+                   gsps <- funD (mkName "gshowsPrec") clcons
+                   return [ InstanceD ctx typ (gsps:gs) ]
+
+
+
+mkContext :: [Con] -> Cxt
+mkContext []                              = []
+mkContext ((NormalC        _ args)  :cs)  = (map snd args) ++ (mkContext cs)
+mkContext ((InfixC   argl  _ argr)  :cs)  = (snd argl) : ((snd argr) : (mkContext cs))
+
+filterVars :: Cxt -> Cxt
+filterVars [] = []
+filterVars (v@(VarT _):vs) = v : filterVars vs
+filterVars (_:vs)          =     filterVars vs
+
+unrollApps :: [Type] -> [Type]
+unrollApps [] = [] 
+unrollApps (a@(AppT _ _):ts) = unrollApp a ++ unrollApps ts
+unrollApps (other:ts)        = other : unrollApps ts
+
+unrollApp :: Type -> [Type]
+unrollApp app = unrollApp' app []
+    where unrollApp' :: Type -> [Type] -> [Type]
+          unrollApp' (AppT sub@(AppT _ _) arg) args = unrollApp' sub (arg:args)
+          unrollApp' (AppT top arg)            args = top:(arg:args)
+
+
+deriveShowCon :: Con -> Q Clause
+
+deriveShowCon (NormalC name types) = do
+                            names <- mapM (const $ newName "x") types
+                            let pat  = conP name (map varP names)
+                                shows = map ((appE fgshowp) . varE) names
+                            clause [varP (mkName "d"), pat] (bdy shows) []
+         where                             
+               bdy s  = normalB (appE (appE fshowParen cond) (str s))
+               fshowParen = varE $ mkName "showParen"
+               cond = infixE (Just $ varE $ mkName "d") 
+                             (varE $ mkName ">") 
+                             (Just $ varE $ mkName "app_prec")
+               str s = infixE (Just (appE (varE $ mkName "showString") cons))
+                              (varE $ mkName ".") (Just $ conc s)
+               cons  = litE $ StringL (nameBase name ++ " ")
+               fgshowp = appE (varE $ mkName "gshowsPrec") (varE $ mkName "app_prec")
+               conc []     = [| id |]
+               conc (s:[]) = [| $(s) |]
+               conc (s:rs) = [| $(s) . $(conc rs)|]
+               
+
+deriveShowCon (InfixC _ name _) = do
+                            f <- getPrec name
+                            clause [varP (mkName "d"), pat] (bdy f) []
+         where 
+               l = mkName "l"
+               r = mkName "r"
+               pat = infixP (varP l) name (varP r) 
+               bdy (f,fl,fr) = normalB (appE (appE fshowParen (cond f)) (str fl fr))
+               fshowParen = varE $ mkName "showParen"
+               cond f = infixE (Just $ varE $ mkName "d") 
+                               (varE $ mkName ">") 
+                               (Just [| f |])
+
+               fshowsPrec d n = appE (appE (varE $ mkName "gshowsPrec") [| d |]) n
+               strl fl   = appE (appE (varE $ mkName ".") (fshowsPrec fl (varE l))) 
+                                (appE (varE $ mkName "showString") 
+                                      (litE $ StringL (' ' : nameBase name ++ " ")))
+               str fl fr = appE (appE (varE $ mkName ".")  (strl fl)) 
+                                (fshowsPrec fr (varE r))
+ 
+getPrec :: Name -> Q (Int, Int, Int)
+getPrec name = do
+    (DataConI _ _ _ (Fixity f fd)) <- reify name
+    return (f, (f + fLeft fd), (f + fRight fd))
+    where
+        fLeft   InfixL  = 0
+        fLeft   InfixR  = 1
+        fRight  InfixR  = 0
+        fRight  InfixL  = 1
+
+
+
+getInfo :: Name -> Q ADInfo
+getInfo name = do
+    info <- reify name
+    case info of
+        TyConI d -> case d of
+            (DataD     _ _ args cs  _)  -> return $ ADInfo args cs 
+            (NewtypeD  _ _ args c   _)  -> return $ ADInfo args [c]
+            _                           -> scopeError
+        _ -> scopeError
+    where scopeError = error $ "Can only be used on algebraic datatypes (which " ++ (show name) ++ " isn't)" 
+
