Adding bugfixes and refactoring