Numerous bug fixes and refactoring.