function [region_num] = find_region(R, info, centroids)
%
% function [region_num] = find_region(R, info, centroids)
%
% This function takes in a NxMxP matrix, where the P denotes the number of
% layers in this (mask) matrix. The second parameter info, is a structure
% for an ellipse. The centroids are the centroids of the regions defined in
% R. NOTE: that centroids are in the format [y, x] and info.Centroid [x, y]
% so we flip centroids in here.
%
% The function returns the region number that the centroid of info falls
% in.
%
% Dr. A. I. Hanna (2006)
region_num = [];
if nargin < 3
    return;
end
% Remember that centroids came from an image, so it has the form [y, x],
% flip it here.
%centroids = fliplr(centroids);
% figure(1); clf; hold on;
% imagesc(R);
% plot(centroids(:,1), centroids(:,2), 'o');
% plot(info.Centroid(1), info.Centroid(2), 'wx');
% 
% axis image;
% If the centroid of the ellipse in question is slightly outside the mean
% shape, then find the Euclidean distance of the centroid to the other
% centroids and choose the minimum.
if (round(info.Centroid(2)) > size(R,1))  || round(info.Centroid(1))>size(R,2)
    d = sqrt(sum((centroids - ones(size(centroids,1),1)*info.Centroid).^2,2));
    [v, p] = min(d);
    region_num = p;
    return;
end
% if the centroid is not bigger than the image, find out the region it is
% within the image.
ci = round(info.Centroid);
region_num = R(ci(2), ci(1))-1;
if region_num<1
    region_num = -1;
    d = sqrt(sum((centroids - ones(size(centroids,1),1)*info.Centroid).^2,2));
    [v, p] = min(d);
    region_num = p;
end
region_num = region_num(1);
return