Incorporated some of the bugfixes in pull request #5 by @samw-bilue.