Refactoring + better error handling