%
% GetBlock.m
%
% gets a square block of size (blocksize), with the specified
% top-left corner (r,c)
%

function block = GetBlock(I, r, c, blocksize)

% check if block is within bounds
[numR, numC] = size(I);
if ((r>=1) & (c>=1) & ...
	(r+blocksize-1<=numR) & (c+blocksize-1<=numC))

  % we can do it the easy way
  block = I(r:r+blocksize-1, c:c+blocksize-1);
  
else

  % we have to do it the slow way
  block = zeros(blocksize);
  for i=1:blocksize
	for j=1:blocksize
	  
	  rCurr = r+i-1;
	  cCurr = c+j-1;
	  if (rCurr < 1)
		rCurr = 1;
	  elseif (rCurr > numR)
		rCurr = numR;
	  end
	  if (cCurr < 1)
		cCurr = 1;
	  elseif (cCurr > numC)
		cCurr = numC;
	  end
	
	  block(i,j) = I(rCurr, cCurr);
	  
	end
  end
  
end
