%function [pat]= align_eyes(img,Nx,xl,xr,yl,yr);
%img = image, Nx = patch size, xl,xr,yl,yr = eye positions
function [pat]= align_eyes(img,Nx,xl,xr,yl,yr)
  
d_eye=floor(Nx/2);xtra=1.2;box=floor(d_eye*2.5*xtra);cr=[1:d_eye*2.5];
crx=floor(cr+(xtra-1)*d_eye*1.25);cry=floor(cr+ d_eye*(1.75*xtra-.75));
d=sqrt((xl-xr).^2+(yl-yr).^2)*xtra;     %%distance between  eyes
m=[(xl+xr)/2 (yl+yr)/2];%%middle of eyes
t=atan((yl-yr)./(xl-xr))*180/pi;     %%rotation angle ??????
%%corners based on box=2.5*d*xtra, 
x1=floor(m(1)-d*5/4+.5); x2=floor(m(1)+d*5/4+.5);
y1=floor(m(2)-d*3/4+.5); y2=floor(m(2)+d*7/4+.5);     %%eyes 25% down ?????


    si=size(img);
    X1=max(x1,1);
    X2=min(x2,si(2));
    Y1=max(y1,1);
    Y2=min(y2,si(1));    
    patch = img(Y1:Y2,X1:X2); 
 
    if (x1<1)
       patch=[zeros(size(patch,1),1-x1),patch];
    end
    if (x2>si(2))
       patch=[patch,zeros(size(patch,1),x2-si(2))];
    end
    if (y1<1)
       patch=[zeros(1-y1,size(patch,2));patch];
    end
    if (y2>si(1))
       patch=[patch;zeros(y2-si(1),size(patch,2))];
    end
    patch = [zeros(floor(d),size(patch,2));patch];
 
    patch=imrotate(patch,t,'bicubic','crop');
    patch =imresize(patch,box/size(patch,2),'bicubic');
    pat=patch(cry,crx);
    cr2=floor((size(pat,2)-Nx)/2);
    pat=pat(cr2+[1:Nx],cr2+[1:Nx]);%%cropping down from 120 to 96
  
