various bug fixes and code cleanup