Added comments and fixed the error handling.