Several bug fixes for both correctness and performance