logic refactoring and cleaning up