Various bug fixes and code cleanup