import linecache


def convert_stack(stack, include_func_start_lineno=False):
  """Converts a stack extracted using extract_stack() to a traceback stack.

  Args:
    stack: A list of n 5-tuples,
      (filename, lineno, name, frame_globals, func_start_lineno).
    include_func_start_lineno: True if function start line number should be
      included as the 5th entry in return tuples.

  Returns:
    A tuple of n 4-tuples or 5-tuples
    (filename, lineno, name, code, [optional: func_start_lineno]), where the
    code tuple element is calculated from the corresponding elements of the
    input tuple.
  """
  def _tuple_generator():  # pylint: disable=missing-docstring
    for (filename, lineno, name, frame_globals, func_start_lineno) in stack:
      linecache.checkcache(filename)
      line = linecache.getline(filename, lineno, frame_globals)
      if line:
        line = line.strip()
      else:
        line = None
      if include_func_start_lineno:
        yield (filename, lineno, name, line, func_start_lineno)
      else:
        yield (filename, lineno, name, line)

  return tuple(_tuple_generator())