General refactoring and bug fixes