Miscellaneous refactoring, code cleanup