Cleaned up error handling. Added logging