Added more error handling. Cleaned up code.