Use map instead of explicit recursion.
Improve error handling.