bug fixes and general code cleanup