Many bug fixes for correctness and performance