function [avg_grayim avg_colorim std_grayim] = part2code(setname)
% input 
% setname: string type to designate the directory where to store images.
% (in my case, setname is either 'set1' or 'set2'.)
% output
% avg_grayim : an image averaged over gray-scale images in the directory
% avg_colorim : an image averaged over color images in the directory
% std_grayim : an image storing standard deviatation over gray-scales
% images in the directory

% extract filenames in the directory
filelist = dir([setname '/*.jpg']);
% read total number of files in the directory
nfiles = length(filelist);
% read image information (esp. width and height) in the directory
img_info = imfinfo([setname '/' filelist(1).name]);

% allocate buffers to hold images in the directory
gray_imgs_buffer = zeros(img_info.Height, img_info.Width, nfiles, 'uint8');
color_imgs_buffer = zeros(img_info.Height, img_info.Width, 3, nfiles, 'uint8');

% read images in the directory and store them in the buffer
for i = 1 : nfiles
    imname = [setname '/' filelist(i).name];
    im = imread(imname);
    gray_imgs_buffer(:,:,i) = rgb2gray(im);
    color_imgs_buffer(:,:,:,i) = im;
end

% compute average and std for gray images
avg_grayim = mean(gray_imgs_buffer, 3);
std_grayim = std(double(gray_imgs_buffer), 0, 3);
% compute average for color images
avg_colorim = mean(color_imgs_buffer, 4);
% display
subplot(1,3,1); 
imshow(avg_grayim./255); % By default, double type image has a display range between
                         % 0 and 1 for imshow.
                         % Otherwise, we need to explicitly set the display range like 
                         % imshow(avg_grayim, [0 255])
title('averaged gray image');
subplot(1,3,2);
imshow(std_grayim, []); % adjust image display within the range [min max] of std_grayim
title('std of gray images: rescaled display range');
subplot(1,3,3);
imshow(avg_colorim./255);
title('averaged color image');

