%COMP 256 Assignment 1
%Adrian Ilie

function [ambimage,imarray,lightdirs] = myLoadFaceImages(Nimages,startx,starty,width,height)
% [ambimage,imarray,lightdirs] = LoadFaceImages([Nimages])
% Load the set of face images.  
% The routine returns
% 		ambimage:  width x height image illuminated under the ambient lighting
%		imarray: a 3-D array of images, width x height x Nimages
% 		lightdirs: 3 x Nimages array of light source directions
% To use:  The routine uses a gui to let the user specify where the face
% images reside in the file directory.  Just select any of the face images.
% If you get the error 'OUT OF MEMORY', reduce Nimages, or increase your swap space.
	
[filename,pathname]=uigetfile('yale*.pgm','Select any face image');
d = dir([pathname,'yale*.pgm']);
filenames = {d(:).name};
filestr = cell2struct(filenames,'names',1);
filenames = struct2cell(filestr);

ambimage = getpgmraw([pathname filenames{Nimages+1}]);
ambimage = double(ambimage(starty:starty+height-1,startx:startx+width-1));
imarray = zeros(height,width,Nimages);

for j=1:(Nimages),
	m = findstr(filenames{j},'A')+1;
	Ang(1,j) = str2num(filenames{j}(m:(m+3)));
	m = findstr(filenames{j},'E')+1;
	Ang(2,j) = str2num(filenames{j}(m:(m+2)));
	[im,maxgray(j)]= getpgmraw([pathname filenames{j}]);
	imarray(:,:,j) = double(im(starty:starty+height-1,startx:startx+width-1));
end

[X,Y,Z]= sph2cart(pi*Ang(1,:)/180,pi*Ang(2,:)/180,1);
lightdirs = [Y;Z;X];
