Refactored code based on comments from author