fixes #64, added tests for that, minor refactoring