Numerous bug fixes and code improvements