function [new_image] = focus_brain(image, threshold)
% FOCUS_BRAIN: Brain-specific focus (cropping)
%  -- Crop background where threshold condition is met --
%
%    GENERAL
%
%      [new_image] = focus_brain(image, threshold)
%
%    INPUT/S
%
%      -Omitted
%
%    OUTPUT/S
%
%      -Omitted
%
%    PENDING WORK
%
%      -
%
%    KNOWN BUG/S
%
%      -None.
%
%    COMMENT/S
%
%      -Note: very inefficient
%
%    RELATED FUNCTION/S
%
%      
%
%    ABOUT
%
%      -Created:     February 2005
%      -Last update: March 15th, 2005
%      -Revision:    0.0.1
%      -Author:      R. S. Schestowitz, University of Manchester
% ==============================================================


reverse_condition = 0;

buffer = 0;

  % the minimum value for a pixel to be considered as synthesis frame

if (threshold < 0), % reverse the condition
    threshold = 0 - threshold;
    reverse_condition = 1;
end

still_looking = 1;

image_dim1 = size(image,1);
image_dim2 = size(image,2);

for i=1:image_dim1,
    for j=1:image_dim2,
       if (reverse_condition),
          if (image(i,j) < threshold && still_looking),
           start_height = i+buffer;
           still_looking = 0;
          end
       else
          if (image(i,j) > threshold && still_looking),
           start_height = i+buffer;
           still_looking = 0;
          end
       end
    end
end    

still_looking = 1;

for i=1:image_dim2,
    for j=1:image_dim1,
       if (reverse_condition),
          if (image(j,i) < threshold && still_looking),
           start_width = i+buffer;
           still_looking = 0;
          end
       else
          if (image(j,i) > threshold && still_looking),
           start_width = i+buffer;
           still_looking = 0;
          end
       end 
    end
end    

still_looking = 1;

for i=image_dim1:-1:1,
    for j=image_dim2:-1:1,
       if (reverse_condition),
          if (image(i,j) < threshold && still_looking), 
           end_height = i-buffer;
           still_looking = 0;
          end
       else
          if (image(i,j) > threshold && still_looking),
           end_height = i-buffer;
           still_looking = 0;
          end
       end
    end
end  

still_looking = 1;

for i=image_dim2:-1:1,
    for j=image_dim1:-1:1,
       if (reverse_condition),
          if (image(j,i) < threshold && still_looking), 
           end_width = i-buffer;
           still_looking = 0;
          end
       else
          if (image(j,i) > threshold && still_looking),
           end_width = i-buffer;
           still_looking = 0;
          end
       end
    end
end

new_height = end_height - start_height;
new_width = end_width - start_width;

for i=1:new_height,
    for j=1:new_width,
       new_image(i,j) = image (i + start_height, j + start_width);
    end
end

% Tests:
% image4=imread('I_016.jpg');image3=crop_frame(image4,15); image5=focus_brain(image3,-120);imshow(image3);