def cap_length(q, a, r, length):
  """Cap total length of q, a, r to length."""
  assert length > 0, "length to cap too short: %d" % length
  while len(q) + len(a) + len(r) >= length:
    max_len = max(len(q), len(a), len(r))
    if len(r) == max_len:
      r = r[:-1]
    elif len(a) == max_len:
      a = a[:-1]
    else:
      q = q[:-1]
  return q, a, r