Some bug fixes and exception handling