More bug fixing and refactoring.
Merge branch 'issues/8'