Fix for #2 and #3 with some code tidy and new tests.