Cleaned up error handling and some logic