More bug fixing and refactoring.