Huge refactoring with many fixes.