lots of bug fixes and optimizations