explanation added as well as code refactoring