def _simplify_conditional_blocks(text, if_exceptions=[]):
  r"""Simplify possibly nested conditional blocks from 'text'.

  For example, `\iffalse TEST1\else TEST2\fi` is simplified to `TEST2`,
  and `\iftrue TEST1\else TEST2\fi` is simplified to `TEST1`.
  Unknown conditionals are left untouched.

  If the conditional tree is malformed, the function will print a warning
  to stderr and return the original text.
  """
  p = regex.compile(r'(?!(?<=\\newif\s*))\\if\s*(\w+)|\\else(?!\w)|\\fi(?!\w)')
  toplevel_tree = {'left': [], 'right': [], 'kind': 'toplevel', 'parent': None}

  tree = toplevel_tree

  exceptions = [
      # TeX primitives
      'iff',
      # package etoolbox
      'ifpatchable',
      'ifpatchable*',
      'ifbool',
      'iftoggle',
      'ifdef',
      'ifcsdef',
      'ifundef',
      'ifcsundef',
      'ifdefmacro',
      'ifcsmacro',
      'ifdefparam',
      'ifcsparam',
      'ifcsprefix',
      'ifdefprotected',
      'ifcsprotected',
      'ifdefltxprotect',
      'ifcsltxprotect',
      'ifdefempty',
      'ifcsempty',
      'ifdefvoid',
      'ifcsvoid',
      'ifdefequal',
      'ifcsequal',
      'ifdefstring',
      'ifcsstring',
      'ifdefstrequal',
      'ifcsstrequal',
      'ifdefcounter',
      'ifcscounter',
      'ifltxcounter',
      'ifdeflength',
      'ifcslength',
      'ifdefdimen',
      'ifcsdimen',
      'ifstrequal',
      'ifstrempty',
      'ifblank',
      'ifnumcomp',
      'ifnumequal',
      'ifnumodd',
      'ifdimcomp',
      'ifdimequal',
      'ifdimgreater',
      'ifdimless',
      'ifboolexpr',
      'ifboolexpe',
      'ifinlist',
      'ifinlistcs',
      'ifrmnum',
      # package hyperref
      'ifpdfstringunicode',
      # package ifthen
      'ifthenelse',
  ] + if_exceptions

  def new_subtree(kind):
    return {'kind': kind, 'left': [], 'right': []}

  def add_subtree(tree, subtree):
    if 'else' not in tree:
      tree['left'].append(subtree)
    else:
      tree['right'].append(subtree)
    subtree['parent'] = tree

  def print_tree(tree, indent, write):
    if 'start' in tree:
      write(' ' * indent + tree['start'].group() + '\n')
    for subtree in tree['left']:
      print_tree(subtree, indent + 2, write)
    if 'else' in tree:
      write(' ' * indent + tree['else'].group() + '\n')
    for subtree in tree['right']:
      print_tree(subtree, indent + 2)
    if 'end' in tree:
      write(' ' * indent + tree['end'].group() + '\n')

  def print_abort(error_finding):
    os.sys.stderr.write(
        f'Warning: Found {error_finding}! Not removing any conditional'
        ' blocks...\n'
    )
    os.sys.stderr.write(
        f'         This is the matched tree (as built up to the error):\n'
    )
    print_tree(toplevel_tree, indent=9, write=os.sys.stderr.write)
    os.sys.stderr.write(
        f'         Potentially, you need to supply an exception using'
        f" --if_exceptions'.\n"
    )

  for m in p.finditer(text):
    m_no_space = m.group().replace(' ', '')
    if m_no_space == r'\iffalse' or m_no_space == r'\if0':
      subtree = new_subtree('iffalse')
      subtree['start'] = m
      add_subtree(tree, subtree)
      tree = subtree
    elif m_no_space == r'\iftrue' or m_no_space == r'\if1':
      subtree = new_subtree('iftrue')
      subtree['start'] = m
      add_subtree(tree, subtree)
      tree = subtree
    elif m_no_space.startswith(r'\if'):
      if m_no_space[1:] in exceptions:
        continue
      subtree = new_subtree('unknown')
      subtree['start'] = m
      add_subtree(tree, subtree)
      tree = subtree
    elif m_no_space == r'\else':
      if tree['parent'] is None:
        print_abort(r'unmatched \else')
        return text
      elif 'else' in tree:
        print_abort(r'duplicate \else')
        return text

      tree['else'] = m
    elif m.group() == r'\fi':
      if tree['parent'] is None:
        print_abort(r'unmatched \fi')
        return text

      tree['end'] = m
      tree = tree['parent']
    else:
      raise RuntimeError('Unreachable!')

  if tree['parent'] is not None:
    print_abort('unmatched ' + tree['start'].group())
    return text

  positions_to_delete = []

  def traverse_tree(tree):
    if tree['kind'] == 'iffalse':
      if 'else' in tree:
        positions_to_delete.append((tree['start'].start(), tree['else'].end()))
        for subtree in tree['right']:
          traverse_tree(subtree)
        positions_to_delete.append((tree['end'].start(), tree['end'].end()))
      else:
        positions_to_delete.append((tree['start'].start(), tree['end'].end()))
    elif tree['kind'] == 'iftrue':
      if 'else' in tree:
        positions_to_delete.append((tree['start'].start(), tree['start'].end()))
        for subtree in tree['left']:
          traverse_tree(subtree)
        positions_to_delete.append((tree['else'].start(), tree['end'].end()))
      else:
        positions_to_delete.append((tree['start'].start(), tree['start'].end()))
        positions_to_delete.append((tree['end'].start(), tree['end'].end()))
    elif tree['kind'] == 'unknown':
      for subtree in tree['left']:
        traverse_tree(subtree)
      for subtree in tree['right']:
        traverse_tree(subtree)
    else:
      raise ValueError('Unreachable!')

  for tree in toplevel_tree['left']:
    traverse_tree(tree)

  for start, end in reversed(positions_to_delete):
    if end < len(text) and text[end].isspace():
      end_to_del = end + 1
    else:
      end_to_del = end
    text = text[:start] + text[end_to_del:]

  return text
Simplify possibly nested conditional blocks from 'text'.

  For example, `\iffalse TEST1\else TEST2\fi` is simplified to `TEST2`,
  and `\iftrue TEST1\else TEST2\fi` is simplified to `TEST1`.
  Unknown conditionals are left untouched.

  If the conditional tree is malformed, the function will print a warning
  to stderr and return the original text.
  
arxiv_latex_cleaner/arxiv_latex_cleaner.py