code cleanup and improve error handling