Code refactoring and some cleanup