More code cleanup and bug fixes