Bug fixes, minor refactoring.