Major cleanup and bug fixes