anchor.diff:               #qos{ level = L } ->
                    Qos = #qos{ level = L,
                                message_id = NextId },
  -                 Replay1 = gb_trees:insert(?LOCAL(NextId), P0, Replay),
  +                 Replay1 = record_for_replay(NextId, P0, Replay),
                    P1 = P0#publish{ qos = Qos },
                    write(S0, P1),
                    S0#state{ replay = Replay1,
  
positive.code:     end.
  
  resend_or_reset(S = #state{ clean_session = true }) ->
      S#state{ rpcs = gb_trees:empty(),
               replay = gb_trees:empty() };
  resend_or_reset(S = #state{ replay = Replay }) ->
      resend(S#state{ rpcs = gb_trees:empty() }, Replay).
  
  resend(S, Replay) ->
      case gb_trees:is_empty(Replay) of
          true ->
              S#state{ replay = Replay };
          false ->
              {_Id, Frame, Replay1} = gb_trees:take_smallest(Replay),
              write(S, dup_of(Frame)),
              resend(S, Replay1)
      end.
  
  %% For the oft-repeated {next_state, opened, ...}
  -define(OPENED(S), {next_state, opened, S}).
  
  %% LOCAL makes a key from an Id created locally. REMOTE, from an Id
  %% provided by the server.
  -define(LOCAL(Id), {client, Id}).
  -define(REMOTE(Id), {server, Id}).
  
  opened({publish, P0}, S0 = #state{ id_counter = NextId,
                                     replay = Replay }) ->
  
negative.code: %% the first of two acknowledgments.
  opened({frame, #pubrec{ message_id = Id }}, S0) ->
      #state{ replay = Replay } = S0,
      #publish{} = check_replay(Id, Replay),
      Ack = #pubrel{ message_id = Id },
      %% NB update: we've passed phase one (publish -> pubrec) of the
      %% delivery, so the replay if any will be phase two (pubrel ->
      %% pubcomp)
      Replay1 = replace_replay(Id, Ack, Replay),
      write(S0, Ack),
      ?OPENED(S0#state{ replay = Replay1 });
  
  