Refactoring and bugfixes, fixes #19