from collections import defaultdict


def _cif_disordered_stoichiometry(doc):
    """ Create a matador stoichiometry normalised to the smallest integer
    number of atoms, unless all occupancies are 1/0.

    Parameters:
        doc: dictionary containing `atom_types`, `site_occupancy` and
            `site_multiplicity` keys.

    Returns:
        list of tuples: a standard matador stoichiometry.

    """
    stoich = defaultdict(float)
    eps = 1e-8
    disordered = False
    for ind, site in enumerate(doc['atom_types']):
        stoich[site] += doc['site_occupancy'][ind] * doc['site_multiplicity'][ind]
        if doc['site_multiplicity'][ind] % 1 > 1e-5:
            disordered = True

    if disordered:
        min_int = 1e10
        for atom in stoich:
            if abs(int(stoich[atom]) - stoich[atom]) < eps:
                if int(stoich[atom]) < min_int:
                    min_int = int(stoich[atom])

        if min_int == 1e10:
            min_int = 1
        for atom in stoich:
            stoich[atom] /= min_int

    return sorted([[atom, stoich[atom]] for atom in stoich])