Bugfixes and refactoring after testing