Fix some edge cases and error handling