More bug correction and code cleanup