%%This script assumes the following:
%
%Current folder contains a nested folder
%ProjectImages>ProjectImages> all class photos (only)
%
% Photos generated by the script, capturephotos2020.py
%
% The photos: 8 of each person/ 4 non-smiling + 4 smiling
% Filenames: faceimage_firstname_lastinitial_00.png for nonsmile
%            faceimage_firstname_lastinitial_smile_00.png
% Photo filenames are created by the python script, 
% 
%       capturephotos2020.py (see file for instructions on taking pictures)
% 
% 
%%
clear all % clears workspace and command window

%load into fnames the contents ProjectImages file
fnames = dir('./ProjectImages/ProjectImages/*.png');

%assign to numpics the total number of images
numpics = size(fnames,1); 

%assign to numindv 1/8 the number of pictures
numindv=numpics/8;  % assumes 8 pictures per person

% use k as an index - it indicates the picture number in the file
k=1; 

% Consider a subset of pictures to be 8 pictures
subsetpics=[1:8];

%in groups of 8, perform the following until you've done all numpics
for n = 1:8:numpics 
    for m = subsetpics;  % use m as a counter in the subset of 8
        clear strout p; %clearing the two variables, strout and p
        
        %Load images
        % Assign to NameBase, the contents of the .name field from fnames
        NameBase=fnames(k).name; 
        
        % determine the number within character string where you hit the '.'
        A=find(NameBase == '.') 
        %NameBase(A-1)=num2str(m-1); %apparently this was useful for
        %something
        
        %read the image into p
        p = imread(fullfile('./ProjectImages/ProjectImages', NameBase)); 
        
        % If first pass, allocate memory for grayscale images
        if k ==1
            grayfaces = zeros(size(p,1),size(p,2),numindv*length(subsetpics));
        end % this creates a 3-D array of zeros to write the images into
        %
        
        %converts p from color (rgb) to gray scale and stores it in grayfaces
        grayfaces(:,:,k) = rgb2gray(p); 
        
        [strout] = strsplit(NameBase,'_'); %parse file name
        %y.name(k) = strcat(strout(2),'_',strout(3), '_', strout(4)); %Record name for face
        %y.name(i) = strout(2);
        
        [strout2] = strsplit(strout{4},'.');
        
        y.picnum(k) = m; %Assigns a picture number of 1 - 8 to the pictures
        y.smile(k) = m > 4; % pictures 5,6,7,8  will get a "1" to designate a smile.
        y.subj(k) = floor((n-1)/8)+1; %Assigns a number to each individual
        k=k+1; %increments k
    end
end

smile=[y.smile]'  %creates a vector of 0 (no smile) and 1 (smiles) for grayfaces
subject=[y.subj]' %creates a vector with a number associated with the individuals

% After the file has run,  you should have grayfaces file (256x256x#picts)

%save matrices to 'qea202Xfaces.mat', use X to indicate year
save('qea202Xfaces.mat','grayfaces', 'smile','subject')