% weighted_average
% INPUT
%	im - color images in 4D array
%	image - output image 

function image = weighted_average(im, n)

%for each rgb value in each pixel
for i = 1:size(im, 2)
    for j = 1:size(im, 3)
        for k = 1:3
            total = 0;
            total_weight = 0;
            for l = 1:n
                %get the value from all frames
                temp(l) = im(l, i, j, k);
            end
            %sort in ascending order
            temp = sort(temp);
            for l = 1:n
                %weight is assigned according to a hat function centered
                %at the center value
                if l < ceil(n/2)
                    total = total + (l*2 - 1)*temp(l);
                    total_weight = total_weight + (l*2 - 1);
                else
                    total = total + ((n-l)*2 + 1)*temp(l);
                    total_weight = total_weight + (n - l)*2 + 1;
                end
            end
            image(i, j, k) = total/total_weight;
            
        end
    end
end

%cast the image to uint8 so it's between 0 and 255

image = uint8(image);
imshow(image);
imwrite(image, 'final.jpg');
end