reviewed and refactored