Fixes and optimizations

See comments on individual commits