Added error handling. Refactored