some code cleanup, refactoring and comments