Optimize stack usage (#409)

This should fix or improve #409 - don't exhaust stack before recursion is detected.

TODO:
* [x] Pass Value objects using shared_ptr instead of by value
* [ ] Throw and catch exceptions on function recursion detected
* [ ] Look at the corresponding module recursion behavior (See #1007)