many bug fixes and code cleanup