Added input validation

Refactored code.