def reorder(fname):
    """
    Reorder fields in a configuration file so that
    assignments of variables comes before use.
    """
    fp = open(fname, 'r+')
    options = Options()
    configresult = {}
    section = ""
    configresult[section] = Options()

    for line in fp.readlines():
        line = line.strip()
        if line.startswith("["):
            # New section
            section = line
            configresult[section] = Options()
        elif line.startswith("#"):
            pass
            # Lonely comments are removed
        else:
            # Store an option
            try:
                key, value = line.split("=")
                configresult[section].insert(Option(key, value))
            except __HOLE__:
                pass  # Ignore all weird lines
    fp.seek(0)
    fp.truncate()

    for section in configresult:
        fp.write("{}\n".format(section))
        configresult[section].sort()  # Sort options in this section
        for option in configresult[section].options:
            fp.write("{}={}\n".format(option.key, option.value))

    fp.close()
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/confsort.py/reorder