Fixes #13, also a little bit of refactoring