Code cleanup and miscellaneous bugfixes