refactoring and tests, fixes#12