Major refactoring.
Bug fix.