Some performance improvements + refactoring. Better handling of dictionaries.