some bug fixes and micro-optimizations