Various bugfixes and refinements