Various minor bug fixes and refactoring.
Fixing merge conflics