Misc code cleanup and slight refactoring