Code refactoring and bug removal