refactoring with a few improvements.