MAJOR refactoring. Most functionality unchanged.