+
+ /* if we're at the end of the other buffer, we're done */
+
+ if (them == other.end()) {
+ break;
+ }
+
+ /* if we have two messages messages with the same timestamp. we
+ * must order them correctly.
+ */
+
+ if ((*us).time() == (*them).time()) {
+
+ DEBUG_TRACE (DEBUG::MidiIO,
+ string_compose ("simultaneous MIDI events discovered during merge, times %1/%2 status %3/%4\n",
+ (*us).time(), (*them).time(),
+ (int) *(_data + us.offset + sizeof (TimeType)),
+ (int) *(other._data + them.offset + sizeof (TimeType))));
+
+ uint8_t our_midi_status_byte = *(_data + us.offset + sizeof (TimeType));
+ uint8_t their_midi_status_byte = *(other._data + them.offset + sizeof (TimeType));
+ bool them_first = second_simultaneous_midi_byte_is_first (our_midi_status_byte, their_midi_status_byte);
+
+ DEBUG_TRACE (DEBUG::MidiIO, string_compose ("other message came first ? %1\n", them_first));
+
+ if (!them_first) {
+ /* skip past our own event */
+ ++us;
+ }
+
+ bytes_to_merge = sizeof (TimeType) + (*them).size();
+
+ /* move our remaining events later in the buffer by
+ * enough to fit the one message we're going to merge
+ */
+
+ memmove (_data + us.offset + bytes_to_merge, _data + us.offset, _size - us.offset);
+ /* increase _size */
+ _size += bytes_to_merge;
+ assert(_size <= _capacity);
+ /* insert new stuff */
+ memcpy (_data + us.offset, other._data + them.offset, bytes_to_merge);
+ /* update iterator to our own events. this is a miserable hack */
+ us.offset += bytes_to_merge;
+ /* 'us' is now an iterator to the event right after the
+ new ones that we merged
+ */
+ if (them_first) {
+ /* need to skip the event pointed to by 'us'
+ since its at the same time as 'them'
+ (still), and we'll enter
+ */
+
+ if (us != end()) {
+ ++us;
+ }
+ }
+
+ /* we merged one event from the other buffer, so
+ * advance the iterator there.
+ */
+
+ ++them;
+