def gen_rst(results):
    """ creates restructured text documents to display tests """

    # make sure the destination directory exists
    try:
        os.mkdir(DOCPATH)
    except OSError as e:
        if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR:
            raise

    toctree = []
    class_ = []
    for output in results:
        section = output.class_.split(',')
        for i in range(len(section)):
            section[i] = section[i].rstrip()
            if section[i] in CLASSMAP:
                section[i] = CLASSMAP[section[i]]
            if i >= len(class_) or section[i] != class_[i]:
                if i == 0:
                    filename = section[i].replace(' ', '_').lower()
                    rst = open(DOCPATH + filename + '.rst', 'w')
                    rst.write(HEADER)
                    rst.write(section[i] + '\n')
                    rst.write(RSTCHARS[0] * len(section[i]))
                    rst.write(time.strftime("\nGenerated %a %d %b %Y %X UTC\n\n", time.gmtime()))
                    toctree.append(filename)
                else:
                    rst.write(section[i] + '\n')
                    rst.write(RSTCHARS[min(i, len(RSTCHARS)-1)] * len(section[i]))
                    rst.write('\n\n')
        class_ = section
        rst.write('.. _cpydiff_%s:\n\n' % output.name.rsplit('.', 1)[0])
        rst.write(output.desc + '\n')
        rst.write('~' * len(output.desc) + '\n\n')
        if output.cause != 'Unknown':
            rst.write('**Cause:** ' + output.cause + '\n\n')
        if output.workaround != 'Unknown':
            rst.write('**Workaround:** ' + output.workaround + '\n\n')

        rst.write('Sample code::\n\n' + indent(output.code, TAB) + '\n')
        output_cpy = indent(''.join(output.output_cpy[0:2]), TAB).rstrip()
        output_cpy = ('::\n\n' if output_cpy != '' else '') + output_cpy
        output_upy = indent(''.join(output.output_upy[0:2]), TAB).rstrip()
        output_upy = ('::\n\n' if output_upy != '' else '') + output_upy
        table = gen_table([['CPy output:', output_cpy], ['uPy output:', output_upy]])
        rst.write(table)

    template = open(INDEXTEMPLATE, 'r')
    index = open(DOCPATH + INDEX, 'w')
    index.write(HEADER)
    index.write(template.read())
    for section in INDEXPRIORITY:
        if section in toctree:
            index.write(indent(section + '.rst', TAB))
            toctree.remove(section)
    for section in toctree:
        index.write(indent(section + '.rst', TAB))