Added sanitize input function and refactored code