Added some error handling and cleaned up code.