refactoring and added more input validation