added debugging and improved input validation.