refactoring: better logic and indentation