Several bug fixes and minor improvements