various subtle bug fixes