Code cleanup and added error handling.