import re


def parse_joint_latex(tex_str):
    """
    Parse .tex string into a different blog posts.
    Each section considered one blog post.

    Return [(section, content)] where section = section string and 
    content is all the remaining string until the next section or end of doc.
    """
    # clean up tex. Remove unnecessary commands at the end of string.    
    tex_str = re.sub(r'\\'+'end{document}', '', tex_str)
    tex_str = re.sub(r'\\'+'bibliography{.+?}', '', tex_str)
    tex_str = re.sub(r'\\'+'bibliographystyle{.+?}', '', tex_str)

    list_posts = []
    # character index
    prev_end_sec_ind = -1
    sec_content_start = -1
    sec_title = None
    for m in re.finditer(r'\\'+'section{(.+?)}\n\n', tex_str, re.DOTALL):
        prev_end_sec_ind = m.start()
        if sec_title is not None:
            # add to the list 
            assert sec_content_start >= 0
            sec_content = tex_str[sec_content_start:prev_end_sec_ind]
            list_posts.append((sec_title, sec_content))

        # beginning of a section 
        sec_title = m.group(1)
        sec_content_start = m.end()
    # add the last post 
    sec_content = tex_str[sec_content_start:]
    list_posts.append((sec_title, sec_content))
    return list_posts