Some important bug fixes for correctness and performance