+ 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;
+
+ } else {
+
+ /* advance past our own events to get to the correct insertion
+ point for the next event(s) from "other"
+ */
+
+ while (us != end() && (*us).time() <= (*them).time()) {
+ ++us;
+ }
+ }
+
+ /* check to see if we reached the end of this buffer while
+ * looking for the insertion point.
+ */
+
+ if (us == end()) {
+
+ /* just append the rest of other and we're done*/
+
+ memcpy (_data + us.offset, other._data + them.offset, other._size - them.offset);
+ _size += other._size - them.offset;
+ assert(_size <= _capacity);
+ break;
+ }