Various bug fixes. See code for comments