Bug fixes and error checking code