Various bug fixes and refinements