def sequences_to_bytes(sequence, value_op=None):
    """
    Transforms result of rle.get_sequences() into a byte array.
    Encoding:
    - repeats start with a byte whose MSB is 1 and the lower bits are the count,
      followed by the value to repeat.
    - sequences start with a byte whose MSB is 0 and the lower bits are the sequence length,
      followed by that number of bytes of the sequence.
    """
    result = []
    for seq in sequence:
        if seq[0] == "R":
            count = seq[1]
            val = seq[2]
            while count != 0:
                cur_reps = min(128, count)
                result.append((0x80 | (cur_reps - 1)).to_bytes(1, "little"))
                store_val = val.to_bytes(1, "little")
                if value_op:
                    store_val = value_op(store_val)
                result.append(store_val)
                count -= cur_reps
        else:
            part_sequence = seq[1]
            seq_len = len(part_sequence)
            seq_i = 0
            while seq_len != 0:
                cur_len = min(128, seq_len)
                result.append((cur_len - 1).to_bytes(1, "little"))
                for seq_val in part_sequence[seq_i : seq_i + cur_len]:
                    store_val = seq_val.to_bytes(1, "little")
                    if value_op:
                        store_val = value_op(store_val)
                    result.append(store_val)
                seq_i += cur_len
                seq_len -= cur_len
    return b''.join(result)