Improved error handling. Cleaned up code.