Fixes #5

plus some refactoring