diff --git a/AspectAG.cabal b/AspectAG.cabal
new file mode 100644
--- /dev/null
+++ b/AspectAG.cabal
@@ -0,0 +1,23 @@
+cabal-version:      >=1.2
+build-type:         Simple
+name:               AspectAG 
+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/AspectAG 
+description:        Library of strongly typed Attribute Grammars implemented using type-level programming   
+synopsis:           Attribute Grammars in the form of an EDSL
+category:           Development 
+stability:          Experimental
+copyright:          Universiteit Utrecht
+build-depends:      base<=4, haskell98, template-haskell, HList>=0.1, containers>=0.2.0.0, mtl>=1.1.0.2
+cabal-version:      >= 1.2.3  
+exposed-modules:    Data.AspectAG, Data.AspectAG.Derive
+other-modules:           
+extensions:         EmptyDataDecls, FlexibleContexts, FlexibleInstances, FunctionalDependencies,
+                    MultiParamTypeClasses, PatternSignatures, RankNTypes, ScopedTypeVariables,
+                    TypeSynonymInstances, UndecidableInstances, GADTs
+hs-source-dirs:     src
+extra-source-files: README, LICENSE-LGPL 
+ghc-options:        -O2 -Wall
diff --git a/COPYRIGHT b/COPYRIGHT
new file mode 100644
--- /dev/null
+++ b/COPYRIGHT
@@ -0,0 +1,28 @@
+The AspectAG 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
+        Wouter Swierstra	
+
+----
+The AspectAG 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.
+
+
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,38 @@
+Please check the right section in this file for instructions depending on how you obtained the source files.
+
+
+Installing AspectAG from a source distribution
+-------------------------------------------
+
+  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/README b/examples/README
new file mode 100644
--- /dev/null
+++ b/examples/README
@@ -0,0 +1,30 @@
+To compile the examples some modules of the library HList have to be exposed.
+The following is an example of a file "HList.cabal" which makes the examples work:
+
+Name:                HList
+Version:             0.1
+Category:            Data
+Synopsis:            Heterogeneous lists
+Description:         HList is a record system providing strongly typed heterogenous lists, records,
+                     type-indexed products (TIP) and co-products; licensed under the MIT X License.
+License:             OtherLicense
+License-File:        LICENSE
+Author:              2004 Oleg Kiselyov (FNMOC, Monterey), Ralf Laemmel (CWI/VU, Amsterdam),
+                     Keean Schupke (Imperial College, London)
+Maintainer:          oleg@pobox.com
+
+Tested-With:         GHC==6.8.2
+Build-Depends:       base, template-haskell
+Build-Type:          Simple
+Exposed-modules:     Data.HList, Data.HList.Label4, Data.HList.Record, Data.HList.TypeCastGeneric1, 
+                     Data.HList.FakePrelude, Data.HList.TypeEqGeneric1, Data.HList.MakeLabels
+Other-modules:       Data.HList.CommonMain, Data.HList.Variant, Data.HList.GhcSyntax,
+                     Data.HList.GhcRecord,Data.HList.HZip, Data.HList.TIC, Data.HList.TIP,
+                     Data.HList.HTypeIndexed, Data.HList.HOccurs, Data.HList.HArray, Data.HList.GhcExperiments,
+                     Data.HList.HListPrelude, Data.HList.TypeEqBoolGeneric
+
+extensions:          EmptyDataDecls, FlexibleContexts, FlexibleInstances, FunctionalDependencies,
+                     MultiParamTypeClasses, OverlappingInstances, PatternSignatures, RankNTypes,
+                     ScopedTypeVariables, TypeSynonymInstances, UndecidableInstances
+ghc-options:         -O2 -Wall
+  
diff --git a/examples/calc.hs b/examples/calc.hs
new file mode 100644
--- /dev/null
+++ b/examples/calc.hs
@@ -0,0 +1,80 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Calc where
+
+import Data.AspectAG
+import Data.AspectAG.Derive
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+import UU.Pretty hiding (par)
+
+--data types-------------------------------------------------------------------
+
+data AGItf = AGItf { expr :: Expr}
+          deriving Show
+
+data Expr = IConst {int::Int}
+          | Add    {e1::Expr, e2::Expr}
+          | Let    {lnm::String, val::Expr, body::Expr}
+          | Var    {vnm::String}
+          deriving Show
+
+
+$(deriveAG ''AGItf)
+
+
+allNT = nt_AGItf .*. nt_Expr .*. hNil
+ 
+-------------------------------------------------------------------------------
+
+
+$(attLabel "spp")
+
+asp_spp () = synAspect spp allNT ((>|<)::PP_Doc->PP_Doc->PP_Doc)  (empty::PP_Doc) ( p_AGItf .*. hNil )
+                       (   p_IConst .=. (\(Fam chi _) -> pp (chi # ch_int))
+                       .*. p_Add    .=. (\(Fam chi _) -> ((chi # ch_e1) # spp) >|< "+" >|< ((chi # ch_e2) # spp))    
+                       .*. p_Var    .=. (\(Fam chi _) -> pp (chi # ch_vnm))
+                       .*. p_Let    .=. (\(Fam chi _) -> "[" >|< (chi # ch_lnm) >|< "=" >|<
+                                                         ((chi # ch_val) # spp) >|< ":" >|< ((chi # ch_body) # spp) >|< "]")    
+                       .*. emptyRecord )
+
+
+$(attLabels ["ienv","sval"])
+
+asp_ienv () = inhAspect ienv ( nt_Expr .*. hNil ) ( p_Add .*. p_Let .*. hNil )
+                       (   p_Let    .=. (\(Fam chi par) -> (    ch_body .=. ((chi # ch_lnm), ((chi # ch_val) # sval)) : (par # ienv)  
+                                                           .*.  emptyRecord))
+                       .*. p_AGItf  .=. (\(Fam chi _)   -> (    ch_expr .=. ([] :: [(String,Int)])
+                                                           .*.  emptyRecord))
+                       .*. emptyRecord )
+
+asp_sval () = synAspect sval allNT ((+)::Int->Int->Int)  (0::Int) ( p_AGItf .*. p_Add .*. hNil )
+                       (   p_IConst .=. (\(Fam chi _)   -> chi # ch_int)
+                       .*. p_Var    .=. (\(Fam chi par) -> maybe 0 id (lookup (chi # ch_vnm) (par # ienv)))
+                       .*. p_Let    .=. (\(Fam chi _)   -> (chi # ch_body) # sval)    
+                       .*. emptyRecord )
+
+
+$(attLabel "ccount")
+
+
+asp_ccount () =   chnAspect ccount allNT ( p_AGItf .*. p_IConst .*. p_Add .*. p_Let .*. p_Var .*. hNil )
+                       emptyRecord
+                       (   p_Add    .=. (\(Fam chi _) -> ((chi # ch_e2) # ccount) + 1 )    
+                       .*. emptyRecord )
+
+
+----example--------------------------------------------------------------------
+
+
+ex = Let "x" (Add (Add (IConst 2) (IConst 3)) (IConst 1)) (Add (Var "x") (Var "x"))
+
+ 
+expp  = sem_AGItf (asp_spp ()) (AGItf ex) () # spp
+exval = sem_AGItf (asp_sval () .+. asp_ienv ()) (AGItf ex) () # sval
+excnt = sem_AGItf (asp_ccount ()) (AGItf ex)  (ccount .=. 0 .*. emptyRecord) # ccount
+
diff --git a/examples/calcM.hs b/examples/calcM.hs
new file mode 100644
--- /dev/null
+++ b/examples/calcM.hs
@@ -0,0 +1,96 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Calc where
+
+import Data.AspectAG
+import Data.AspectAG.Derive
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+import UU.Pretty hiding (par)
+
+
+--data types-------------------------------------------------------------------
+
+data AGItf = AGItf { expr :: Expr}
+          deriving Show
+
+data Expr = IConst {int::Int}
+          | Add    {e1::Expr, e2::Expr}
+          | Let    {lnm::String, val::Expr, body::Expr}
+          | Var    {vnm::String}
+          deriving Show
+
+
+$(deriveAG ''AGItf)
+
+
+allNT = nt_AGItf .*. nt_Expr .*. hNil
+ 
+-------------------------------------------------------------------------------
+
+$(attLabel "spp")
+
+asp_spp () = synAspect spp allNT ((>|<)::PP_Doc->PP_Doc->PP_Doc)  (empty::PP_Doc) ( p_AGItf .*. hNil )
+                       (   p_IConst .=. (def $ do  int <- at ch_int
+                                                   return $ pp int )
+                       .*. p_Add    .=. (def $ do  e1 <- at ch_e1
+                                                   e2 <- at ch_e2
+                                                   return $ (e1 # spp) >|< "+" >|< (e2 # spp) )    
+                       .*. p_Var    .=. (def $ do  vnm <- at ch_vnm 
+                                                   return $ pp vnm )
+                       .*. p_Let    .=. (def $ do  lnm  <- at ch_lnm
+                                                   val  <- at ch_val
+                                                   body <- at ch_body
+                                                   return $ "[" >|< lnm >|< "=" >|< (val # spp) >|< ":" >|< (body # spp) >|< "]")    
+                       .*. emptyRecord )
+
+
+$(attLabels ["ienv","sval"])
+
+
+asp_ienv () = inhAspect ienv ( nt_Expr .*. hNil ) ( p_Add .*. p_Let .*. hNil )
+                       (   p_Let    .=. (def $ do  lnm <- at ch_lnm
+                                                   val <- at ch_val
+                                                   lhs <- at lhs
+                                                   return  (    ch_body .=. ((lnm, val # sval) : (lhs # ienv))
+                                                           .*.  emptyRecord))
+                       .*. p_AGItf  .=. (def $ do  return  (    ch_expr .=. ([] :: [(String,Int)])
+                                                           .*.  emptyRecord))
+
+                       .*. emptyRecord )
+
+asp_sval () = synAspect sval allNT ((+)::Int->Int->Int)  (0::Int) ( p_AGItf .*. p_Add .*. hNil )
+                       (   p_IConst .=. (def $ do  int <- at ch_int
+                                                   return int)
+                       .*. p_Var    .=. (def $ do  vnm <- at ch_vnm
+                                                   lhs <- at lhs
+                                                   return $ maybe 0 id (lookup vnm (lhs # ienv)))
+                       .*. p_Let    .=. (def $ do  body <- at ch_body
+                                                   return $ body # sval)    
+                       .*. emptyRecord )
+
+
+$(attLabel "ccount")
+
+
+asp_ccount () =   chnAspect ccount allNT ( p_AGItf .*. p_IConst .*. p_Add .*. p_Let .*. p_Var .*. hNil )
+                       emptyRecord
+                       (   p_Add    .=. (def $ do  e2 <- at ch_e2
+                                                   return $ (e2 # ccount) + 1 )    
+                       .*. emptyRecord )
+
+
+----example--------------------------------------------------------------------
+
+
+ex = Let "x" (Add (Add (IConst 2) (IConst 3)) (IConst 1)) (Add (Var "x") (Var "x"))
+
+ 
+expp  = sem_AGItf (asp_spp ()) (AGItf ex) () # spp
+exval = sem_AGItf (asp_sval () .+. asp_ienv ()) (AGItf ex) () # sval
+excnt = sem_AGItf (asp_ccount ()) (AGItf ex)  (ccount .=. 0 .*. emptyRecord) # ccount
+
diff --git a/examples/repmin.hs b/examples/repmin.hs
new file mode 100644
--- /dev/null
+++ b/examples/repmin.hs
@@ -0,0 +1,69 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Repmin where
+
+import Data.AspectAG
+import Data.AspectAG.Derive
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+
+
+--data types-------------------------------------------------------------------
+
+data Root = Root { tree :: Tree}
+          deriving Show
+
+data Tree = Node {l::Tree, r::Tree}
+          | Leaf {i::Int}
+          deriving Show
+
+
+$(deriveAG ''Root)
+
+ 
+--repmin-----------------------------------------------------------------------
+
+
+$(attLabels ["smin","ival","sres"])
+
+asp_smin () = synAspect smin ( nt_Tree .*. hNil ) (min::Int->Int->Int)  (0::Int) ( p_Node .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi # ch_i)
+                        .*. emptyRecord )
+
+asp_ival () = inhAspect ival ( nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (   ch_tree .=. (chi # ch_tree) # smin
+                                                        .*. emptyRecord ) )
+                        .*. emptyRecord )
+
+asp_sres () = synAspect sres ( nt_Root .*. nt_Tree .*. hNil ) Node (Leaf 0) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (chi # ch_tree) # sres)
+                        .*. p_Leaf .=. (\(Fam _ par) -> Leaf (par # ival))
+                        .*. emptyRecord )
+
+
+asp_repmin () =  asp_smin () .+. asp_sres () .+. asp_ival ()
+
+repmin tree = sem_Root (asp_repmin ()) (Root tree) () # sres
+
+
+
+
+----example--------------------------------------------------------------------
+
+
+examplet =    (Node (Node (Node (Leaf 1) (Leaf 4))
+                          (Node (Leaf 2) (Leaf 1))
+                    )
+
+                    (Node (Node (Leaf 9) (Leaf 8))
+                          (Leaf 6)
+                    )
+              )
+
+res_repmin = repmin examplet
+
+
diff --git a/examples/repminM.hs b/examples/repminM.hs
new file mode 100644
--- /dev/null
+++ b/examples/repminM.hs
@@ -0,0 +1,72 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Repmin where
+
+import Data.AspectAG
+import Data.AspectAG.Derive
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+
+
+--data types-------------------------------------------------------------------
+
+data Root = Root { tree :: Tree}
+          deriving Show
+
+data Tree = Node {l::Tree, r::Tree}
+          | Leaf {i::Int}
+          deriving Show
+
+
+$(deriveAG ''Root)
+
+ 
+--repmin-----------------------------------------------------------------------
+
+
+$(attLabels ["smin","ival","sres"])
+
+asp_smin () = synAspect smin ( nt_Tree .*. hNil ) (min::Int->Int->Int)  (0::Int) ( p_Node .*. hNil )
+                        (   p_Leaf .=. (def $ liftM id (at ch_i))
+                        .*. emptyRecord )
+
+asp_ival () = inhAspect ival ( nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (def $ do  tree <- at ch_tree 
+                                                  return (   ch_tree .=. tree # smin
+                                                         .*. emptyRecord ) )
+                        .*. emptyRecord )
+
+asp_sres () = synAspect sres ( nt_Root .*. nt_Tree .*. hNil ) Node (Leaf 0) ( p_Node .*. hNil )
+                        (   p_Root .=. (def $ do  tree <- at ch_tree
+                                                  return $ tree # sres)
+                        .*. p_Leaf .=. (def $ do  lhs  <- at lhs 
+                                                  return $ Leaf (lhs # ival))
+                        .*. emptyRecord )
+
+
+asp_repmin () =  asp_smin () .+. asp_sres () .+. asp_ival ()
+
+repmin tree = sem_Root (asp_repmin ()) (Root tree) () # sres
+
+
+
+
+----example--------------------------------------------------------------------
+
+
+examplet =    (Node (Node (Node (Leaf 1) (Leaf 4))
+                          (Node (Leaf 2) (Leaf 1))
+                    )
+
+                    (Node (Node (Leaf 9) (Leaf 8))
+                          (Leaf 6)
+                    )
+              )
+
+res_repmin = repmin examplet
+
+
diff --git a/examples/test1.hs b/examples/test1.hs
new file mode 100644
--- /dev/null
+++ b/examples/test1.hs
@@ -0,0 +1,106 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+
+module Test where
+
+import Data.AspectAG
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+
+
+--data types-------------------------------------------------------------------
+data Root = Root Tree
+          deriving Show
+
+data Tree = Node Tree Tree
+          | Leaf Int
+          deriving Show
+
+
+--data types' dependent definitions
+
+----non terminals
+nt_Root = proxy::Proxy Root
+nt_Tree = proxy::Proxy Tree
+
+----productions
+data P_Root;   p_Root    = proxy::Proxy P_Root
+data P_Node;   p_Node    = proxy::Proxy P_Node
+data P_Leaf;   p_Leaf    = proxy::Proxy P_Leaf
+
+----children labels
+data Ch_tree;   ch_tree  = proxy::Proxy (Ch_tree, Tree)
+data Ch_l;      ch_l     = proxy::Proxy (Ch_l,    Tree)
+data Ch_r;      ch_r     = proxy::Proxy (Ch_r,    Tree)
+data Ch_i;      ch_i     = proxy::Proxy (Ch_i,    Int)
+
+----catamorphism
+sem_Tree  asp (Node left right) = knit (asp # p_Node) (   ch_l .=. sem_Tree asp left 
+                                                      .*. ch_r .=. sem_Tree asp right 
+                                                      .*. emptyRecord )
+sem_Tree  asp (Leaf i         ) = knit (asp # p_Leaf) (   ch_i .=. sem_Lit i 
+                                                      .*. emptyRecord )
+sem_Root  asp (Root t         ) = knit (asp # p_Root) (   ch_tree .=. sem_Tree asp t 
+                                                      .*. emptyRecord )
+
+
+--repmin-----------------------------------------------------------------------
+
+data Att_smin;   smin    = proxy::Proxy Att_smin
+data Att_ival;   ival    = proxy::Proxy Att_ival
+data Att_sres;   sres    = proxy::Proxy Att_sres
+
+
+asp_smin () = synAspect smin ( nt_Tree .*. hNil ) (min::Int->Int->Int)  (0::Int) ( p_Node .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi # ch_i)
+                        .*. emptyRecord )
+
+asp_ival f  = inhAspect ival ( nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (   ch_tree .=. f (chi # ch_tree) 
+                                                        .*. emptyRecord ) )
+                        .*. emptyRecord )
+
+asp_sres () = synAspect sres ( nt_Root .*. nt_Tree .*. hNil ) Node (Leaf 0) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (chi # ch_tree) # sres)
+                        .*. p_Leaf .=. (\(Fam _ par) -> Leaf (par # ival))
+                        .*. emptyRecord )
+
+
+asp_repmin () =  asp_smin () .+. asp_sres () .+. asp_ival (\c -> c # smin)
+
+repmin tree = sem_Root (asp_repmin ()) (Root tree) () # sres
+
+
+--average----------------------------------------------------------------------
+
+data Att_ssum;   ssum    = proxy::Proxy Att_ssum
+data Att_scnt;   scnt    = proxy::Proxy Att_scnt
+
+asp_ssum att f  = 
+              synAspect att ( nt_Tree .*. hNil ) ((+)::Int->Int->Int)  (0::Int) ( p_Node .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> f chi )
+                        .*. emptyRecord )
+
+asp_avg () = asp_ssum scnt (const 1) .+. asp_ssum ssum (\c -> c # ch_i) .+. asp_sres () .+. asp_ival (\c -> div (c # ssum) (c # scnt))
+
+avg tree  = sem_Root (asp_avg ()) (Root tree) () # sres
+
+
+----example--------------------------------------------------------------------
+
+
+examplet =    (Node (Node (Node (Leaf 1) (Leaf 4))
+                          (Node (Leaf 2) (Leaf 1))
+                    )
+
+                    (Node (Node (Leaf 9) (Leaf 8))
+                          (Leaf 6)
+                    )
+              )
+
+res_repmin = repmin examplet
+
+res_avg = avg examplet
+
diff --git a/examples/test1TH.hs b/examples/test1TH.hs
new file mode 100644
--- /dev/null
+++ b/examples/test1TH.hs
@@ -0,0 +1,86 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Test where
+
+import Data.AspectAG
+import Data.AspectAG.Derive
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+
+
+--data types-------------------------------------------------------------------
+
+data Root = Root { tree :: Tree}
+          deriving Show
+
+data Tree = Node {l::Tree, r::Tree}
+          | Leaf {i::Int}
+          deriving Show
+
+
+$(deriveAG ''Root)
+
+ 
+--repmin-----------------------------------------------------------------------
+
+
+$(attLabels ["smin","ival","sres"])
+
+asp_smin () = synAspect smin ( nt_Tree .*. hNil ) (min::Int->Int->Int)  (0::Int) ( p_Node .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi # ch_i)
+                        .*. emptyRecord )
+
+asp_ival f  = inhAspect ival ( nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (   ch_tree .=. f (chi # ch_tree) 
+                                                        .*. emptyRecord ) )
+                        .*. emptyRecord )
+
+asp_sres () = synAspect sres ( nt_Root .*. nt_Tree .*. hNil ) Node (Leaf 0) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (chi # ch_tree) # sres)
+                        .*. p_Leaf .=. (\(Fam _ par) -> Leaf (par # ival))
+                        .*. emptyRecord )
+
+
+asp_repmin () =  asp_smin () .+. asp_sres () .+. asp_ival (\c -> c # smin)
+
+repmin tree = sem_Root (asp_repmin ()) (Root tree) () # sres
+
+
+
+
+--average----------------------------------------------------------------------
+
+$(attLabels ["ssum","scnt"])
+
+
+asp_ssum att f  = 
+              synAspect att ( nt_Tree .*. hNil ) ((+)::Int->Int->Int)  (0::Int) ( p_Node .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> f chi )
+                        .*. emptyRecord )
+
+asp_avg () = asp_ssum scnt (const 1) .+. asp_ssum ssum (\c -> c # ch_i) .+. asp_sres () .+. asp_ival (\c -> div (c # ssum) (c # scnt))
+
+avg tree  = sem_Root (asp_avg ()) (Root tree) () # sres
+
+
+
+----example--------------------------------------------------------------------
+
+
+examplet =    (Node (Node (Node (Leaf 1) (Leaf 4))
+                          (Node (Leaf 2) (Leaf 1))
+                    )
+
+                    (Node (Node (Leaf 9) (Leaf 8))
+                          (Leaf 6)
+                    )
+              )
+
+res_repmin = repmin examplet
+
+res_avg = avg examplet
+
diff --git a/examples/test2.hs b/examples/test2.hs
new file mode 100644
--- /dev/null
+++ b/examples/test2.hs
@@ -0,0 +1,122 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+
+module Test where
+
+import Data.AspectAG
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+
+
+--data types-------------------------------------------------------------------
+data Root = Root Tree
+          deriving Show
+
+data Tree = Node Tree Tree
+          | Bin  Tree Int Tree
+          | Leaf Int
+          deriving Show
+
+
+ 
+--data types' dependent definitions
+
+----non terminals
+nt_Root = proxy::Proxy Root
+nt_Tree = proxy::Proxy Tree
+
+----productions
+data P_Root;   p_Root    = proxy::Proxy P_Root
+data P_Node;   p_Node    = proxy::Proxy P_Node
+data P_Bin;    p_Bin     = proxy::Proxy P_Bin
+data P_Leaf;   p_Leaf    = proxy::Proxy P_Leaf
+
+----children labels
+data Ch_tree;   ch_tree  = proxy::Proxy (Ch_tree, Tree)
+data Ch_l;      ch_l     = proxy::Proxy (Ch_l,    Tree)
+data Ch_r;      ch_r     = proxy::Proxy (Ch_r,    Tree)
+data Ch_i;      ch_i     = proxy::Proxy (Ch_i,    Int)
+data Ch_lb;     ch_lb    = proxy::Proxy (Ch_lb,   Tree)
+data Ch_rb;     ch_rb    = proxy::Proxy (Ch_rb,   Tree)
+data Ch_ib;     ch_ib    = proxy::Proxy (Ch_ib,   Int)
+
+----catamorphism
+sem_Tree  asp (Node left right) = knit (asp # p_Node) (   ch_l .=. sem_Tree asp left 
+                                                      .*. ch_r .=. sem_Tree asp right 
+                                                      .*. emptyRecord )
+sem_Tree  asp (Bin left i right) = knit (asp # p_Bin) (   ch_lb .=. sem_Tree asp left 
+                                                      .*. ch_ib .=. sem_Lit i 
+                                                      .*. ch_rb .=. sem_Tree asp right 
+                                                      .*. emptyRecord )
+sem_Tree  asp (Leaf i         ) = knit (asp # p_Leaf) (   ch_i .=. sem_Lit i 
+                                                      .*. emptyRecord )
+
+sem_Root  asp (Root t         ) = knit (asp # p_Root) (   ch_tree .=. sem_Tree asp t 
+                                                      .*. emptyRecord )
+
+
+--repmin-----------------------------------------------------------------------
+
+data Att_smin;   smin    = proxy::Proxy Att_smin
+data Att_ival;   ival    = proxy::Proxy Att_ival
+data Att_sres;   sres    = proxy::Proxy Att_sres
+
+
+asp_smin () = synAspect smin ( nt_Tree .*. hNil ) (min::Int->Int->Int)  (0::Int)  ( p_Node .*. p_Bin .*.  hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi # ch_i)
+                        .*. emptyRecord )
+
+asp_ival f  = inhAspect ival ( nt_Tree .*. hNil ) ( p_Node .*. p_Bin .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (   ch_tree .=. f (chi # ch_tree) 
+                                                        .*. emptyRecord ) )
+                        .*. emptyRecord )
+
+asp_sres () = synAspect sres ( nt_Root .*. nt_Tree .*. hNil ) Node (Leaf 0) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (chi # ch_tree) # sres)
+                        .*. p_Leaf .=. (\(Fam _ par) -> Leaf (par # ival))
+                        .*. p_Bin  .=. (\(Fam chi _) -> Bin ((chi # ch_lb) # sres) (chi # ch_ib) ((chi # ch_rb) # sres))
+                        .*. emptyRecord )
+
+
+asp_repmin () =  asp_smin () .+. asp_sres () .+. asp_ival (\c -> c # smin)
+
+repmin tree = sem_Root (asp_repmin ()) (Root tree) () # sres
+
+
+--average----------------------------------------------------------------------
+
+data Att_ssum;   ssum    = proxy::Proxy Att_ssum
+data Att_scnt;   scnt    = proxy::Proxy Att_scnt
+
+asp_ssum ()  = 
+              synAspect ssum ( nt_Tree .*. hNil ) ((+)::Int->Int->Int)  (0::Int) ( p_Node .*. p_Bin .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi  # ch_i)
+                        .*. emptyRecord )
+
+asp_scnt ()  = 
+              synAspect scnt ( nt_Tree .*. hNil ) ((+)::Int->Int->Int)  (0::Int) ( p_Node .*. p_Bin .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> 1)
+                        .*. emptyRecord )
+
+asp_avg () = asp_scnt () .+. asp_ssum () .+. asp_sres () .+. asp_ival (\c -> div (c # ssum) (c # scnt))
+
+avg tree  = sem_Root (asp_avg ()) (Root tree) () # sres
+
+----example--------------------------------------------------------------------
+
+examplet =    (Node (Bin  (Node (Leaf 1) (Leaf 4))
+                          100
+                          (Node (Leaf 2) (Leaf 1))
+                    )
+
+                    (Node (Bin  (Leaf 9) 300 (Leaf 8))
+                          (Leaf 6)
+                    )
+              )
+
+res_repmin = repmin examplet
+
+res_avg = avg examplet
+
diff --git a/examples/test2TH.hs b/examples/test2TH.hs
new file mode 100644
--- /dev/null
+++ b/examples/test2TH.hs
@@ -0,0 +1,93 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Test where
+
+import Data.AspectAG
+import Data.AspectAG.Derive
+
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+
+
+--data types-------------------------------------------------------------------
+
+data Root = Root { tree :: Tree}
+          deriving Show
+
+data Tree = Node {l::Tree, r::Tree}
+          | Bin  {lb::Tree, ib::Int, rb::Tree}
+          | Leaf {i::Int}
+          deriving Show
+
+
+$(deriveAG ''Root)
+
+ 
+
+--repmin-----------------------------------------------------------------------
+
+
+$(attLabels ["smin","ival","sres"])
+
+
+asp_smin () = synAspect smin ( nt_Tree .*. hNil ) (min::Int->Int->Int)  (0::Int)  ( p_Node .*. p_Bin .*.  hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi # ch_i)
+                        .*. emptyRecord )
+
+asp_ival f  = inhAspect ival ( nt_Tree .*. hNil ) ( p_Node .*. p_Bin .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (   ch_tree .=. f (chi # ch_tree) 
+                                                        .*. emptyRecord ) )
+                        .*. emptyRecord )
+
+asp_sres () = synAspect sres ( nt_Root .*. nt_Tree .*. hNil ) Node (Leaf 0) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (chi # ch_tree) # sres)
+                        .*. p_Leaf .=. (\(Fam _ par) -> Leaf (par # ival))
+                        .*. p_Bin  .=. (\(Fam chi _) -> Bin ((chi # ch_lb) # sres) (chi # ch_ib) ((chi # ch_rb) # sres))
+                        .*. emptyRecord )
+
+
+asp_repmin () =  asp_smin () .+. asp_sres () .+. asp_ival (\c -> c # smin)
+
+repmin tree = sem_Root (asp_repmin ()) (Root tree) () # sres
+
+
+
+--average----------------------------------------------------------------------
+
+$(attLabels ["ssum","scnt"])
+
+asp_ssum ()  = 
+              synAspect ssum ( nt_Tree .*. hNil ) ((+)::Int->Int->Int)  (0::Int) ( p_Node .*. p_Bin .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi  # ch_i)
+                        .*. emptyRecord )
+
+asp_scnt ()  = 
+              synAspect scnt ( nt_Tree .*. hNil ) ((+)::Int->Int->Int)  (0::Int) ( p_Node .*. p_Bin .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> 1)
+                        .*. emptyRecord )
+
+asp_avg () = asp_scnt () .+. asp_ssum () .+. asp_sres () .+. asp_ival (\c -> div (c # ssum) (c # scnt))
+
+avg tree  = sem_Root (asp_avg ()) (Root tree) () # sres
+
+
+----example--------------------------------------------------------------------
+
+examplet =    (Node (Bin  (Node (Leaf 1) (Leaf 4))
+                          100
+                          (Node (Leaf 2) (Leaf 1))
+                    )
+
+                    (Node (Bin  (Leaf 9) 300 (Leaf 8))
+                          (Leaf 6)
+                    )
+              )
+
+res_repmin = repmin examplet
+
+res_avg = avg examplet
+
diff --git a/examples/test3.hs b/examples/test3.hs
new file mode 100644
--- /dev/null
+++ b/examples/test3.hs
@@ -0,0 +1,114 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+
+module Test where
+
+import Data.AspectAG
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+
+
+--data types-------------------------------------------------------------------
+data Root = Root Tree
+          deriving Show
+
+data Tree = Node Tree Tree
+          | Leaf Int
+          deriving Show
+
+
+--data types' dependent definitions
+
+----non terminals
+nt_Root = proxy::Proxy Root
+nt_Tree = proxy::Proxy Tree
+
+----productions
+data P_Root;   p_Root    = proxy::Proxy P_Root
+data P_Node;   p_Node    = proxy::Proxy P_Node
+data P_Leaf;   p_Leaf    = proxy::Proxy P_Leaf
+
+----children labels
+data Ch_tree;   ch_tree  = proxy::Proxy (Ch_tree, Tree)
+data Ch_l;      ch_l     = proxy::Proxy (Ch_l,    Tree)
+data Ch_r;      ch_r     = proxy::Proxy (Ch_r,    Tree)
+data Ch_i;      ch_i     = proxy::Proxy (Ch_i,    Int)
+
+----catamorphism
+sem_Tree  asp (Node left right) = knit (asp # p_Node) (   ch_l .=. sem_Tree asp left 
+                                                      .*. ch_r .=. sem_Tree asp right 
+                                                      .*. emptyRecord )
+sem_Tree  asp (Leaf i         ) = knit (asp # p_Leaf) (   ch_i .=. sem_Lit i 
+                                                      .*. emptyRecord )
+sem_Root  asp (Root t         ) = knit (asp # p_Root) (   ch_tree .=. sem_Tree asp t 
+                                                      .*. emptyRecord )
+
+
+--repmin-----------------------------------------------------------------------
+
+data Att_smin;   smin    = proxy::Proxy Att_smin
+data Att_ival;   ival    = proxy::Proxy Att_ival
+data Att_sres;   sres    = proxy::Proxy Att_sres
+
+
+asp_smin () = synAspect smin ( nt_Tree .*. hNil ) (min::Int->Int->Int)  (0::Int) ( p_Node .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi # ch_i)
+                        .*. emptyRecord )
+
+asp_ival a  = inhAspect ival ( nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (   ch_tree .=. (chi # ch_tree) # a
+                                                        .*. emptyRecord ) )
+                        .*. emptyRecord )
+
+asp_sres a  = synAspect sres ( nt_Root .*. nt_Tree .*. hNil ) Node (Leaf 0) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (chi # ch_tree) # sres)
+                        .*. p_Leaf .=. (\(Fam _ par) -> Leaf (par # a))
+                        .*. emptyRecord )
+
+
+asp_repmin a =  asp_smin () .+. asp_sres a .+. asp_ival smin
+
+repmin tree = sem_Root (asp_repmin ival) (Root tree) () # sres
+
+
+--chained attribute------------------------------------------------------------
+
+data Att_ccnt;   ccnt    = proxy::Proxy Att_ccnt
+
+
+asp_ccnt () = chnAspect ccnt (nt_Root .*. nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam _ _) -> (   ch_tree .=. (0::Int)
+                                                      .*. emptyRecord ) ) 
+                        .*. emptyRecord )
+                        (   p_Leaf .=. (\(Fam chi par) -> 
+                                            if chi # ch_i == (par # ival) 
+                                                 then (par # ccnt) +1 
+                                                 else  par # ccnt
+                                       )
+                        .*. emptyRecord )
+
+
+
+asp_cnt () = asp_ccnt () .+. asp_repmin ccnt
+
+cnt tree  = sem_Root (asp_cnt ()) (Root tree) () # sres
+
+
+----example--------------------------------------------------------------------
+
+
+examplet =    (Node (Node (Node (Leaf 1) (Leaf 4))
+                          (Node (Leaf 2) (Leaf 1))
+                    )
+
+                    (Node (Node (Leaf 9) (Leaf 8))
+                          (Leaf 6)
+                    )
+              )
+
+res_repmin = repmin examplet
+
+res_cnt = cnt examplet
+
diff --git a/examples/test3TH.hs b/examples/test3TH.hs
new file mode 100644
--- /dev/null
+++ b/examples/test3TH.hs
@@ -0,0 +1,91 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Test where
+
+import Data.AspectAG
+import Data.AspectAG.Derive
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+
+
+--data types-------------------------------------------------------------------
+
+data Root = Root { tree :: Tree}
+          deriving Show
+
+data Tree = Node {l::Tree, r::Tree}
+          | Leaf {i::Int}
+          deriving Show
+
+
+$(deriveAG ''Root)
+
+
+--repmin-----------------------------------------------------------------------
+
+$(attLabels ["smin","ival","sres"])
+
+
+asp_smin () = synAspect smin ( nt_Tree .*. hNil ) (min::Int->Int->Int)  (0::Int) ( p_Node .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi # ch_i)
+                        .*. emptyRecord )
+
+asp_ival a  = inhAspect ival ( nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (   ch_tree .=. (chi # ch_tree) # a
+                                                        .*. emptyRecord ) )
+                        .*. emptyRecord )
+
+asp_sres a  = synAspect sres ( nt_Root .*. nt_Tree .*. hNil ) Node (Leaf 0) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (chi # ch_tree) # sres)
+                        .*. p_Leaf .=. (\(Fam _ par) -> Leaf (par # a))
+                        .*. emptyRecord )
+
+
+asp_repmin a =  asp_smin () .+. asp_sres a .+. asp_ival smin
+
+repmin tree = sem_Root (asp_repmin ival) (Root tree) () # sres
+
+
+--chained attribute------------------------------------------------------------
+
+$(attLabel "ccnt")
+
+
+asp_ccnt () = chnAspect ccnt (nt_Root .*. nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam _ _) -> (   ch_tree .=. (0::Int)
+                                                      .*. emptyRecord ) ) 
+                        .*. emptyRecord )
+                        (   p_Leaf .=. (\(Fam chi par) -> 
+                                            if chi # ch_i == (par # ival) 
+                                                 then (par # ccnt) +1 
+                                                 else  par # ccnt
+                                       )
+                        .*. emptyRecord )
+
+
+
+asp_cnt () = asp_ccnt () .+. asp_repmin ccnt
+
+cnt tree  = sem_Root (asp_cnt ()) (Root tree) () # sres
+
+
+----example--------------------------------------------------------------------
+
+
+examplet =    (Node (Node (Node (Leaf 1) (Leaf 4))
+                          (Node (Leaf 2) (Leaf 1))
+                    )
+
+                    (Node (Node (Leaf 9) (Leaf 8))
+                          (Leaf 6)
+                    )
+              )
+
+res_repmin = repmin examplet
+
+res_cnt = cnt examplet
+
diff --git a/examples/test4.hs b/examples/test4.hs
new file mode 100644
--- /dev/null
+++ b/examples/test4.hs
@@ -0,0 +1,93 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+
+module Test where
+
+import Data.AspectAG
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+
+
+--data types-------------------------------------------------------------------
+data Root = Root Tree
+          deriving Show
+
+data Tree = Node Tree Tree
+          | Leaf Int
+          deriving Show
+
+
+--data types' dependent definitions
+
+----non terminals
+nt_Root = proxy::Proxy Root
+nt_Tree = proxy::Proxy Tree
+
+----productions
+data P_Root;   p_Root    = proxy::Proxy P_Root
+data P_Node;   p_Node    = proxy::Proxy P_Node
+data P_Leaf;   p_Leaf    = proxy::Proxy P_Leaf
+
+----children labels
+data Ch_tree;   ch_tree  = proxy::Proxy (Ch_tree, Tree)
+data Ch_l;      ch_l     = proxy::Proxy (Ch_l,    Tree)
+data Ch_r;      ch_r     = proxy::Proxy (Ch_r,    Tree)
+data Ch_i;      ch_i     = proxy::Proxy (Ch_i,    Int)
+
+----catamorphism
+sem_Tree  asp (Node left right) = knit (asp # p_Node) (   ch_l .=. sem_Tree asp left 
+                                                      .*. ch_r .=. sem_Tree asp right 
+                                                      .*. emptyRecord )
+sem_Tree  asp (Leaf i         ) = knit (asp # p_Leaf) (   ch_i .=. sem_Lit i 
+                                                      .*. emptyRecord )
+sem_Root  asp (Root t         ) = knit (asp # p_Root) (   ch_tree .=. sem_Tree asp t 
+                                                      .*. emptyRecord )
+
+
+--repmin-----------------------------------------------------------------------
+
+data Att_smin;   smin    = proxy::Proxy Att_smin
+data Att_ival;   ival    = proxy::Proxy Att_ival
+data Att_sres;   sres    = proxy::Proxy Att_sres
+
+
+asp_smin () = synAspect smin ( nt_Tree .*. hNil ) (min::Int->Int->Int)  (0::Int) ( p_Node .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi # ch_i)
+                        .*. emptyRecord )
+
+asp_ival f  = inhAspect ival ( nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (   ch_tree .=. f (chi # ch_tree) 
+                                                        .*. emptyRecord ) )
+                        .*. p_Node .=. (\(Fam _ par) -> (   ch_l .=. (par # ival) + 1    -- difference with repmin (doesn't apply copy rule for ch_l)
+                                                        .*. emptyRecord ) )
+                        .*. emptyRecord )
+
+asp_sres () = synAspect sres ( nt_Root .*. nt_Tree .*. hNil ) Node (Leaf 0) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (chi # ch_tree) # sres)
+                        .*. p_Leaf .=. (\(Fam _ par) -> Leaf (par # ival))
+                        .*. emptyRecord )
+
+
+asp_repmin () =  asp_smin () .+. asp_sres () .+. asp_ival (\c -> c # smin)
+
+repmin tree = sem_Root (asp_repmin ()) (Root tree) () # sres
+
+
+
+----example--------------------------------------------------------------------
+
+
+examplet =    (Node (Node (Node (Leaf 1) (Leaf 4))
+                          (Node (Leaf 2) (Leaf 1))
+                    )
+
+                    (Node (Node (Leaf 9) (Leaf 8))
+                          (Leaf 6)
+                    )
+              )
+
+res_repmin = repmin examplet
+
+
diff --git a/examples/test4TH.hs b/examples/test4TH.hs
new file mode 100644
--- /dev/null
+++ b/examples/test4TH.hs
@@ -0,0 +1,70 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Test where
+
+import Data.AspectAG
+import Data.AspectAG.Derive
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+
+
+--data types-------------------------------------------------------------------
+
+data Root = Root { tree :: Tree}
+          deriving Show
+
+data Tree = Node {l::Tree, r::Tree}
+          | Leaf {i::Int}
+          deriving Show
+
+
+$(deriveAG ''Root)
+
+
+--repmin-----------------------------------------------------------------------
+
+$(attLabels ["smin","ival","sres"])
+
+
+asp_smin () = synAspect smin ( nt_Tree .*. hNil ) (min::Int->Int->Int)  (0::Int) ( p_Node .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi # ch_i)
+                        .*. emptyRecord )
+
+asp_ival f  = inhAspect ival ( nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (   ch_tree .=. f (chi # ch_tree) 
+                                                        .*. emptyRecord ) )
+                        .*. p_Node .=. (\(Fam _ par) -> (   ch_l .=. (par # ival) + 1    -- difference with repmin (doesn't apply copy rule for ch_l)
+                                                        .*. emptyRecord ) )
+                        .*. emptyRecord )
+
+asp_sres () = synAspect sres ( nt_Root .*. nt_Tree .*. hNil ) Node (Leaf 0) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (chi # ch_tree) # sres)
+                        .*. p_Leaf .=. (\(Fam _ par) -> Leaf (par # ival))
+                        .*. emptyRecord )
+
+
+asp_repmin () =  asp_smin () .+. asp_sres () .+. asp_ival (\c -> c # smin)
+
+repmin tree = sem_Root (asp_repmin ()) (Root tree) () # sres
+
+
+
+----example--------------------------------------------------------------------
+
+
+examplet =    (Node (Node (Node (Leaf 1) (Leaf 4))
+                          (Node (Leaf 2) (Leaf 1))
+                    )
+
+                    (Node (Node (Leaf 9) (Leaf 8))
+                          (Leaf 6)
+                    )
+              )
+
+res_repmin = repmin examplet
+
+
diff --git a/examples/test5.hs b/examples/test5.hs
new file mode 100644
--- /dev/null
+++ b/examples/test5.hs
@@ -0,0 +1,116 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+
+module Test where
+
+import Data.AspectAG
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+
+
+--data types-------------------------------------------------------------------
+data Root = Root Tree
+          deriving Show
+
+data Tree = Node Tree Tree
+          | Leaf Int
+          deriving Show
+
+
+--data types' dependent definitions
+
+----non terminals
+nt_Root = proxy::Proxy Root
+nt_Tree = proxy::Proxy Tree
+
+----productions
+data P_Root;   p_Root    = proxy::Proxy P_Root
+data P_Node;   p_Node    = proxy::Proxy P_Node
+data P_Leaf;   p_Leaf    = proxy::Proxy P_Leaf
+
+----children labels
+data Ch_tree;   ch_tree  = proxy::Proxy (Ch_tree, Tree)
+data Ch_l;      ch_l     = proxy::Proxy (Ch_l,    Tree)
+data Ch_r;      ch_r     = proxy::Proxy (Ch_r,    Tree)
+data Ch_i;      ch_i     = proxy::Proxy (Ch_i,    Int)
+
+----catamorphism
+sem_Tree  asp (Node left right) = knit (asp # p_Node) (   ch_l .=. sem_Tree asp left 
+                                                      .*. ch_r .=. sem_Tree asp right 
+                                                      .*. emptyRecord )
+sem_Tree  asp (Leaf i         ) = knit (asp # p_Leaf) (   ch_i .=. sem_Lit i 
+                                                      .*. emptyRecord )
+sem_Root  asp (Root t         ) = knit (asp # p_Root) (   ch_tree .=. sem_Tree asp t 
+                                                      .*. emptyRecord )
+
+
+--repmin-----------------------------------------------------------------------
+
+data Att_smin;   smin    = proxy::Proxy Att_smin
+data Att_ival;   ival    = proxy::Proxy Att_ival
+data Att_sres;   sres    = proxy::Proxy Att_sres
+
+
+asp_smin () = synAspect smin ( nt_Tree .*. hNil ) (min::Int->Int->Int)  (0::Int) ( p_Node .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi # ch_i)
+                        .*. emptyRecord )
+
+asp_ival a  = inhAspect ival ( nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (   ch_tree .=. (chi # ch_tree) # a
+                                                        .*. emptyRecord ) )
+                        .*. emptyRecord )
+
+asp_sres a  = synAspect sres ( nt_Root .*. nt_Tree .*. hNil ) Node (Leaf 0) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (chi # ch_tree) # sres)
+                        .*. p_Leaf .=. (\(Fam _ par) -> Leaf (par # a))
+                        .*. emptyRecord )
+
+
+asp_repmin a =  asp_smin () .+. asp_sres a .+. asp_ival smin
+
+repmin tree = sem_Root (asp_repmin ival) (Root tree) () # sres
+
+
+--chained attribute------------------------------------------------------------
+
+data Att_ccnt;   ccnt    = proxy::Proxy Att_ccnt
+
+
+asp_ccnt () = chnAspect ccnt (nt_Root .*. nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam _ _) -> (   ch_tree .=. (0::Int)
+                                                      .*. emptyRecord ) )
+                        .*. p_Node .=. (\(Fam _ par) -> ( ch_l .=. (par # ccnt) + 10  -- diference with scn (doesn't use chain rule for ch_l) 
+                                                        .*. emptyRecord) )  
+                        .*. emptyRecord )
+                        (   p_Leaf .=. (\(Fam chi par) -> 
+                                            if chi # ch_i == (par # ival) 
+                                                 then (par # ccnt) +1 
+                                                 else  par # ccnt
+                                       )
+                        .*. emptyRecord )
+
+
+
+asp_cnt () = asp_ccnt () .+. asp_repmin ccnt
+
+cnt tree  = sem_Root (asp_cnt ()) (Root tree) () # sres
+
+
+----example--------------------------------------------------------------------
+
+
+examplet =    (Node (Node (Node (Leaf 1) (Leaf 4))
+                          (Node (Leaf 2) (Leaf 1))
+                    )
+
+                    (Node (Node (Leaf 9) (Leaf 8))
+                          (Leaf 6)
+                    )
+              )
+
+res_repmin = repmin examplet
+
+res_cnt = cnt examplet
+
diff --git a/examples/test5TH.hs b/examples/test5TH.hs
new file mode 100644
--- /dev/null
+++ b/examples/test5TH.hs
@@ -0,0 +1,93 @@
+{-# OPTIONS -XEmptyDataDecls #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Test where
+
+import Data.AspectAG
+import Data.AspectAG.Derive
+
+import Data.HList.Label4
+import Data.HList.TypeEqGeneric1
+import Data.HList.TypeCastGeneric1
+
+
+
+--data types-------------------------------------------------------------------
+
+data Root = Root { tree :: Tree}
+          deriving Show
+
+data Tree = Node {l::Tree, r::Tree}
+          | Leaf {i::Int}
+          deriving Show
+
+
+$(deriveAG ''Root)
+
+
+--repmin-----------------------------------------------------------------------
+
+$(attLabels ["smin","ival","sres"])
+
+
+asp_smin () = synAspect smin ( nt_Tree .*. hNil ) (min::Int->Int->Int)  (0::Int) ( p_Node .*. hNil )
+                        (   p_Leaf .=. (\(Fam chi _) -> chi # ch_i)
+                        .*. emptyRecord )
+
+asp_ival a  = inhAspect ival ( nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (   ch_tree .=. (chi # ch_tree) # a
+                                                        .*. emptyRecord ) )
+                        .*. emptyRecord )
+
+asp_sres a  = synAspect sres ( nt_Root .*. nt_Tree .*. hNil ) Node (Leaf 0) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam chi _) -> (chi # ch_tree) # sres)
+                        .*. p_Leaf .=. (\(Fam _ par) -> Leaf (par # a))
+                        .*. emptyRecord )
+
+
+asp_repmin a =  asp_smin () .+. asp_sres a .+. asp_ival smin
+
+repmin tree = sem_Root (asp_repmin ival) (Root tree) () # sres
+
+
+--chained attribute------------------------------------------------------------
+
+$(attLabel "ccnt")
+
+
+asp_ccnt () = chnAspect ccnt (nt_Root .*. nt_Tree .*. hNil ) ( p_Node .*. hNil )
+                        (   p_Root .=. (\(Fam _ _) -> (   ch_tree .=. (0::Int)
+                                                      .*. emptyRecord ) )
+                        .*. p_Node .=. (\(Fam _ par) -> ( ch_l .=. (par # ccnt) + 10  -- diference with scn (doesn't use chain rule for ch_l) 
+                                                        .*. emptyRecord) )  
+                        .*. emptyRecord )
+                        (   p_Leaf .=. (\(Fam chi par) -> 
+                                            if chi # ch_i == (par # ival) 
+                                                 then (par # ccnt) +1 
+                                                 else  par # ccnt
+                                       )
+                        .*. emptyRecord )
+
+
+
+asp_cnt () = asp_ccnt () .+. asp_repmin ccnt
+
+cnt tree  = sem_Root (asp_cnt ()) (Root tree) () # sres
+
+
+----example--------------------------------------------------------------------
+
+
+examplet =    (Node (Node (Node (Leaf 1) (Leaf 4))
+                          (Node (Leaf 2) (Leaf 1))
+                    )
+
+                    (Node (Node (Leaf 9) (Leaf 8))
+                          (Leaf 6)
+                    )
+              )
+
+res_repmin = repmin examplet
+
+res_cnt = cnt examplet
+
diff --git a/src/Data/AspectAG.hs b/src/Data/AspectAG.hs
new file mode 100644
--- /dev/null
+++ b/src/Data/AspectAG.hs
@@ -0,0 +1,665 @@
+{-# OPTIONS -XMultiParamTypeClasses -XFunctionalDependencies 
+            -XFlexibleContexts -XFlexibleInstances 
+            -XUndecidableInstances 
+            -XExistentialQuantification 
+            -XEmptyDataDecls -XRank2Types
+            -XTypeSynonymInstances #-}
+
+{-| 
+    Library for First-Class Attribute Grammars.
+
+    The library is documented in the paper: /Attribute Grammars Fly First-Class. How to do aspect oriented programming in Haskell/
+
+
+    For more documentation see the AspectAG webpage: 
+    <http://www.cs.uu.nl/wiki/bin/view/Center/AspectAG>.
+-}
+
+
+module Data.AspectAG (
+
+              -- * Rules
+              Att, Fam(..), Chi, Rule, 
+              inhdef, syndef, ext,
+
+              -- * Aspects
+              Prd, (.+.),
+
+              -- * Semantic Functions
+              sem_Lit, knit,
+
+              -- * Common Patterns
+              copy, use, chain,
+
+              -- * Defining Aspects
+              inhAspect, synAspect, chnAspect,
+              attAspect, defAspect,
+              At(..), lhs, def,
+
+              module Data.HList
+            ) where
+
+import Data.HList hiding ((.+.), hUpdateAtLabel)
+import Data.HList.FakePrelude
+
+import Control.Monad.Reader
+
+-- | Field of an attribution.
+type Att att val = LVPair att val
+
+-- | A Family 'Fam' contains a single attribution 'p' for the parent and
+--   a collection of attributions 'c' for the children. 
+data Fam c p = Fam c p
+
+-- | Field of the record of attributions for the children.
+type Chi ch atts = LVPair ch atts
+
+-- | The type 'Rule' states that a rule takes as input the synthesized attributes 
+--   of the children 'sc' and the inherited attributes of the parent 'ip' and returns
+--   a function from the output constructed thus far (inherited attributes of the children 
+--   |ic| and synthesized attributes of the parent 'sp') to the extended output.
+type Rule sc ip ic sp ic' sp' = Fam sc ip -> Fam ic sp -> Fam ic' sp'
+
+-- | The function 'syndef' adds the definition of a synthesized attribute.
+--   It takes a label 'att' representing the name of the new attribute, 
+--   a value 'val' to be assigned to this attribute, and it builds a function which 
+--   updates the output constructed thus far.
+syndef  ::  HExtend (Att att val) sp sp'
+        =>  att -> val -> (Fam ic sp -> Fam ic sp')
+syndef  att val (Fam ic sp) = Fam  ic (att .=. val .*. sp)
+
+-- | The function 'inhdef' introduces a new inherited attribute for 
+--   a collection of non-terminals.
+--   It takes the following parameters:
+--     'att': the attribute which is being defined,
+--     'nts': the non-terminals with which this attribute is being associated, and
+--     'vals': a record labelled with child names and containing values, 
+--              describing how to compute the attribute being defined at each 
+--              of the applicable child  positions.
+--   It builds a function which updates the output constructed thus far.||
+inhdef  ::  Defs att nts vals ic ic' 
+        =>  att -> nts -> vals -> (Fam ic sp -> Fam ic' sp)
+inhdef att nts vals (Fam ic sp) = 
+        Fam (defs att nts vals ic) sp
+
+
+-- | The class 'Def' is defined by induction over the record 'vals' 
+--   containing the new definitions. 
+--   The function 'defs' inserts each definition into the attribution 
+--   of the corresponding child. 
+class Defs att nts vals ic ic'  | vals ic -> ic' where
+  defs :: att -> nts -> vals -> ic -> ic'
+
+instance Defs att nts (Record HNil) ic ic where
+  defs _ _ _ ic = ic
+
+instance  ( Defs att nts (Record vs) ic ic'
+          , HasLabel (Proxy (lch,t)) ic' mch
+          , HMember (Proxy t) nts mnts
+          , SingleDef  mch mnts att 
+                  (Chi (Proxy (lch,t)) vch) 
+                  ic' ic'' ) 
+      => Defs  att nts 
+               (Record (HCons  (Chi (Proxy (lch,t)) vch) vs)) 
+               ic ic'' 
+      where 
+  defs att nts ~(Record (HCons pch vs)) ic = 
+         singledef mch mnts att pch ic'  
+         where  ic'     = defs att nts (Record vs) ic
+                lch     = labelLVPair pch
+                mch     = hasLabel lch ic'
+                mnts    = hMember (sndProxy lch) nts
+
+
+class  SingleDef mch mnts att pv ic ic' 
+       | mch mnts pv ic -> ic' 
+  where singledef :: mch -> mnts -> att -> pv -> ic -> ic'
+
+
+data IncorrectDef l lch err
+data UndefNT t
+data UndefProd t
+data UndefAtt t
+
+instance Fail (IncorrectDef l lch (UndefNT t)) 
+         => SingleDef HTrue HFalse (Proxy l) (LVPair (Proxy (lch,t)) c) r r' where
+ singledef = undefined
+
+instance Fail (IncorrectDef l lch (UndefProd (lch,t))) 
+         => SingleDef HFalse HTrue (Proxy l) (LVPair (Proxy (lch,t)) c) r r' where
+ singledef = undefined
+
+
+instance  ( HasField lch ic och
+          , HExtend (Att att vch) och och'
+          , HUpdateAtLabel lch och' ic ic') 
+      => SingleDef  HTrue HTrue att (Chi lch vch) ic ic' 
+  where singledef _ _ att pch ic = 
+           hUpdateAtLabel lch (att .=. vch .*. och) ic  
+           where  lch  = labelLVPair  pch
+                  vch  = valueLVPair  pch
+                  och  = hLookupByLabel lch ic 
+
+-- | Composition of two rules.
+ext ::  Rule sc ip ic' sp' ic'' sp'' -> Rule sc ip ic sp ic' sp'
+    -> Rule sc ip ic sp ic'' sp''  
+ext f g input = f input . g input
+
+-- | Field of an aspect. It associates a production 'prd' with a rule 'rule'.
+type Prd prd rule = LVPair prd rule
+
+-- | The class 'Com' combines two aspects.
+class  Com r r' r'' | r r' -> r''
+  where (.+.) :: r -> r' -> r''
+
+instance Com r (Record HNil) r
+  where   r .+. _ = r
+
+instance  (  HasLabel lprd r b
+          ,  ComSingle b (Prd lprd rprd) r r'''
+          ,  Com r''' (Record r') r'')
+        => Com  r (Record (HCons (Prd lprd rprd) r')) r''
+  where
+   r .+. (Record (HCons prd r')) = r''
+    where  b       = hasLabel (labelLVPair prd) r
+           r'''    = comsingle b prd r
+           r''     = r''' .+. (Record r')
+
+
+class  ComSingle b f r r' | b f r -> r'
+  where comsingle :: b -> f -> r -> r'
+
+instance  (  HasField  lprd  r (Rule sc ip ic' sp' ic'' sp'')
+          ,  HUpdateAtLabel  lprd (Rule  sc    ip 
+                                         ic    sp 
+                                         ic''  sp'') 
+                             r r')
+         => ComSingle   HTrue (Prd lprd (Rule sc ip ic sp ic' sp')) 
+                        r r'
+   where 
+    comsingle _ f r  = hUpdateAtLabel n ((r # n) `ext` v) r
+     where  n  = labelLVPair f
+            v  = valueLVPair f
+
+instance ComSingle  HFalse f (Record r) (Record (HCons f r))
+   where comsingle _ f (Record r) = Record (HCons f r)
+
+-- | Semantic function of a terminal
+sem_Lit :: a -> Record HNil -> a
+sem_Lit e (Record HNil) = e
+
+
+-- | The function 'knit' takes the combined rules for a node and the 
+--   semantic functions of the children, and builds a
+--   function from the inherited attributes of the parent to its
+--   synthesized attributes.
+knit  ::  (  Kn fc ic sc,  Empties fc ec) 
+      =>  Rule sc ip ec (Record HNil) ic sp
+          -> fc -> ip -> sp
+knit  rule fc ip =  
+  let  ec = empties fc 
+       (Fam ic sp)   = rule  (Fam sc  ip) 
+                             (Fam ec  emptyRecord)
+       sc = kn fc ic
+  in   sp
+
+
+ 
+class Kn fc ic sc  | fc  -> ic sc where  
+  kn :: fc -> ic -> sc
+
+instance Kn fc ic sc 
+ => Kn (Record fc) (Record ic) (Record sc)  where
+  kn (Record fc) (Record ic) = Record $ kn fc ic
+
+
+instance Kn HNil HNil HNil where
+  kn _ _ = hNil
+
+instance Kn fcr icr scr
+         => Kn    (HCons (Chi lch (ich->sch))     fcr) 
+                  (HCons (Chi lch ich)            icr) 
+                  (HCons (Chi lch sch)            scr) 
+         where
+  kn  ~(HCons pfch fcr) ~(HCons pich icr) = 
+    let  scr        = kn fcr icr
+         lch        = labelLVPair  pfch
+         fch        = valueLVPair  pfch
+         ich        = valueLVPair  pich
+    in   HCons  (newLVPair lch (fch ich)) scr
+
+
+class Empties fc ec | fc -> ec where
+  empties :: fc -> ec
+
+instance Empties fc ec => Empties (Record fc) (Record ec)
+        where empties (Record fc) = Record $ empties fc
+
+instance Empties fcr ecr
+         => Empties  (HCons (Chi lch fch)            fcr) 
+                     (HCons (Chi lch (Record HNil))  ecr) 
+         where
+  empties  ~(HCons pch fcr)  = 
+    let  ecr     = empties fcr
+         lch     = labelLVPair  pch
+    in   HCons  (newLVPair lch emptyRecord) ecr 
+
+instance Empties HNil HNil where
+  empties _ = hNil
+
+
+-- | A /copy/ rule copies an inherited attribute from the parent to all its children.
+--   The function 'copy' takes the name of an attribute 'att' and 
+--   an heterogeneous list of non-terminals 'nts' for which the attribute has to be defined,
+--   and generates a copy rule for this.
+copy  ::   (Copy att nts vp ic ic', HasField att ip vp) 
+      =>   att -> nts -> Rule sc ip ic sp ic' sp
+copy att nts (Fam _ ip) = defcp att nts (ip # att)
+
+defcp  ::  Copy att nts vp ic ic' 
+       =>  att -> nts -> vp -> (Fam ic sp -> Fam ic' sp)
+defcp att nts vp (Fam ic sp)  = 
+        Fam (cpychi att nts vp ic) sp
+
+class  Copy att nts vp ic ic' | ic -> ic' where
+  cpychi  ::  att -> nts -> vp -> ic -> ic'
+
+instance Copy att nts vp (Record HNil) (Record HNil) where
+  cpychi  _ _ _ _ = emptyRecord
+
+instance  ( Copy att nts vp (Record ics) ics'
+          , HMember (Proxy t) nts mnts
+          , HasLabel att vch mvch 
+          , Copy'  mnts mvch att vp 
+                   (Chi (Proxy (lch, t)) vch)  
+                   pch
+          , HExtend pch ics' ic) 
+      => Copy  att nts vp 
+               (Record (HCons (Chi (Proxy (lch, t)) vch) ics))
+               ic
+      where 
+  cpychi att nts vp (Record (HCons pch ics)) = 
+            cpychi' mnts mvch att vp pch .*. ics'
+           where  ics'  = cpychi att nts vp (Record ics) 
+                  lch   = sndProxy (labelLVPair pch)
+                  vch   = valueLVPair pch
+                  mnts  = hMember lch nts
+                  mvch  = hasLabel att vch
+
+class Copy' mnts mvch att vp pch pch'  | mnts mvch pch -> pch' 
+  where
+   cpychi'  ::  mnts -> mvch -> att -> vp -> pch -> pch'
+
+instance Copy' HFalse mvch att vp pch pch where 
+  cpychi' _ _ _ _ pch = pch
+
+instance Copy' HTrue HTrue att vp pch pch where 
+  cpychi' _ _ _ _ pch = pch
+ 
+instance HExtend (Att att vp) vch vch' 
+    => Copy' HTrue HFalse att vp  (Chi lch vch) 
+                           (Chi lch vch') where
+  cpychi' _ _ att vp pch = lch .=. (att .=. vp .*. vch) 
+            where  lch  = labelLVPair pch
+                   vch  = valueLVPair pch
+                   
+
+
+-- | A /use/ rule declares a synthesized attribute that collects information
+--   from some of the children.
+--   The function 'use' takes the following arguments: the attribute to be defined, 
+--   the list of non-terminals for which the attribute is defined,
+--   a monoidal operator which combines the attribute values, 
+--   and a unit value to be used in those cases where none of 
+--   the children has such an attribute. 
+use  ::  (Use att nts a sc, HExtend (Att att a) sp sp') 
+     =>  att -> nts -> (a -> a -> a) -> a 
+         -> Rule sc ip ic sp ic sp'
+
+use att nts oper unit (Fam sc _) = syndef att val
+                    where val = case usechi att nts oper sc of
+                                  Just r  -> r
+                                  Nothing -> unit 
+
+
+class Use att nts a sc  where
+  usechi :: att -> nts -> (a -> a -> a) -> sc -> Maybe a
+
+instance Use att nts a sc => Use att nts a (Record sc) where
+ usechi att nts oper (Record sc) = usechi att nts oper sc
+
+instance Use l nt a HNil where
+ usechi _ _ _ _ = Nothing
+
+
+instance ( HMember (Proxy t) nts mnts
+         , Use' mnts att nts a (HCons (LVPair (Proxy (lch, t)) vch) scr))   
+       => Use att nts a (HCons (LVPair (Proxy (lch, t)) vch) scr) where
+ usechi att nts oper ~sc@(HCons fa _) = usechi' mnts att nts oper sc
+                            where mnts = hMember (sndProxy $ labelLVPair fa) nts
+
+class Use' mnts att nts a sc where
+ usechi' :: mnts -> att -> nts -> (a -> a -> a) -> sc -> Maybe a
+
+instance (HasField att (Record vch) a, Use att nts a scr)  => 
+         Use' HTrue att nts a (HCons (LVPair lch (Record vch)) scr) where
+ usechi' _ att nts oper ~(HCons fa scr) = Just $ case usechi att nts oper scr of
+                                                   Just r  -> oper a r
+                                                   Nothing -> a 
+                            where a = valueLVPair fa # att
+
+instance (Use att nts a scr)  => 
+         Use' HFalse att nts a (HCons (LVPair lch b) scr) where
+ usechi' _ att nts oper ~(HCons _ scr) = usechi att nts oper scr
+
+
+-- | In the /chain/ rule a value is threaded in a depth-first way through the tree, 
+--   being updated every now and then. For this we have chained attributes 
+--   (both inherited and synthesized). If a definition for a synthesized attribute 
+--   of the parent with this name is missing we look for the right-most child with a 
+--   synthesized attribute of this name. If we are missing a definition for one 
+--   of the children, we look for the right-most of its left siblings which 
+--   can provide such a value, and if we cannot find it there, 
+--   we look at the inherited attributes of the father.  
+chain  ::  (  Chain att nts val sc ic sp ic' sp' 
+           ,  HasField att ip val )
+      => att -> nts -> Rule sc ip ic sp ic' sp'
+chain att nts (Fam sc ip) = defchn att nts (ip # att) sc
+
+
+class Chain att nts val sc ic sp ic' sp' | sc ic sp -> ic' sp' where
+  defchn :: att -> nts -> val -> sc -> (Fam ic sp -> Fam ic' sp')
+
+instance  (  Chain' msp att nts val sc ic sp ic' sp' 
+          ,  HasLabel att sp msp )
+      => Chain att nts val sc ic sp ic' sp'
+  where
+  defchn att nts val sc inp@(Fam _ sp)  = defchn' msp att nts val sc inp 
+        where  msp        = hasLabel att sp
+               
+
+
+class Chain' msp att nts val sc ic sp ic' sp' | msp sc ic sp -> ic' sp' where
+  defchn' :: msp -> att -> nts -> val -> sc -> Fam ic sp -> Fam ic' sp'
+
+
+instance   (  ChnChi att nts val sc ic ic' 
+           ,  HExtend (Att att val) sp sp' )
+      => Chain' HFalse att nts val sc ic sp ic' sp'
+  where
+  defchn' _ att nts val sc (Fam ic sp)  = 
+        let (val',ic') = chnchi att nts val sc ic
+        in  Fam ic' (att .=. val' .*. sp)
+
+instance   (  ChnChi att nts val sc ic ic' )
+      => Chain' HTrue att nts val sc ic sp ic' sp
+  where
+  defchn' _ att nts val sc (Fam ic sp)  = 
+        let (_,ic') = chnchi att nts val sc ic
+        in  Fam ic' sp
+
+
+class ChnChi att nts val sc ic ic' | sc ic -> ic' where
+  chnchi :: att -> nts -> val -> sc -> ic -> (val,ic')
+
+
+instance ChnChi att nts val (Record HNil) (Record HNil) (Record HNil) where
+  chnchi  _ _ val _ _ = (val, emptyRecord)
+
+instance  ( ChnChi att nts val (Record scs) (Record ics) ics'
+          , HMember (Proxy t) nts mnts
+          , ChnChi'  mnts att val
+                     (Chi (Proxy (lch, t)) sch)  
+                     (Chi (Proxy (lch, t)) ich)  
+                     pch
+          , HExtend pch ics' ic) 
+      => ChnChi  att nts val 
+                 (Record (HCons (Chi (Proxy (lch, t)) sch) scs))
+                 (Record (HCons (Chi (Proxy (lch, t)) ich) ics))
+                 ic
+      where 
+  chnchi att nts val (Record (HCons psch scs)) (Record (HCons pich ics)) =  
+            let (val'',ics') = chnchi att nts val' (Record scs) (Record ics)  
+            in (val'',ich'.*. ics')
+           where  (val',ich') = chnchi' mnts att val psch pich  
+                  lch   = sndProxy (labelLVPair psch)
+                  mnts  = hMember lch nts
+
+class ChnChi' mnts att val sch ich ich'  | mnts sch ich -> ich' 
+  where
+   chnchi'  ::  mnts -> att -> val -> sch -> ich -> (val,ich')
+
+
+instance ChnChi' HFalse att val sch ich ich where 
+  chnchi' _ _ val _ ich = (val,ich)
+
+instance  ( HasLabel att sch msch 
+          , HasLabel att ich mich 
+          , ChnChi'' msch mich att val
+                     (Chi (Proxy (lch, t)) sch)  
+                     (Chi (Proxy (lch, t)) ich)  
+                     pch )
+      => ChnChi'  HTrue att val
+                  (Chi (Proxy (lch, t)) sch)  
+                  (Chi (Proxy (lch, t)) ich)  
+                  pch
+  where
+  chnchi' _ att val psch pich = chnchi'' msch mich att val psch pich
+           where  sch   = valueLVPair psch
+                  ich   = valueLVPair pich
+                  msch  = hasLabel att sch
+                  mich  = hasLabel att ich
+
+
+class ChnChi'' msch mich att val sch ich ich'  | msch mich sch ich -> ich' 
+  where
+   chnchi''  ::  msch -> mich -> att -> val -> sch -> ich -> (val,ich')
+
+
+
+instance Fail (IncorrectDef att lch (UndefAtt att)) 
+        => ChnChi'' HFalse HTrue att val sch (Chi lch ich) ich' where 
+  chnchi'' _ _ _ _ _ _ = undefined
+
+instance Fail (IncorrectDef att lch (UndefAtt att)) 
+        => ChnChi'' HFalse HFalse att val sch (Chi lch ich) ich' where 
+  chnchi'' _ _ _ _ _ _ = undefined
+
+instance HasField att sch val
+        => ChnChi'' HTrue HTrue att val (Chi lch sch) ich ich where 
+  chnchi'' _ _ att _ psch ich = (sch # att,ich)
+             where sch = valueLVPair psch
+
+instance  (  HasField att sch val
+          ,  HExtend (Att att val) ich ich' )
+        => ChnChi'' HTrue HFalse att val (Chi lch sch) (Chi lch ich) (Chi lch ich') where 
+  chnchi'' _ _ att val psch pich = (sch # att, lch .=. (att .=. val .*. ich))
+             where  lch = labelLVPair psch
+                    sch = valueLVPair psch
+                    ich = valueLVPair pich 
+
+-- | The function 'inhAspect' defines an inherited attribute aspect.
+--   It takes as arguments: the name of the attribute 'att', 
+--   the list 'nts' of non-terminals where the attribute is defined,
+--   the list 'cpys' of productions where the copy rule has to be applied, 
+--   and a record 'defs' containing the explicit definitions for some productions.
+inhAspect ::  (  AttAspect (FnInh att nts) defs defasp
+              ,  DefAspect (FnCpy att nts) cpys cpyasp
+              ,  Com cpyasp defasp inhasp)
+         => att -> nts -> cpys -> defs -> inhasp
+inhAspect att nts cpys defs 
+   =     (defAspect  (FnCpy att nts)  cpys)
+   .+.   (attAspect  (FnInh att nts)  defs) 
+
+
+-- | The function 'synAspect' defines a synthesized attribute aspect. 
+---  The rule applied is the use rule, 
+--   which takes 'op' as the monoidal operator and 'unit' as the unit value. 
+synAspect ::  (  AttAspect (FnSyn att) defs defasp
+              ,  DefAspect (FnUse att nts op unit) uses useasp
+              ,  Com useasp defasp synasp) 
+         => att -> nts -> op -> unit -> uses -> defs -> synasp
+synAspect att nts op unit uses defs 
+   =     (defAspect  (FnUse att nts op unit)    uses)
+   .+.   (attAspect  (FnSyn att)                defs)
+
+
+-- | A chained attribute definition introduces both an inherited 
+--   and a synthesized attribute. In this case the pattern to be applied is the chain rule. 
+chnAspect ::  (  DefAspect (FnChn att nts) chns chnasp
+              ,  AttAspect (FnInh att nts) inhdefs inhasp
+              ,  Com chnasp inhasp asp
+              ,  AttAspect (FnSyn att) syndefs synasp
+              ,  Com asp synasp  asp') 
+         => att -> nts -> chns -> inhdefs -> syndefs -> asp'
+chnAspect att nts chns inhdefs syndefs 
+   =     (defAspect  (FnChn att nts)   chns)
+   .+.   (attAspect  (FnInh att nts)   inhdefs)
+   .+.   (attAspect  (FnSyn att)       syndefs)
+
+
+
+class AttAspect rdef defs rules | rdef defs -> rules 
+   where attAspect :: rdef -> defs -> rules
+
+instance  (  AttAspect rdef (Record defs) rules
+          ,  Apply rdef def rule  
+          ,  HExtend (Prd lprd rule) rules rules' )  
+         => AttAspect  rdef 
+                       (Record (HCons  (Prd lprd def) 
+                                       defs)) 
+                       rules' 
+  where
+   attAspect rdef (Record (HCons def defs)) = 
+         let  lprd = (labelLVPair def)
+         in   lprd .=. apply rdef (valueLVPair def) 
+              .*.  attAspect rdef (Record defs)   
+
+
+instance AttAspect rdef (Record HNil) (Record HNil) 
+  where attAspect _ _ = emptyRecord
+
+{-
+data FnSyn att = FnSyn att
+
+instance  (HExtend (LVPair att val) sp sp', TypeCast (Rule sc ip ic sp ic sp') r)
+         => Apply  (FnSyn att) (Fam sc ip -> val) r
+                    where 
+  apply (FnSyn att) f =  typeCast $ syndef att . f 
+
+data FnInh att nt = FnInh att nt
+
+instance  (Defs att nts vals ic ic', TypeCast (Rule sc ip ic sp ic' sp) r)
+         => Apply  (FnInh att nts) (Fam sc ip -> vals) r
+                    where 
+  apply (FnInh att nts) f = typeCast $ inhdef att nts . f 
+-}
+
+data FnSyn att = FnSyn att
+
+instance  HExtend (LVPair att val) sp sp'
+         => Apply  (FnSyn att) (Fam sc ip -> val) 
+                   (Rule sc ip ic sp ic sp') where 
+  apply (FnSyn att) f =  syndef att . f 
+
+data FnInh att nt = FnInh att nt
+
+instance  Defs att nts vals ic ic'
+         => Apply  (FnInh att nts) (Fam sc ip -> vals) 
+                   (Rule sc ip ic sp ic' sp) where 
+  apply (FnInh att nts) f = inhdef att nts . f 
+
+
+
+class DefAspect deff prds rules | deff prds -> rules 
+  where defAspect :: deff -> prds -> rules
+
+instance DefAspect deff HNil (Record HNil) where
+  defAspect _ _ = emptyRecord
+
+instance  (  Poly deff deff'
+          ,  DefAspect deff prds rules
+          ,  HExtend (Prd prd deff') rules rules' )  
+         => DefAspect deff (HCons prd prds) rules' where
+  defAspect deff (HCons prd prds)  =
+              prd .=. poly deff  .*.  defAspect deff prds   
+
+
+class Poly a b where
+  poly :: a -> b
+
+data FnCpy att nts = FnCpy att nts
+
+instance  (  Copy att nts vp ic ic'
+          ,  HasField att ip vp
+          ,  TypeCast (Rule sc ip ic sp ic' sp) r) 
+         => Poly  (FnCpy att nts) r  where 
+  poly (FnCpy att nts)  = typeCast $ copy att nts 
+
+
+data FnUse att nt op unit = FnUse att nt op unit
+
+instance  (  Use att nts a sc
+          ,  HExtend (LVPair att a) sp sp'
+          ,  TypeCast (Rule sc ip ic sp ic sp') r) 
+         => Poly  (FnUse att nts (a -> a -> a) a) r where 
+  poly (FnUse att nts op unit)  = typeCast $ use att nts op unit 
+
+
+data FnChn att nt = FnChn att nt
+
+instance  (  Chain att nts val sc ic sp ic' sp' 
+          ,  HasField att ip val 
+          ,  TypeCast (Rule sc ip ic sp ic' sp') r) 
+      => Poly   (FnChn att nts) r where 
+  poly (FnChn att nts) = typeCast $ chain att nts
+
+
+------ 
+
+data Lhs
+lhs :: Proxy Lhs
+lhs = proxy 
+
+class At l m v | l -> v where
+  at :: l -> m v
+
+instance (HasField (Proxy (lch,nt)) chi v, MonadReader (Fam chi par) m) 
+       => At (Proxy (lch,nt)) m v where
+  at lbl = liftM (\(Fam chi _) -> chi # lbl) ask
+
+instance MonadReader (Fam chi par) m
+       => At (Proxy Lhs) m par where
+  at _ = liftM (\(Fam _ par) -> par) ask
+
+def :: Reader (Fam chi par) a -> ((Fam chi par) -> a)
+def = runReader
+
+
+------ HList
+
+class HBool b => HasLabel l r b | l r -> b
+instance HasLabel l r b => HasLabel l (Record r) b
+instance (HEq l lp b, HasLabel l r b', HOr b b' b'') 
+   => HasLabel l (HCons (LVPair lp vp) r) b''
+instance HasLabel l HNil HFalse
+
+hasLabel :: HasLabel l r b => l -> r -> b
+hasLabel = undefined
+
+class HUpdateAtLabel l v r r' | l v r -> r' where
+  hUpdateAtLabel :: l -> v -> r -> r'
+
+instance  (  RecordLabels r ls, HFind l ls n
+          ,  HUpdateAtHNat n (LVPair l v) r r')
+      => HUpdateAtLabel l v (Record r) (Record r')
+  where
+   hUpdateAtLabel l v (Record r) = Record r'
+    where
+     n    = hFind l (recordLabels r)
+     r'   = hUpdateAtHNat n (newLVPair l v) r
+
+
+sndProxy :: Proxy (a,b) -> Proxy b
+sndProxy _ = undefined
+
diff --git a/src/Data/AspectAG/Derive.hs b/src/Data/AspectAG/Derive.hs
new file mode 100644
--- /dev/null
+++ b/src/Data/AspectAG/Derive.hs
@@ -0,0 +1,156 @@
+{-# LANGUAGE TemplateHaskell #-}
+{-# OPTIONS -XEmptyDataDecls #-}
+
+module Data.AspectAG.Derive (deriveAG, attLabel, attLabels) where
+
+import Language.Haskell.TH
+
+import Data.Set (Set)
+import Data.List (isPrefixOf)
+import qualified Data.Set as S
+
+--import Data.HList
+
+import Data.AspectAG
+
+data UserType  = UserD Name [Name] [Con]
+type TypeDecls = (Set Name, [Dec])
+
+
+declareLabel :: Name -> Name -> TypeQ -> Q [Dec]
+declareLabel ndata nlabel t = do 
+            dtl <- dataD (cxt []) ndata [] [] []
+            lbl <- declareFnLabel nlabel t
+            return $ dtl:lbl
+
+declareFnLabel ::  Name -> TypeQ -> Q [Dec]
+declareFnLabel nlabel t = do 
+            sgn <- sigD nlabel (appT (conT $ mkName "Proxy") t)  
+            let pxy = normalB [| proxy |]
+            lbl <- funD nlabel [clause [] pxy []]
+            return [sgn,lbl]
+
+attLabel ::  String -> Q [Dec]
+attLabel att = declareLabel attn (mkName att) (conT $ attn) 
+  where
+      attn  = mkName $ "Att_" ++ att
+      
+
+attLabels ::  [String] -> Q [Dec]
+attLabels = liftM concat . mapM attLabel
+
+
+chLabels ::  [Name] -> [Type] -> Q [Dec]
+chLabels ns ts = (liftM concat) $ zipWithM label ns ts
+  where
+      label n t = declareLabel (chTName n) (chName n) (tyLabel (chTName n) t) 
+      tyLabel n t = appT (appT (conT $ mkName "(,)") (conT n)) (return t) 
+
+chName,chTName,ntName,prdName,prdTName ::  Name -> Name
+chName   cn = mkName $ "ch_" ++ nameBase cn 
+chTName  cn = mkName $ "Ch_" ++ nameBase cn 
+ntName   cn = mkName $ "nt_" ++ nameBase cn 
+prdName  cn = mkName $ "p_"  ++ nameBase cn 
+prdTName cn = mkName $ "P_"  ++ nameBase cn 
+
+
+deriveAG :: Name -> Q [Dec]
+deriveAG n = do
+              (_,decl) <- derive n (S.empty,[]) --eval)
+              return decl
+
+
+
+
+semName ::  Name -> Name
+semName t = mkName ("sem_"++(nameBase t))
+
+derive :: Name -> TypeDecls -> Q TypeDecls 
+derive n (stn,decl) = 
+    do
+       info <- reify n 
+       if (S.member n stn || primitive info)  
+          then return (stn,decl)
+          else let stn' = S.insert n stn
+               in  do
+                      (UserD _ _ lc) <- getUserType info
+                      ((s,d),fc)   <- foldM deriveCons ((stn',decl),[]) lc
+                      let semDecl = FunD (semName n) fc
+                      nt <- declareFnLabel (ntName n) (conT $ n)
+                      return (s,semDecl:(nt++d))
+
+deriveCons :: (TypeDecls,[Clause]) -> Con -> Q (TypeDecls,[Clause])
+deriveCons ((stn,decl),fc) c =                     
+    do
+      let (cht,chn,cn) = getCtx c
+      (stn',decl') <- foldM (\td t -> derive (typeName t) td) (stn,decl) cht
+      conargs <- newNames cht
+      body <- [| knit ($(aspV) # $(att cn)) $(childs cht chn conargs) |] 
+      let semF = Clause (pat cn conargs) (NormalB body) []
+      lp <- declareLabel (prdTName cn) (prdName cn) (conT $ prdTName cn)
+      lc <- chLabels chn cht
+      return ((stn',lp++lc++decl'),semF:fc)
+  where
+     newNames []     = return []
+     newNames (_:as) = do
+                        na  <- newName "x"
+                        nas <- newNames as
+                        return (na:nas)
+     pat cn args = [aspP, ConP cn (map VarP args)] 
+     aspP = VarP $ mkName "asp"
+     aspV = varE $ mkName "asp"
+     att cn  = varE $ prdName cn
+     ch  cn  = varE $ chName cn
+     childs []     _      _      = [| emptyRecord |]
+     childs (t:ts) (n:ns) (p:ps) = [| $(ch n) .=. $(chFun (typeName t) p)  .*. $(childs ts ns ps) |]
+     childs _      _      _      = error "Impossible case!!"
+     chFun tn n =  
+              do
+                  i <- reify (tn)
+                  if primitive i
+                   then [| ( \(Record HNil) -> $(varE n) ) |]
+                   else [| $(varE (semName tn)) $(aspV) $(varE n) |]
+           
+
+
+
+
+getUserType :: Info -> Q UserType
+getUserType info = do
+    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"
+
+getCtx :: Con -> ([Type],[Name], Name) 
+getCtx (RecC           name args) = (map thd args, map fst' args, name)
+getCtx (NormalC name _) = error $ "Constructor " ++ (show name) ++ " is not a record."
+getCtx (InfixC _ name _) = error $ "Constructor " ++ (show name) ++ " is not a record."	
+getCtx _ = error $ "Cannot derive a 'forall' constructor."	
+
+thd :: (a, b, c) -> c
+thd (_, _, c) = c
+
+fst' :: (a, b, c) -> a
+fst' (a, _, _) = a
+
+
+
+primitive ::  Info -> Bool
+primitive (PrimTyConI _ _ _)          =  True
+primitive (TyConI (DataD _ n _ _ _))  =  isPrefixOf "GHC" (show n) 
+primitive (TyConI (TySynD _ _ _))     =  True   -- type synonyms to escape
+primitive  _                          =  False
+
+
+typeName :: Type -> Name
+typeName t = case t of
+    VarT varname             -> varname
+    ConT conname             -> conname
+    _                        -> error $ "Not valid type " ++ (show t)
+
+
+
