added arity calculation to support recursion; fixed a few bugs and hacks