Added basic error handling.
Refactored code.