Added error messages and cleaned up the code.