Some refactoring. Many bug fixes.