Added error handling and cleaned up code.