Refactored, better error handling