code cleanup and error fixes