bug fixes and optimizations