def write(file, system):
    """
    Write data in system to a dm file
    """

    # TODO: Check for bugs!!!

    out = list()
    out.append('# DOME format version 1.0')
    ppl = 7  # parameter per line
    retval = True
    dev_list = sorted(system.devman.devices)
    for dev in dev_list:
        model = system.__dict__[dev]
        if not model.n:
            continue

        out.append('')
        header = dev + ', '
        space = ' ' * (len(dev) + 2)
        keys = list(model._data.keys())
        keys.extend(['name', 'idx'])
        keys = sorted(keys)

        # remove non-existent keys
        for key in keys:
            if key not in model.__dict__.keys():
                keys.pop(key)

        nline = int(ceil(len(keys) / ppl))
        nelement = model.n
        vals = [''] * len(keys)

        # for each element, read values
        for elem in range(nelement):
            for idx, key in enumerate(keys):
                if model._flags['sysbase'] and key in model._store.keys():
                    val = model._store[key][elem]
                else:
                    val = model.__dict__[key][elem]

                if isinstance(val, float):
                    val = round(val, 5)
                elif isinstance(val, str):
                    val = '"{}"'.format(val)
                elif isinstance(val, list):
                    val = list(val)
                    val = '; '.join(str(i) for i in val)
                    val = '[{}]'.format(val)
                elif val is None:
                    val = 0
                vals[idx] = val

            pair = []
            for key, val in zip(keys, vals):
                pair.append('{} = {}'.format(key, val))

            for line in range(nline):
                string = ', '.join(pair[ppl * line:ppl * (line + 1)])
                if line == 0:  # append header or space
                    string = header + string
                else:
                    string = space + string
                if not line == nline - 1:  # add comma except for last line
                    string += ','

                out.append(string)

    fid = open(file, 'w')
    for line in out:
        fid.write(line + '\n')

    fid.close()
    return retval
Write data in system to a dm file