refactored and added input validation