code cleanup and error handling