various correctness and potential bug fixes