import re


def answer2dict(text):
    """ Translate an M3G API request answer to a dictionary (aka 'text' should
        be the the response.text).
        Normaly the answer is not very simple to handle, cause it has the form:
        [header line] 'col0       col1      col2  col3 .....'
        [line1]       'value0     value1          valu3 ....'
        [line2]       ''
        which means that the text is arranged in columns, and some values may
        be missing. If the answer is empty, [line1] is '', in which case an 
        empty dictionary is returned.
        return value: {'col0':value0, 'col1':value1, 'col2':'', 'col3':value3}
    """
    text = text.split("\n")
    header = text[0]
    header_keys = [f.strip() for f in header.split(' ') if not re.match(r"^\s*$", f)]
    header_idxs = [header.find(k) for k in header_keys]
    header_idxs.append(len(text[0]))

    fields = None
    for line in text[1:]:
        header_idxs[-1] = len(line)
        if line.strip() != '':
            assert(fields == None)
            fields = [ line[idx:header_idxs[i+1]].strip() for i, idx in enumerate(header_idxs[0:-1])]

    ## if fields == None, we have no answer, but only the header line
    if fields is None: return {}
    
    dct={}
    assert(len(header_keys) == len(fields))
    for k,v in zip(header_keys, fields): dct[k]=v
    return dct