def bangbang_compressor(bangbang_protocol
                       ):
  """Compresses the bang bang protocol.

  Merges chunks of contiguous bangbang chunks into a Tuple of duration (in
  number of chunks) and which Hamiltonian to apply.

  Args:
    bangbang_protocol: List of HamiltonianType values, determines which
        Hamiltonian should be applied at the corresponding chunk.

  Returns:
    List of Tuples containing the Hamiltonian type and the number of chunks to
    apply the Hamiltonian type for.
  """
  current_mode = None
  compressed_protocol = []
  chunk_counter = 0
  for protocol_mode in bangbang_protocol:
    if current_mode is None:
      current_mode = protocol_mode
      chunk_counter = 1
    elif current_mode == protocol_mode:
      chunk_counter += 1
    else:
      compressed_protocol.append((chunk_counter, current_mode))
      current_mode = protocol_mode
      chunk_counter = 1
  # Append what's left over
  if chunk_counter > 0:
    compressed_protocol.append((chunk_counter, current_mode))
  return compressed_protocol