Several bug fixes and code improvements