import copy


def _fold_stats(result, stats, ktk_cube_dataset_id):
    """
    Add stats together.

    Parameters
    ----------
    result: Dict[str, Dict[str, int]]
        Result dictionary, may be empty or a result of a previous call to :meth:`_fold_stats`.
    stats: Dict[str, int]
        Statistics for a single dataset.
    ktk_cube_dataset_id: str
        Ktk_cube dataset ID for the given ``stats`` object.

    Returns
    -------
    result: Dict[str, Dict[str, int]]
        Result dictionary with ``stats`` added.
    """
    result = copy.deepcopy(result)

    if ktk_cube_dataset_id in result:
        ref = result[ktk_cube_dataset_id]
        for k, v in stats.items():
            ref[k] += v
    else:
        result[ktk_cube_dataset_id] = stats

    return result