anchor.diff:  write_chunks(MiddleMan, ChunkFun) ->
       MiddleMan ! {self(), gimme_data},
       receive
  -    {MiddleMan, {0, _Footers}} ->
  -        % MiddleMan ! {self(), done},
  -        ok;
  -    {MiddleMan, ChunkRecord} ->
  -        ChunkFun(ChunkRecord, ok),
  -        write_chunks(MiddleMan, ChunkFun)
  +    {MiddleMan, ChunkRecordList} ->
  +        case flush_chunks(ChunkRecordList, ChunkFun) of
  +        continue -> write_chunks(MiddleMan, ChunkFun);
  +        done -> ok
  +        end
       after 600000 ->
           exit(timeout)
       end.
  +
  +flush_chunks([], _ChunkFun) ->
  +    continue;
  +flush_chunks([{0, _}], _ChunkFun) ->
  +    done;
  +flush_chunks([Chunk | Rest], ChunkFun) ->
  +    ChunkFun(Chunk, ok),
  +    flush_chunks(Rest, ChunkFun).
   
   receive_unchunked_attachment(_Req, 0) ->
       ok;
  
positive.code: 
      % take requests from the DB writers and get data from the receiver
      N = erlang:list_to_integer(couch_config:get("cluster","n")),
      middleman_loop(Receiver, N, dict:new(), 0, []);
  
  middleman(Req, Length) ->
      Receiver = spawn(fun() -> receive_unchunked_attachment(Req, Length) end),
      N = erlang:list_to_integer(couch_config:get("cluster","n")),
      middleman_loop(Receiver, N, dict:new(), 0, []).
  
  middleman_loop(Receiver, N, Counters, Offset, ChunkList) ->
      receive {From, gimme_data} ->
          % figure out how far along this writer (From) is in the list
          {NewCounters, WhichChunk} = case dict:find(From, Counters) of
          {ok, I} ->
              {dict:update_counter(From, 1, Counters), I};
          error ->
              {dict:store(From, 2, Counters), 1}
          end,
          ListIndex = WhichChunk - Offset,
  
          % talk to the receiver to get another chunk if necessary
          ChunkList1 = if ListIndex > length(ChunkList) ->
              Receiver ! {self(), go},
              receive {Receiver, ChunkRecord} -> ChunkList ++ [ChunkRecord] end;
          true -> ChunkList end,
  
          % reply to the writer
          From ! {self(), lists:nth(ListIndex, ChunkList1)},
  
          % check if we can drop a chunk from the head of the list
          SmallestIndex = dict:fold(fun(_, Val, Acc) -> lists:min([Val,Acc]) end,
              WhichChunk+1, NewCounters),
          Size = dict:size(NewCounters),
  
          {NewChunkList, NewOffset} =
          if Size == N andalso (SmallestIndex - Offset) == 2 ->
              {tl(ChunkList1), Offset+1};
          true ->
              {ChunkList1, Offset}
          end,
          middleman_loop(Receiver, N, NewCounters, NewOffset, NewChunkList)
      after 10000 ->
          ok
      end.
  
negative.code:     fun() ->
          Middleman ! {self(), gimme_data},
          receive
              {Middleman, Data} -> iolist_to_binary(Data)
          after 600000 ->
              exit(timeout)
          end
  