This commit fixes #5 and fixes #6.

Also, refactored recursive function to improve readablity