% function [EyePosn,Yout,r,facefound]=CERT_restart(imgdir,i_last,EyePosn,Yout,r,facefound)
%
% Restarts CERT if it crashes. First load temp.out.
% 
% Cert reads a directory of images and automatically detects faces and
% facial actions in each image. 
%
% Input: imgdir is a string containing the name of the image directory.
%
% Output: Yout is a matrix containing the AU detector output. Each row 
% is a frame and each column is the output of one of the AU detectors. 
% eyeposn is a matrix containing eye detector output. Each row is a frame
% and the columns are [left_x left_y right_x right_y]. 
% r is a struct containing the image names in r(3:end).names. 
% Facefound is a binary vector indicating whether a face was found for 
% each image. 
%
% This is CERT Version 1.0.0
% It detects 8 AU's: [1 2 4 5 10 12 14 20]


function [EyePosn,Yout,r,facefound]=CERT_restart(imgdir,i_last,EyePosn,Yout,r,facefound)

startingDir = pwd;
%cd (imgdir)
%r=dir;
%cd (startingDir)

% get parameters
  
%Load weights for eye detector and for SVMs
load GentleEye_eyeDist_eyeCentered.mat  
load SVMweights9_21_05.mat
g=[1 2 4 5 10 12 14 20];%list of AU's for this classifier
Nx=96;ns=1;nf=9;

% step through frames

for i=i_last:size(r,1)
  fprintf(1,'Processing image %5d\n%s\n',i-2,r(i).name );
  
  % read in image and detect eye positions
  origimg = imread([imgdir,'/',r(i).name]);
  origimg=rgb2gray(origimg);	  
  img = double(origimg)./255;
  F = eyefinder(img,ci);
  if(size(F,1)>0)
    xl=F(1).xLeft;
    yl=F(1).yLeft;
    xr=F(1).xRight;
    yr=F(1).yRight;
  else
    xl=0;xr=0;yl=0;yr=0;
    facefound(i-2)=0;
  end
  EyePosn(i-2,:)=[xl yl xr yr];
 

  % If there is a good candidate face ...
  % (Criteria are eye x-positions are nonzero and at least 50 pix apart.)
  if((xl*xr)~=0&xl-xr>50)
  facefound(i-2)=1;

    % get a patch Nx-by-Nx with eyes aligned
    pat= align_eyes(img,Nx,xl,xr,yl,yr);
  
    % generate au codes based on Gabor filters and SVM weights
    yhat=zeros(1,size(W,4));
    for ni=ns:nf
        for mu=1:8
            gx=Gabor_jetF(pat,Nx,Nx,ni-3,mu-1);%full Gabor filter
            yhat=yhat+gx*squeeze(W(ni,mu,:,:));%linear svm weight
        end
    end
    Yout(i-2,:)=yhat;
 
  else  %If no face was found put zeros. 
     Yout(i-2,:)=zeros(1,size(W,4));
     facefound(i-2)=0;
  end

     if (mod(i,100)==0)
        cmd = 'save temp_out EyePosn Yout r imgdir facefound i';
	%cd (startingDir);
        eval (cmd);
        %cd(imgdir);
     end
    
end

  
  
  
  
  
  
