% EYEFINDER find eyes in given images
%   F = eyefinder(IMG) finds both eyes in the frontal faces in IMG
%        where IMG is the image to perform search, can be path name or a 
%        pre loaded image
%   F = eyefinder(IMG, P1, P2, ...)
%     where P1, P2, ... are optional parameters which may take on the
%     following values:
%      'show_results' to display the results when finished
%      'fast' to use the faster face detector 
%         (NOTE: interaction with eye detector not well tested, but it seems fine to me)
%      'images_in_sequence' -- restrict search region to a neighborhood near previous 
%         face detections.  Repeated misses will grow the region.  Resets to full
%         image search after five consecutive misses.
%
%   F is an array of sructs, where each row contains the face's
%   x, y, scale, and a vector of structs for each eye.  Each eye has fields
%   x, y, scale, activation, and flag.
%
%   This function makes use of the mp_eyefinderMex mex file, which must
%   be compiled with the eyefinder project.
function [F] = eyefinder(img, varargin)
  if nargin < 1
    error('Image must be specified')
  end
  if nargout < 1
    error('At least one output is needed')
  end
%  vararginSize = size(varargin,2);

  %defaults
  showResults=0;
  use_ada_facedetector = 1;
  images_in_sequence=0;
  
  %get options
  if nargin > 1
    for n=1:size(varargin,2)
      if (isstr(varargin{n}))
        switch varargin{n}
          case 'show_results'
            showResults=1;
          case 'images_in_sequence'
            images_in_sequence=1;
      	  case 'fast'
      	    use_ada_facedetector=0;
        end
      end
    end
  end

%  M = [];
%  if ischar(img)
%    [img, M] = imread(img);
%  elseif ~isnumeric(img)
%    error('First argument must be an image or image filename')
%  end
  
  % set display image
  true_img = [];
  if showResults
    true_img=img;
  end
  
  % make grayscale
%  if ndims(img) == 3
%    img = single(rgb2gray(img));
%  elseif ~isempty(M)
%    img = single(ind2gray(img,M));
%  end

  [F] = mp_eyefinderMex(img, use_ada_facedetector, images_in_sequence);
  
  if showResults
    imshow(true_img, 'InitialMagnification','fit');
    for i=1:size(F,1)
      p = rectangle('Position', [F(i).x F(i).y F(i).size F(i).size]);
      eyewidth = F(i).size*.04;
      shift = eyewidth/2;
      set(p, 'EdgeColor', 'r');
      pleft = rectangle('Position', [F(i).xLeft-shift F(i).yLeft-shift eyewidth eyewidth]);
      set(pleft, 'FaceColor', 'b', 'EdgeColor', 'none');
      pright = rectangle('Position', [F(i).xRight-shift F(i).yRight-shift eyewidth eyewidth]);
      set(pright, 'FaceColor', 'b', 'EdgeColor', 'none');
    end
  end

