General refactoring and bug fixing