code cleanup and added exception handling