Several bug fixes ported from CDH4