bug fixes and optimize