Some bug fixes and improvements