a bit of refactoring and bugfixing as per comments on the pull request