Cleanup and refactoring of pull request #1