import csv


def write_spds_to_csv_file(spds,
                           path,
                           delimiter=',',
                           fields=None):
    """
    Writes the given spectral power distributions to given *CSV* file.

    Parameters
    ----------
    spds : dict
        Spectral power distributions to write.
    path : unicode
        Absolute *CSV* file path.
    delimiter : unicode, optional
        *CSV* file content delimiter.
    fields : array_like, optional
        *CSV* file spectral data fields names. If no value is provided the
        order of fields will be the one defined by the sorted spectral power
        distributions *dict*.

    Returns
    -------
    bool
        Definition success.

    Raises
    ------
    RuntimeError
        If the given spectral power distributions have different shapes.
    """

    shapes = [spd.shape for spd in spds.values()]
    if not all(shape == shapes[0] for shape in shapes):
        raise RuntimeError(('Cannot write spectral power distributions with '
                            'different shapes to "CSV" file!'))

    wavelengths = tuple(spds.values())[0].wavelengths
    with open(path, 'w') as csv_file:
        fields = list(fields) if fields is not None else sorted(spds.keys())
        writer = csv.DictWriter(csv_file,
                                delimiter=str(delimiter),
                                fieldnames=['wavelength'] + fields)
        # Python 2.7.x / 3.4.x only.
        # writer.writeheader()
        writer.writerow(dict((name, name) for name in writer.fieldnames))
        for wavelength in wavelengths:
            row = {'wavelength': wavelength}
            row.update(
                dict((field, spds[field][wavelength]) for field in fields))
            writer.writerow(row)

    return True