anchor.diff:  	    exit(shutdown)
       end.
   
  +update_piece_count(X, N) when X == none ->
  +    N-1;
  +update_piece_count(_X, N) ->
  +    N.
  +
   update_with_new_piece(Index, Offset, Len, Data, GBT, N, S) ->
  -    case gb_trees:get(Offset, GBT) of
  -	{PLen, none} when PLen == Len ->
  -	    PR = lists:keyreplace(
  -		   Index, 1, S#state.piece_request,
  -		   {Index,
  -		    gb_trees:update(Offset, {Len, Data}, GBT),
  -		    N-1}),
  -	    S#state{piece_request = PR}
  +    {PLen, Slot} = gb_trees:get(Offset, GBT),
  +    PLen = Len,
  +    PiecesLeft = update_piece_count(Slot, N),
  +    PR = lists:keyreplace(
  +	   Index, 1, S#state.piece_request,
  +	   {Index,
  +	    gb_trees:update(Offset, {Len, Data}, GBT),
  +	    PiecesLeft}),
  +    case PiecesLeft of
  +	0 ->
  +	    {done, S#state{piece_request = PR}};
  +	K when integer(K) ->
  +	    {not_done, S#state{piece_request = PR}}
       end.
   
   %%--------------------------------------------------------------------
  
positive.code: 		{ok, NQ} ->
  		    {ok, S#state{request_queue = NQ}};
  		false ->
  		    % Bastard sent us something out of band, kill!
  		    error_logger:error_msg("Out of band request!~n"),
  		    stop
  	    end
      end.
  
  getorrent_requests(S) ->
      lists:flatten(lists:map(fun({Index, _, _}) ->
  					  io_lib:format("|~B|", [Index])
  				  end,
  				  S#state.piece_request)).
  
  getorrent_queues(S) ->
      lists:flatten(lists:map(
  		    fun({Index, Offset, Len}) ->
  			    io_lib:format("|~p|", [{Index, Offset, Len}])
  
negative.code: report_errornous_piece(Index, Offset, Len, S) ->
      error_logger:warning_msg(
        "Peer ~s sent us chunk ~p have no piece_request on~nRequests: ~p~n~p~n",
        [S#state.peer_id, {Index, Offset, Len}, get_requests(S), get_queues(S)]).
  
  delete_piece(Index, Offset, Len, S) ->
      case delete_piece_from_request_sets(Index, Offset, Len, S) of
  	{ok, NS} ->
  	    NS;
  	out_of_band ->
  	    S
      end.
  
  handle_store_piece(Index, S) ->
      case check_and_store_piece(Index, S) of
  	ok ->
  	    PR = lists:keydelete(Index, 1, S#state.piece_request),
  	    {ok, S#state{piece_request = PR}};
  	wrong_hash ->
  	    stop
      end.
  
  handle_update_piece(Index, Offset, Len, Data, GBT, N, S) ->
      case update_with_new_piece(Index, Offset, Len, Data, GBT, N, S) of
  	{done, NS} ->
  	    handle_store_piece(Index, NS);
  	{not_done, NS} ->
  	    {ok, NS}
      end.
  
  handle_got_chunk(Index, Offset, Data, Len, S) ->
      NS = delete_piece(Index, Offset, Len, S),
      case lists:keysearch(Index, 1, NS#state.piece_request) of
  	false ->
  	    report_errornous_piece(Index, Offset, Len, NS),
  	    stop;
  	{value, {_CurrentIndex, GBT, N}} ->
  	    handle_update_piece(Index, Offset, Len, Data, GBT, N, NS)
      end.
  
  check_and_store_piece(Index, S) ->
      case lists:keysearch(Index, 1, S#state.piece_request) of
  