various fixes and optimizations