some code cleanup and refactoring