various code cleanup and bug fixes