minor refactoring and added more comments