Fix recursion (total rewrite) and tests