Bug fixes, code cleanup