slightly better error handling
code refactoring