Add error handling, general refactoring