Some bug fixes and code improvements