Better error handeling and refactoring