Minor bug fixes to make it more error-resistant