function [image_number] = find_image_closest_to_mean (images, image_width, number_of_images, type, distance_type)
% FIND_IMAGE_CLOSEST_TO_MEAN: Find the image closest to the mean image
%
%    GENERAL
%
%      [image_number] = find_image_closest_to_mean (images)
%
%    INPUT/S
%
%      -images:
%            All the images.
%
%      -image_width:
%            The width of the images.
%
%      -number_of_images:
%            The number of images.
%
%      -type:
%            Allows other (inverse) operations.
%
%      -distance_type:
%            The way to meausre distance from the mean.
%           
%    OUTPUT/S
%
%      -image_number:
%           The number of the image closest to the mean.
%
%    PENDING WORK
%
%      -
%
%    KNOWN BUG/S
%
%      -None.
%
%    COMMENT/S
%
%      -
%
%    RELATED FUNCTION/S
%
%      
%
%    ABOUT
%
%      -Created:     May 1st, 2004
%      -Last update: May 1st, 2004
%      -Revision:    0.0.1
%      -Author:      R. S. Schestowitz, University of Manchester
% ==============================================================
for current_image_number = 1:number_of_images,   
	for i = 1:image_width - 1,
      if (images(i, current_image_number) == 0 & images(i + 1, current_image_number) ~= 0)
        lo(current_image_number) = i;
      elseif (images(i, current_image_number) ~= 0 & images(i + 1, current_image_number) == 0)
        hi(current_image_number) = i;
      end
	end
end

mean_low = mean(lo);
mean_high = mean(hi);

for current_image_number = 1:number_of_images,
   switch distance_type,
       case 'absolute_values'    
         distance_measure(current_image_number) = abs(mean_low - lo(current_image_number)) ...
          + abs(mean_high - hi(current_image_number));
       case 'sum_of_squared_distances'
         distance_measure(current_image_number) = (mean_low - lo(current_image_number)).^2 ...
          + (mean_high - hi(current_image_number)).^2;
       otherwise
         error('Unknown distance type.');
   end
end

% OPTIMISATION NOTE: In the above, very many identical tests are run for
% all images.

if (strcmp(type,'closest')),
  required_distance = min (distance_measure);
elseif (strcmp(type,'farthest')),
  required_distance = max (distance_measure);
end

for current_image_number = 1:number_of_images,
  if (distance_measure(current_image_number) == required_distance),
      image_number = current_image_number;
  end
end  
