function value = nearestnonslipsurface( MAP, index, slipsurfacevalue)

[row, col ] = ind2sub( size( MAP), index);

halfsize = 1;

value = slipsurfacevalue;
while value == slipsurfacevalue,
    rows = row-halfsize : row+halfsize;
    cols = col-halfsize : col+halfsize ;
    
    rows = rows( rows>0 & rows<size(MAP,1));
    cols = cols( cols>0 & cols<size(MAP,2));
    
    block = ( MAP( rows, cols ) );
    block = block( block ~= slipsurfacevalue);
    
    
    blocklenghtiseven = mod( length( block(:)) ,2) == 0;
    
    if blocklenghtiseven,
        block = [block(:); 1];
    end
    
    value = median( block( : ));
%     if round(value) ~= value,
%         value = 1 ; %for an even number of values median returns the 
%     end
    halfsize = halfsize + 1;
end
