% Results=function write_resultfiles(nametag,EyePosn,AUout,imNames,facefound)
%
% This function saves the CERT output variables in a .mat file
% and also writes an output matrix in tab-delimited 
% text with column labels.  It creates a matrix called Results, 
% in which each line contains the frame number and the raw output 
% of each of the 8 AU detectors, for all frames for which a face 
% was found. If you The results are written to [nametag]'out.mat' 
% and [nametag]'out.txt'.
% 
% Input:
% -nametag: String containing the first part of the output filename. A 
%  convenient nametag is the image directory name. 
% -AUout 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]. 
% -imNames is a struct containing the image names in imNames(3:end).names. 
% -Facefound is a binary vector indicating whether a face was found for 
% each image. 
%
% For CERT Version 1.0.0 the output AU's are: [1 2 4 5 10 12 14 20].


function Results=write_resultfiles(nametag,EyePosn,AUout,imNames,facefound)


%INDICATE LOCATION OF FRAME NUMBER IN FILENAME
% We need the spot of the first and last digit. 
% For filenames such as  D006_S016_face_1151.jpg
% D1=16; D2=19;
% To be more flexible, we assume the last 4 characters before the
% extension are the frame number. 
L = findstr(imNames(3).name,'.')
D1 = L-4; D2 = L-1;

%%%%% Organize Results
%Extract frame number from file name 
for i = 3:size(imNames,1) 
     name = imNames(i).name;
     frame(i-2) = str2num(name(D1:D2)); %Gets frame number here.
end

%Alternatively, number the frames 
%frame = 1:size(imNames,1)-2;

%Make results matrix:
[i,j] = find(facefound ==1); %Only analyze output when face found. 
Results = [frame(j)', AUout(j,:)];


%%%%  Save results 
%
%  The results are written to the directory containing imgdir, with 
%  filenames [nametag]'out.mat' and [nametag]'out.txt'

% Save results in matlab:
fprintf('Creating %s\n',[nametag,'out.mat']);
eval(['save ',nametag,'out.mat Results EyePosn AUout imNames facefound'])

%Create tab-delimited text file with labels.
labels = {'frame' 'AU1' 'AU2' 'AU4' 'AU5' 'AU10' ... 
         'AU12' 'AU14' 'AU20' };
filename = [nametag,'out.txt'];
fprintf('Creating %s\n', filename);
writeMatrix(Results,filename,labels);

