Refactored with a minor bug

refactored