%                                 faceInfo.m
%
%                     By: Henry Chang and Ulises Robles

% ---------------------------------------------------------------------
% Gets some information of the region that might indicate a face
% This function retrieves:
% 1.-The cross-correlation value between the face region and the frontal
% face model.
% 2.-The model positioned on the face region alone
% 3.- The rectangle coordinates of the region that might indicate a
% face.
% ----------------------------------------------------------------------

function [ccorr, mfit, RectCoord] = faceInfo(mult, frontalmodel,ly,wx,cx, cy, angle)

  % Resize the frontal model according to the height and width of the region
  model_rot = imresize(frontalmodel,[ly wx],'bilinear');
   
  % Rotate the model
  model_rot = imrotate(model_rot,-angle,'bilinear'); 
  
  % Get the coordinates of the rotated image
  [l,r,u,d] = recsize(model_rot);
  
  % Generate a new image that elects only the model region
  model_rot=imcrop(model_rot,[l u (r-l) (d-u)]);  
  
  % Get rid of the boundary noise
  model_rot = clean_model(model_rot);
  bwmodel_rot = (model_rot >=1);

  % Compute the center of the rotated face model 
  [modx,mody] =center(bwmodel_rot);
 
  % Get the size of the rotated face model
  [morig, norig] = size(bwmodel_rot);
   
  % Create the grayscale image that will have the face model on it. 
  
  mfit = zeros(size(mult));
  mfitbw = zeros(size(mult));
  [limy, limx] = size(mfit);
  
  % Compute the coordinates of where the face model is going to be in
  % the main image
  
  startx = cx-modx;
  starty = cy-mody;
  endx = startx + norig-1;
  endy = starty + morig-1;	  
   
  % Check for boundaries of the image
  startx = checklimit(startx,limx);
  starty = checklimit(starty,limy);
  endx = checklimit(endx,limx);
  endy = checklimit(endy,limy);
  
  % The following is to generate a new image having the same
  % size as the original one, but with the face of the model on it
  % rotated accordingly.
 
  for i=starty:endy,
   for j=startx:endx,
     mfit(i,j) = model_rot(i-starty+1,j-startx+1);
    end;
  end;

  
 % figure;
 % imshow(mfit,[0 255]);  
     
% Get the cross-correlation value between the face model and the region
% that might indicate a face in the image
ccorr = corr2(mfit,mult)

% Get the rectangle coordinates that will indicate the position of the
% face in the image
[l,r,u,d] = recsize(bwmodel_rot);
				  
% Compute the start point in x and y, as well as the width of the rectangle				    
sx = startx+l;
sy = starty+u;

% Create the rectangle coordinates and return.
RectCoord = [sx  sy (r-1) (d-u)];
 





% Auxiliar function:
% ---------------------------------------------------------------
% Verifies that the coordinate is between the image region.
function newcoord = checklimit(coord,maxval)

  newcoord = coord;
  if (newcoord<1) newcoord=1; end;
  if (newcoord>maxval) newcoord=maxval; end;
